我正在使用 sqlalchemy 和 psycopg2 将 python 连接到 redshift。
engine = create_engine('postgresql://user:password@hostname:port/database_name')
我想避免使用我的密码连接到 redshift 并使用 IAM 角色。
AWS 提供了一种请求临时凭证以访问 Redshift 集群的方法。 Boto3实现get_cluster_credentials
,允许您执行如下操作。确保您已遵循此处说明关于设置您的 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.')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)