步骤1:在AWS lambda上打开需要访问redshift的角色,并为该角色添加AmazonRedshiftFullAccess策略。
步骤2:在AWS lambda对应的VPC中配置一个安全组,将安全组设置为入站规则操作,允许来自AWS lambda的请求能够访问redshift。可以设置安全组规则为Source为lambda函数的安全组。当然,你也可以将其设置为为public子网中的任何地址均可进行访问。
步骤3:编写Python代码,创建一个redshift连接对象,并使用该对象进行sql操作。示例代码如下:
import psycopg2
def redshift_conn():
try:
conn=psycopg2.connect(
host="xxxxxxxxxxxxx.redshift.amazonaws.com",
port=5439,
dbname="database-name",
user="username",
password="password"
)
print("Connected to Redshift successfully")
return conn
except Exception as error:
print("Error while connecting to redshift: ", error)
raise Exception("Unable to connect to Redshift")
def lambda_handler(event, context):
conn = redshift_conn()
cursor = conn.cursor()
cursor.execute("SELECT * from table_name")
rows = cursor.fetchall()
for row in rows:
print(row)
cursor.close()
conn.close()
return {
'statusCode': 200,
'body': json.dumps('Successfully retrieved data from Redshift!')
}
在上面的示例代码中,使用psycopg2库创建连接对象,并用该对象连接到redshift进行sql操作。在lambda_handler()函数中,首先使用redshift_conn()函数创建连接对象,然后使用cursor对象执行sql查询,并遍历结果。
通过以上步骤和示例代码,你可以在AWS lambda中成功连接AWS redshift并进行SQL操作。