Crear un token para la federación de identidades de carga de trabajo con AWS
Organízate con las colecciones
Guarda y clasifica el contenido según tus preferencias.
Crea un token que la federación de identidades de carga de trabajo de IAM puede verificar sin revelar la clave de acceso secreta de AWS.
Investigar más
Para obtener documentación detallada que incluya este código de muestra, consulta lo siguiente:
Código de ejemplo
A menos que se indique lo contrario, el contenido de esta página está sujeto a la licencia Reconocimiento 4.0 de Creative Commons y las muestras de código están sujetas a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio web de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
[[["Es fácil de entender","easyToUnderstand","thumb-up"],["Me ofreció una solución al problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Es difícil de entender","hardToUnderstand","thumb-down"],["La información o el código de muestra no son correctos","incorrectInformationOrSampleCode","thumb-down"],["Me faltan las muestras o la información que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis code sample demonstrates how to create a token for IAM Workload Identity Federation that can be verified without using the AWS secret access key.\u003c/p\u003e\n"],["\u003cp\u003eThe token is generated by preparing and signing a GetCallerIdentity request using the boto3 library.\u003c/p\u003e\n"],["\u003cp\u003eThe generated token includes the request URL, method, and headers, which allows the Workload Identity Federation to verify the identity.\u003c/p\u003e\n"],["\u003cp\u003eTo authenticate to IAM, setting up Application Default Credentials is required, particularly within local environments.\u003c/p\u003e\n"],["\u003cp\u003eThe example uses placeholders for the project number, pool ID, and provider ID, which must be replaced with actual values.\u003c/p\u003e\n"]]],[],null,["# Create a token for Workload Identity Federation with AWS\n\nCreates a token that IAM Workload Identity Federation can verify without revealing the AWS secret access key.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Configure Workload Identity Federation with AWS or Azure VMs](/iam/docs/workload-identity-federation-with-other-clouds)\n\nCode sample\n-----------\n\n### Python\n\n\nTo learn how to install and use the client library for IAM, see\n[IAM client libraries](/iam/docs/reference/libraries).\n\n\nFor more information, see the\n[IAM Python API\nreference documentation](https://developers.google.com/api-client-library/python/apis/iam/v1).\n\n\nTo authenticate to IAM, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import json\n import urllib\n\n import boto3\n from botocore.auth import SigV4Auth\n from botocore.awsrequest import AWSRequest\n\n\n def create_token_aws(project_number: str, pool_id: str, provider_id: str) -\u003e None:\n # Prepare a GetCallerIdentity request.\n request = AWSRequest(\n method=\"POST\",\n url=\"https://sts.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15\",\n headers={\n \"Host\": \"sts.amazonaws.com\",\n \"x-goog-cloud-target-resource\": f\"//iam.googleapis.com/projects/{project_number}/locations/global/workloadIdentityPools/{pool_id}/providers/{provider_id}\",\n },\n )\n\n # Set the session credentials and Sign the request.\n # get_credentials loads the required credentials as environment variables.\n # Refer:\n # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html\n SigV4Auth(boto3.Session().get_credentials(), \"sts\", \"us-east-1\").add_auth(request)\n\n # Create token from signed request.\n token = {\"url\": request.url, \"method\": request.method, \"headers\": []}\n for key, value in request.headers.items():\n token[\"headers\"].append({\"key\": key, \"value\": value})\n\n # The token lets workload identity federation verify the identity without revealing the AWS secret access key.\n print(\"Token:\\n%s\" % json.dumps(token, indent=2, sort_keys=True))\n print(\"URL encoded token:\\n%s\" % urllib.parse.quote(json.dumps(token)))\n\n\n def main() -\u003e None:\n # TODO(Developer): Replace the below credentials.\n # project_number: Google Project number (not the project id)\n project_number = \"my-project-number\"\n pool_id = \"my-pool-id\"\n provider_id = \"my-provider-id\"\n\n create_token_aws(project_number, pool_id, provider_id)\n\n\n if __name__ == \"__main__\":\n main()\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=iam)."]]