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.
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.
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.')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With