AWS Glue Spark作业从CodeArtifact安装Python包:VPC镜像参数及方案
问题解答
一、VPC端点模式下的--index-url和--trusted-host配置
当通过VPC接口端点连接CodeArtifact时,无需在URL中携带临时令牌(依赖IAM角色权限认证),具体配置如下:
--index-url格式
--index-url=https://<domain-name>-<domain-owner-id>.d.codeartifact.<region>.amazonaws.com/pypi/<repo-name>/simple/
替换占位符:
<domain-name>:你的CodeArtifact域名<domain-owner-id>:域名所属的AWS账号ID<region>:CodeArtifact所在区域<repo-name>:目标仓库名称
--trusted-host配置
直接使用CodeArtifact的私有域名即可:
--trusted-host <domain-name>-<domain-owner-id>.d.codeartifact.<region>.amazonaws.com
前置条件
- 为你的VPC创建CodeArtifact接口类型VPC端点,并启用私有DNS(确保Glue作业在VPC内可以直接解析CodeArtifact的标准域名)
- 给Glue作业的IAM角色添加以下权限:
codeartifact:GetAuthorizationTokencodeartifact:ReadFromRepository- 资源范围限定为你的CodeArtifact仓库ARN:
arn:aws:codeartifact:<region>:<account-id>:repository/<domain-name>/<repo-name>
二、替代方案:解决令牌过期问题
除了VPC端点模式,还有两种更简洁的方式避免手动更新令牌:
1. 作业启动时动态获取令牌
在Glue作业代码开头,通过boto3调用CodeArtifact API获取临时令牌,动态构造pip安装命令:
import boto3 import sys from subprocess import check_call # 初始化CodeArtifact客户端 ca_client = boto3.client("codeartifact") # 获取12小时有效期的令牌 token_res = ca_client.get_authorization_token( domain="你的域名", domainOwner="你的账号ID", durationSeconds=43200 ) token = token_res["authorizationToken"] # 构造索引URL index_url = f"https://aws:{token}@你的域名-你的账号ID.d.codeartifact.你的区域.amazonaws.com/pypi/你的仓库名/simple/" # 执行包安装 check_call([ sys.executable, "-m", "pip", "install", "--index-url", index_url, "--trusted-host", "你的域名-你的账号ID.d.codeartifact.你的区域.amazonaws.com", "你的私有包名" ])
注意:需确保Glue作业的IAM角色拥有codeartifact:GetAuthorizationToken权限。
2. 将私有包上传至S3直接引用
如果你的私有包更新频率较低,可以将包文件(.tar.gz或.whl)上传至S3,然后在Glue作业参数中直接指定S3路径:
--additional-python-modules s3://你的存储桶路径/你的包文件名.tar.gz
这种方式完全绕过CodeArtifact,无需处理令牌或VPC配置,适合静态包场景。
内容的提问来源于stack exchange,提问作者teejay
相关产品推荐
相关产品推荐

