刷新 CodeArtifact 令牌 - Amazon Managed Workflows for Apache Airflow
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

刷新 CodeArtifact 令牌

如果您使用 CodeArtifact 来安装 Python 依赖项,则 Amazon MWAA 需要有效的令牌。要允许 Amazon MWAA 在运行时访问 CodeArtifact 存储库,您可以使用启动脚本并使用令牌进行 PIP_EXTRA_INDEX_URL 设置。

以下主题介绍如何创建启动脚本,该脚本使用 get_authorization_token CodeArtifact API 操作在每次环境启动或更新时检索新令牌。

版本

  • 您可以将本页上的代码示例与 Python 3.10 中的 Apache Airflow v2 及更高版本一起使用。

先决条件

要使用本页上的示例代码,您需要以下内容:

权限

要刷新 CodeArtifact 令牌并将结果写入 Amazon S3,Amazon MWAA 的执行角色必须具有以下权限。

  • codeartifact:GetAuthorizationToken 操作允许 Amazon MWAA 从 CodeArtifact 中检索新令牌。以下策略为您创建的每个 CodeArtifact 域授予权限。您可以通过修改语句中的资源值并仅指定您希望环境访问的域来进一步限制对所有域的访问。

    { "Effect": "Allow", "Action": "codeartifact:GetAuthorizationToken", "Resource": "arn:aws:codeartifact:us-west-2:*:domain/*" }
  • sts:GetServiceBearerToken 操作是调用 CodeArtifact GetAuthorizationToken API 操作所必需的。此操作返回一个令牌,在将程序包管理器(例如 pip)与 CodeArtifact 配合使用时,必须使用该令牌。要将程序包管理器与 CodeArtifact 存储库配合使用,环境的执行角色角色必须允许 sts:GetServiceBearerToken,如以下策略声明所示。

    { "Sid": "AllowServiceBearerToken", "Effect": "Allow", "Action": "sts:GetServiceBearerToken", "Resource": "*" }

代码示例

以下步骤描述了如何创建用于更新 CodeArtifact 令牌的启动脚本。

  1. 复制以下代码示例的内容,并在本地另存为 code_artifact_startup_script.sh

    #!/bin/sh # Startup script for MWAA, see https://docs.aws.amazon.com/mwaa/latest/userguide/using-startup-script.html set -eu # setup code artifact endpoint and token # https://pip.pypa.io/en/stable/cli/pip_install/#cmdoption-0 # https://docs.aws.amazon.com/mwaa/latest/userguide/samples-code-artifact.html DOMAIN="amazon" DOMAIN_OWNER="112233445566" REGION="us-west-2" REPO_NAME="MyRepo" echo "Getting token for CodeArtifact with args: --domain $DOMAIN --region $REGION --domain-owner $DOMAIN_OWNER" TOKEN=$(aws codeartifact get-authorization-token --domain $DOMAIN --region $REGION --domain-owner $DOMAIN_OWNER | jq -r '.authorizationToken') echo "Setting Pip env var for '--index-url' to point to CodeArtifact" export PIP_EXTRA_INDEX_URL="https://aws:$TOKEN@$DOMAIN-$DOMAIN_OWNER.d.codeartifact.$REGION.amazonaws.com/pypi/$REPO_NAME/simple/" echo "CodeArtifact startup setup complete"
  2. 导航到保存该脚本的文件夹。在新提示窗口中使用 cp 将脚本上传到存储桶。用您的信息替换 your-s3-bucket

    $ aws s3 cp code_artifact_startup_script.sh s3://your-s3-bucket/code_artifact_startup_script.sh

    如果成功,Amazon S3 会输出该对象的 URL 路径:

    upload: ./code_artifact_startup_script.sh to s3://your-s3-bucket/code_artifact_startup_script.sh

    上传脚本后,环境会在启动时更新并运行脚本。

接下来做什么?