Pass credentials / .json file stored in S3 bucket to GoogleServiceAccountClient

Viewed 155

Here the code to initialize the GoogleRefreshTokenClient using the credentials from json key file.

oauth2_client = oauth2.GoogleServiceAccountClient(key_file, oauth2.GetAPIScope('ad_manager'))

Key_file .json is stored in S3 bucket.

Is there any way to pass .json file (with credentials) stored in s3 to GoogleServiceAccountClient?

Ps. Info to DalmTo stackoverflow member. Do not close or merge this question, please :)

1 Answers

You can read the file from S3 and write it as a json file to your /tmp folder

def readFileFromS3(file_name):
    tmp_path = "/tmp/"+file_name
    file_path = Path(tmp_path)
    if file_path.is_file():
        return tmp_path
    s3 = boto3.resource(
            's3',
            aws_access_key_id      = <AWS_ACCESS_KEY>,
            aws_secret_access_key  = <AWS_SECRET>,
            region_name            = <YOUR_REGION_NAME>
            )
    content_object = s3.Object(<BUCKET_NAME>, file_name)
    file_content = content_object.get()['Body'].read().decode('utf-8')
    json_content = json.loads(file_content)
    with open(tmp_path, 'w') as res_file:
        json.dump(json_content, res_file, indent=4)
    return tmp_path

Then use the path returned from the above function in GoogleServiceAccountClient

key_file = readFileFromS3(<key_file_name_in_s3>)
oauth2_client = oauth2.GoogleServiceAccountClient(key_file, oauth2.GetAPIScope('ad_manager'))
Related