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

Jenkinsfile中能否从shell脚本内向Groovy变量赋值?

实现方案

核心逻辑是使用Jenkins sh 步骤的returnStdout: true参数捕获shell命令的标准输出,处理后直接写入循环外定义的Groovy列表/Map变量即可。

1. 赋值给Groovy List示例

def functionName() {
    // 循环外部定义List变量
    def awsResultList = []
    // 示例循环遍历的数据源:3个AWS区域
    def regions = ["cn-north-1", "cn-northwest-1", "ap-southeast-1"]

    for (region in regions) {
        // 捕获aws cli命令的输出,trim()去掉首尾多余的换行、空白符
        def vpcCount = sh(
            script: """
                # 这里替换为你自己的aws cli逻辑,示例为查询指定区域的VPC数量
                aws ec2 describe-vpcs --region ${region} --query 'length(Vpcs[*])' --output text
            """,
            returnStdout: true
        ).trim()
        
        // 将结果写入外部List
        awsResultList.add([
            "region": region,
            "vpcCount": vpcCount as Integer
        ])
    }

    // 循环结束后可直接使用该List
    println "全区域VPC查询结果:${awsResultList}"
    return awsResultList
}

2. 赋值给Groovy Map示例

def functionName() {
    // 循环外部定义Map变量
    def awsResultMap = [:]
    def regions = ["cn-north-1", "cn-northwest-1", "ap-southeast-1"]

    for (region in regions) {
        def runningInstanceIds = sh(
            script: """
                # 示例:查询指定区域所有运行中EC2的实例ID,输出用空格分隔
                aws ec2 describe-instances --region ${region} --filters Name=instance-state-name,Values=running --query 'Reservations[*].Instances[*].InstanceId' --output text | tr '\\n' ' '
            """,
            returnStdout: true
        ).trim()
        
        // 将结果写入外部Map
        awsResultMap[region] = runningInstanceIds.split(" ")
    }

    println "各区域运行中EC2实例ID:${awsResultMap}"
    return awsResultMap
}

注意事项

  • 如果shell命令需要返回多个值,可以约定分隔符(比如逗号、竖线),捕获输出后用split()方法拆分后再存入对应变量
  • 需要判断命令是否执行成功的场景,可以额外添加returnStatus: true参数获取命令退出码,非0值代表执行异常
  • 如果是在声明式流水线的steps块中使用上述逻辑,需要包裹在script{ }块内
  • 提前给Jenkins执行agent配置好对应AWS操作的IAM权限,避免命令执行失败返回空值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:06:03