|
| 1 | +# Copyright 2021 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Demonstrates how to obtain short-lived credentials with identity federation.""" |
| 16 | +import json |
| 17 | +import urllib |
| 18 | + |
| 19 | +import boto3 |
| 20 | +from botocore.auth import SigV4Auth |
| 21 | +from botocore.awsrequest import AWSRequest |
| 22 | + |
| 23 | + |
| 24 | +def create_token_aws(project_id: str, pool_id: str, provider_id: str) -> None: |
| 25 | + # Prepare a GetCallerIdentity request. |
| 26 | + request = AWSRequest( |
| 27 | + method="POST", |
| 28 | + url="https://sts.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15", |
| 29 | + headers={ |
| 30 | + "Host": "sts.amazonaws.com", |
| 31 | + "x-goog-cloud-target-resource": f"//iam.googleapis.com/projects/{project_id}/locations/global/workloadIdentityPools/{pool_id}/providers/{provider_id}" |
| 32 | + }) |
| 33 | + |
| 34 | + # Set the session credentials and Sign the request. |
| 35 | + # get_credentials loads the required credentials as environment variables. |
| 36 | + # Refer: |
| 37 | + # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html |
| 38 | + SigV4Auth(boto3.Session().get_credentials(), "sts", "us-east-1").add_auth(request) |
| 39 | + |
| 40 | + # Create token from signed request. |
| 41 | + token = { |
| 42 | + "url": request.url, |
| 43 | + "method": request.method, |
| 44 | + "headers": request.headers.items() |
| 45 | + } |
| 46 | + # The token lets workload identity federation verify the identity without revealing the AWS secret access key. |
| 47 | + print("Token:\n%s" % json.dumps(token, indent=2, sort_keys=True)) |
| 48 | + print("URL encoded token:\n%s" % urllib.parse.quote(json.dumps(token))) |
| 49 | + |
| 50 | + |
| 51 | +def main(): |
| 52 | + # TODO(Developer): Replace the below credentials. |
| 53 | + project_id = "my-project-id" |
| 54 | + pool_id = "my-pool-id" |
| 55 | + provider_id = "my-provider-id" |
| 56 | + |
| 57 | + create_token_aws(project_id, pool_id, provider_id) |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + main() |
0 commit comments