CelestialSky
CelestialSky

Reputation: 67

How to return temporary password and username using Boto3 for Redshift get_cluster_credentials

I can print the boto3.client.get_cluster_credentials and see the 'DbUser: 'IAM:#####" and 'DbPassword'###########' but not able to assign that to a variable.

I've tried to set in my connection string the DbUser and DbPassword from my function call but get error. When I hard code the actual username and password it works but I need to get what AWS returns to me as temporary credentials:

client = boto3.client('redshift', region_name='us-east-1')
cluster_creds = client.get_cluster_credentials( DbUser=',dbuser', DbName='dbName', ClusterIdentifier='ClusterName', AutoCreate=False)
conn = psycopg2.connect("host='<clusername>.<randomKey>.us-east-1.redshift.amazonaws.com' port='5439' user=cluster_cred['Dbuser'] password=cluster_creds['DbPassword'] dbname='databaseName'")

I changed the code to user=cluster_creds.DbUser and it passed however when I changed password=cluster_creds.DbPassword it failed to authenticate.

Upvotes: 0

Views: 1602

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 269081

This line is referencing variables within a string, so the value is not being substituted:

conn = psycopg2.connect("host='<clusername>.<randomKey>.us-east-1.redshift.amazonaws.com' port='5439' user=cluster_cred['Dbuser'] password=cluster_creds['DbPassword'] dbname='databaseName'")

Also, it should be cluster_creds (not cluster_cred) and DbUser (not Dbuser).

Here's code that worked for me:

import boto3
import psycopg2

DB_NAME = '<DB-NAME>'
CLUSTER_IDENTIFIER = '<CLUSTER-IDENTIFIER>'
DB_USER = '<DB-USER>'
ENDPOINT = '<DB-NAME>.<RANDOM-KEY>.us-east-1.redshift.amazonaws.com'

client = boto3.client('redshift', region_name='us-east-1')
cluster_creds = client.get_cluster_credentials(DbUser=DB_USER, DbName=DB_NAME, ClusterIdentifier=CLUSTER_IDENTIFIER, AutoCreate=False)
temp_user=cluster_creds['DbUser']
temp_password=cluster_creds['DbPassword']
conn = psycopg2.connect("host='" + ENDPOINT + "' port='5439' user=" + temp_user + " password=" + temp_password + " dbname='" + DB_NAME + "'")

If you are using Python 3.6+, then the last line can use prettier f-strings:

conn = psycopg2.connect(f"host='{ENDPOINT}' port='5439' user={temp_user} password={temp_password} dbname='{DB_NAME}'")

You will need to substitute your values for <VALUES>.

Upvotes: 2

Related Questions