使用IAM角色使用Python连接到Redshift [英] Connect to Redshift using Python using IAM Role

查看:217
本文介绍了使用IAM角色使用Python连接到Redshift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用sqlalchemy和psycopg2将python连接到redshift。

I'am using sqlalchemy and psycopg2 to connect python to redshift.

engine = create_engine('postgresql://user:password@hostname:port/database_name')

我想避免使用密码连接到redshift

I want to avoid using my password to connect to redshift and using IAM Role.

推荐答案

AWS提供了一种方法来请求临时凭据以访问Redshift集群。 Boto3实现 get_cluster_credentials ,使您可以执行以下操作。确保您已遵循以下此处的说明设置您的IAM用户和角色。

AWS offers a way to request temporary credentials for access to Redshift clusters. Boto3 implements get_cluster_credentials, allowing you to do something like the following. Ensure that you have followed the instructions here on setting up your IAM Users and Roles.

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.')

这篇关于使用IAM角色使用Python连接到Redshift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆