Oma*_*r14 3 python postgresql sqlalchemy amazon-web-services amazon-redshift
我使用sqlalchemy和psycopg2将python连接到redshift.
engine = create_engine('postgresql://user:password@hostname:port/database_name')
Run Code Online (Sandbox Code Playgroud)
我想避免使用我的密码连接到redshift并使用IAM Role.
dan*_*lef 10
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.')
Run Code Online (Sandbox Code Playgroud)