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

无法在Jenkins动态选项下拉列表中列出AWS ECR镜像标签

解决Jenkins动态下拉列表无法加载AWS ECR仓库的问题

问题背景

我使用以下Groovy脚本在Jenkins动态选项下拉列表中展示AWS ECR仓库选项:

def profile = "ecr"
def region = "us-east-1"
def cmd_output = "aws ecr describe-repositories --profile $profile --region $region --output yaml".execute()
def awk_cmd_output = cmd_output | ['awk', '/repositoryName:/ {print $2}'].execute()
def repo_names = awk_cmd_output.text.tokenize().reverse()
return repo_names

在Linux Shell中执行对应命令aws ecr describe-repositories --profile ecr --region us-east-1可正常返回ECR仓库列表,但通过aws configure修改AWS凭证后,Jenkins中的下拉列表功能失效。已在安全设置中添加归属权限组的IAM API用户,仍无法列出镜像版本。脚本运行方式为Jenkins的动态参数(Active Choices Parameter)。

排查与解决步骤

1. 确认Jenkins运行用户的AWS凭证

Jenkins默认以jenkins用户运行,你通过aws configure修改的可能是其他用户(如root)的凭证,Jenkins进程无法读取:

  • 切换到Jenkins运行用户:sudo su - jenkins
  • 重新配置目标profile的凭证:aws configure --profile ecr,输入新的Access Key ID、Secret Access Key、区域等信息
  • 测试命令有效性:aws ecr describe-repositories --profile ecr --region us-east-1,确保能正常返回仓库列表

2. 检查IAM用户权限

确保IAM用户拥有必需的ECR权限,至少包含ecr:DescribeRepositories(列出仓库),若需列出镜像版本还需ecr:DescribeImages。示例权限策略:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecr:DescribeRepositories",
                "ecr:DescribeImages"
            ],
            "Resource": "*"
        }
    ]
}

3. 优化Groovy脚本(提升稳定性)

原脚本依赖shell管道和awk,易受环境变化影响,改用Groovy直接解析JSON输出更可靠:

def profile = "ecr"
def region = "us-east-1"

// 执行AWS命令并等待完成
def proc = ["aws", "ecr", "describe-repositories", "--profile", profile, "--region", region, "--output", "json"].execute()
proc.waitFor()

// 捕获命令执行错误
if (proc.exitValue() != 0) {
    throw new Exception("AWS命令执行失败: " + proc.err.text)
}

// 解析JSON获取仓库名称
def json = new groovy.json.JsonSlurper().parseText(proc.text)
def repoNames = json.repositories.collect { it.repositoryName }

// 保持原逻辑的列表反转
return repoNames.reverse()

该脚本直接调用AWS CLI的JSON输出,用Groovy内置工具解析,避免了shell兼容性问题,同时能明确抛出错误信息,便于排查。

4. 验证Jenkins用户的AWS配置文件权限

AWS凭证默认存储在用户家目录的.aws/文件夹下,Jenkins用户的对应路径通常是/var/lib/jenkins/.aws/:

  • 检查文件权限:ls -l /var/lib/jenkins/.aws/,确保jenkins用户对credentials和config文件有读取权限
  • 若使用自定义环境变量(如AWS_SHARED_CREDENTIALS_FILE),确认路径正确且权限达标

5. 在Jenkins脚本控制台测试

通过Jenkins的脚本控制台(Manage Jenkins -> Script Console)运行测试脚本,快速定位问题:

def proc = ["aws", "ecr", "describe-repositories", "--profile", "ecr", "--region", "us-east-1"].execute()
proc.waitFor()
println "命令输出: " + proc.text
println "错误信息: " + proc.err.text

根据输出的错误提示(如凭证无效、权限不足)针对性解决问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:43:15