Created
August 31, 2023 02:57
-
-
Save bijukunjummen/b8a6f8e3c0928a825612146ae93c6bcb to your computer and use it in GitHub Desktop.
Use federated identity to make a call from GCP to AWS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
import google.auth | |
import google.auth.transport.requests | |
import requests | |
import google.oauth2.id_token | |
auth_req = google.auth.transport.requests.Request() | |
# Get GCP Id Token, with an audience of 'gcp-aws-access' | |
credentials = google.oauth2.id_token.fetch_id_token_credentials('gcp-aws-access', request=auth_req) | |
credentials.refresh(auth_req) | |
id_token = credentials.token | |
# Use STS AWS Service to assume an AWS role, with appropriate permissions attached to it.. | |
client = boto3.client("sts") | |
# Replace role-id with the right role-arn on the AWS side.. | |
response = client.assume_role_with_web_identity( | |
RoleArn='arn:aws:iam::role-id:role/google-cloud-sa-access', | |
RoleSessionName='gcp-access', | |
WebIdentityToken=id_token | |
) | |
# Make the AWS client calls using the credentials.. | |
accessKey = response["Credentials"]["AccessKeyId"] | |
secretKey = response["Credentials"]["SecretAccessKey"] | |
sessionToken = response["Credentials"]["SessionToken"] | |
awssession = boto3.Session( | |
aws_access_key_id = accessKey, | |
aws_secret_access_key = secretKey, | |
aws_session_token = sessionToken | |
) | |
s3 = awssession.client("s3") | |
print(s3.list_buckets()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# GCP Side | |
service_account=... | |
gcloud iam service-accounts describe $service_account | |
# grab the uniqueId from above, this will be the subject of the id token | |
# AWS Side | |
subject=<uniqueId from above> | |
cat <<EOF > sample-policy.json | |
{ | |
"Version": "2012-10-17", | |
"Statement": [ | |
{ | |
"Effect": "Allow", | |
"Principal": { | |
"Federated": "accounts.google.com" | |
}, | |
"Action": "sts:AssumeRoleWithWebIdentity", | |
"Condition": { | |
"StringEquals": { | |
"accounts.google.com:sub": "$subject" | |
} | |
} | |
} | |
] | |
} | |
EOF | |
aws iam create-role \ | |
--role-name google-cloud-sa-access \ | |
--assume-role-policy-document file://assume-role-policy.json | |
# Then give the role the right permissions |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment