繁体   English   中英

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

[英]Connect to Redshift using Python using IAM Role

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

AWS为python中的IAM信誉提供了不像它们的JDBC驱动程序那样方便的包装器。 您需要手动调用GetClusterCredentials端点,然后将返回的用户名和密码传递给create_engine 看起来像:

def get_redshift_credentials():
    role_creds = get_role_credentials()
    client = boto3.client(
        'redshift',
        region_name=CLUSTER_REGION,
        aws_access_key_id=role_creds['AccessKeyId'],
        aws_secret_access_key=role_creds['SecretAccessKey'],
        aws_session_token=role_creds['SessionToken'],
    )
    response = client.get_cluster_credentials(
        DbUser=PGUSER,
        ClusterIdentifier=CLUSTER_IDENTIFIER,
    )
    return response

creds = get_redshift_credentials()
engine = create_engine('postgresql://{creds.DbUser}:{creds.DbPassword}@hostname:port/database_name'.format(creds))

AWS IAM用户与Redshift数据库用户不同。 尽管Redshift是postgres的一个(非常遥远的)亲戚,但它还不允许无密码连接。

编辑:

我的答案不再适用,请查看相关代码段的其他答案。

不久前,AWS 有一个适用于 Python 的本机Redshift 连接器

它支持使用 IAM 进行连接,因为您的 IAM 凭证允许您调用get-cluster-credentials

例子:

import redshift_connector

conn = redshift_connector.connect(
    iam=True,
    database='dev',
    db_user='<username>', # the database user in call to get-cluster-credentials
    cluster_identifier='my-redshift-cluster', # identifier of your cluster
    profile='redshift_profile' # profile in ~./aws/config with correct permissions
 )

cursor = redshift_connector.Cursor = conn.cursor()
cursor.execute('SELECT 1;')

这个连接器的一个很好的特性是它使用cluster_identifier内部调用describe-clusters ,所以你甚至不需要指定主机和端口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM