Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to Redshift using Python using IAM Role

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

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

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

like image 307
Omar14 Avatar asked May 29 '17 13:05

Omar14


People also ask

How do you associate IAM role with Redshift cluster?

To associate an IAM role with a clusterOn the navigation menu, choose Clusters, then choose the name of the cluster that you want to update. For Actions, choose Manage IAM roles. The IAM roles page appears. Either choose Enter ARN and then enter an ARN or an IAM role, or choose an IAM role from the list.


1 Answers

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.')
like image 186
danielchalef Avatar answered Sep 21 '22 08:09

danielchalef