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

标签 python amazon-web-services sqlalchemy amazon-redshift

我正在使用 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/

相关文章:

python - SQLAlchemy 多对多性能

python - 将 TIMIT 数据库中的 Nist Wav 文件读入 python numpy 数组

python - "Error when calling the metaclass bases"在模块内声明类时

amazon-web-services - 如何将多个单独的维度用于自定义 cloudwatch 指标?

python - 如何在 sqlalchemy 中连接两个关于公共(public)关系的查询?

python - 如何直接从sqlalchemy中的关系排序

python - django 基本分页问题

python - PyQT 终端模拟器

amazon-web-services - 当基于AWS的应用程序失败时,如何设置失败鲸鱼风格的页面?

amazon-web-services - 如何在现有的Apache Spark独立群集上安装Apache Zeppelin