使用IAM角色使用Python连接到Redshift


问题内容

我正在使用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.')