我正在使用 sqlalchemy 和 psycopg2 将 python 连接到 redshift。
engine = create_engine('postgresql://user:password@hostname:port/database_name')
我想避免使用我的密码连接到 redshift 和使用 IAM 角色。
最佳答案
AWS 提供了一种方法来请求访问 Redshift 集群的临时凭证。 Boto3 实现了 get_cluster_credentials
,允许您执行如下操作。确保您已遵循 instructions here关于设置您的 IAM 用户和角色。
def db_connection():
logger = logging.getLogger(__name__)
RS_PORT = 5439
RS_USER = 'myDbUser'
DATABASE = 'myDb'
CLUSTER_ID = 'myCluster'
RS_HOST = 'myClusterHostName'
client = boto3.client('redshift')
cluster_creds = client.get_cluster_credentials(DbUser=RS_USER,
DbName=DATABASE,
ClusterIdentifier=CLUSTER_ID,
AutoCreate=False)
try:
conn = psycopg2.connect(
host=RS_HOST,
port=RS_PORT,
user=cluster_creds['DbUser'],
password=cluster_creds['DbPassword'],
database=DATABASE
)
return conn
except psycopg2.Error:
logger.exception('Failed to open database connection.')
关于python - 使用 IAM 角色使用 Python 连接到 Redshift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44243169/