You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS Glue Job中访问AWS CodeArtifact内的Python包?

在AWS Glue Job中使用AWS CodeArtifact托管的Python包

要在Glue Job中直接从CodeArtifact安装自定义PyPI包,核心是动态获取CodeArtifact的授权凭证并配置pip源,而非依赖S3存储包文件。以下是具体实现步骤:

1. 配置Glue Job的IAM权限

确保Glue Job使用的IAM角色拥有以下CodeArtifact权限,可通过添加内联策略实现:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "codeartifact:GetAuthorizationToken",
                "codeartifact:ReadFromRepository"
            ],
            "Resource": "*"
        }
    ]
}

2. 在Glue脚本中添加包安装逻辑

在Python脚本开头加入以下代码,动态获取CodeArtifact凭证并执行pip安装:

import subprocess
import boto3
import os

# 替换为你的CodeArtifact信息
REGION = "us-east-1"
DOMAIN = "your-codeartifact-domain"
DOMAIN_OWNER = "123456789012"  # AWS账号ID
REPOSITORY = "your-pypi-repo"
PACKAGE_NAME = "your-custom-package"

# 初始化CodeArtifact客户端
ca_client = boto3.client("codeartifact", region_name=REGION)

# 获取12小时有效期的授权Token
token_resp = ca_client.get_authorization_token(
    domain=DOMAIN,
    domainOwner=DOMAIN_OWNER
)
auth_token = token_resp["authorizationToken"]

# 获取仓库的PyPI端点
endpoint_resp = ca_client.get_repository_endpoint(
    domain=DOMAIN,
    domainOwner=DOMAIN_OWNER,
    repository=REPOSITORY,
    format="pypi"
)
repo_url = endpoint_resp["repositoryEndpoint"]

# 构造带认证的pip源地址(移除http/https前缀,添加AWS凭证)
pip_index_url = f"https://aws:{auth_token}@{repo_url.split('://')[1]}"

# 执行pip安装
subprocess.check_call([
    "pip", "install",
    PACKAGE_NAME,
    "--index-url", pip_index_url,
    "--trusted-host", repo_url.split('://')[1]  # 避免SSL证书验证问题
])

# 安装完成后即可导入自定义包
import your_custom_package

关键注意事项

  • Token有效期:CodeArtifact授权Token默认有效期12小时,动态获取无需硬编码,避免凭证泄露风险。
  • Glue版本兼容:确保自定义包兼容Glue使用的Python版本(Glue 3.0+为Python 3.9)。
  • 依赖拉取:如果自定义包依赖其他PyPI包,需确保CodeArtifact仓库已代理公共PyPI,或依赖包已上传至CodeArtifact。
  • 性能优化:若Job频繁运行,可考虑将安装逻辑抽离到Glue的初始化脚本(--init-script参数),避免每次Job启动重复安装。

内容的提问来源于stack exchange,提问作者tonicebrian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 00:32:36