【问题标题】:Jenkins pass variable out of script section詹金斯将变量传递出脚本部分
【发布时间】:2021-06-17 06:39:08
【问题描述】:

我正在尝试创建一个创建 EC2 实例的管道,并且我想在其上执行一些 shell 命令。

Terraform 应用计划后,AWS 创建新实例:

  1. 构建 [尚无关于公共 IP 的信息]
  2. 暂存 [尚无关于公共 IP 的信息]

在计划阶段无法检索公共 ipv4 信息,因此我创建了该结构:

stage ('Running command on a Build server') {
            steps {
                script {
                    BUILD_INSTANCE_IP = sh (
                        script: """
                        aws --region eu-central-1 ec2 describe-instances --filter \
                        "Name=instance-state-name,Values=running" --query \
                        "Reservations[*].Instances[*].[PublicIpAddress, Tags[?Key=='Name'].Value|[0]]" \
                        --output text | grep Build | cut -f1 //retrieve 'Build' instance IP
                        """, returnStdout: true
                        ).trim()
                        sleep time: 3, unit: 'MINUTES' // wait 3 minutes until instance will be available to connect
                        sh ( script: """ssh -i ${AWS_KEY} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ubuntu@${BUILD_INSTANCE_IP} touch /home/ubuntu/test.txt""", returnStdout: true ).trim()

所以,这里我需要通过 sshagent {} 指令连接到实例,但是 Jenkins 移动到新的部分后,变量 1 的数据被重置为零。

如何制作一个不会改变的变量?

【问题讨论】:

    标签: jenkins amazon-ec2 terraform


    【解决方案1】:

    我相信这个例子会对你有所帮助,如何在整个管道的阶段使用或重用变量

    def x
    node() {
        stage('shell') {
            x = sh(script: "echo 10", returnStdout: true) as int // needed to convert from String to int
            print x // result = 10
        }
        stage('groovy') {
            x = x + 10
            print x // result = 20
        }
    }
    
    

    【讨论】:

    • 这个解决方案不适用于我之前写的 SSH 连接。不过谢谢你的回答。
    • 你试过执行我的例子吗?并且它不与代理一起使用您的意思是通过 ssh 连接?
    • 我尝试将您的示例与我的需求混合在一起,最后它的工作方式如下: def x node() { stage ('shell') { sh("""ssh root@${env.x } cat /etc/os-release""") } } 在所有其他情况下,变量 x 的内容都是空的。不过感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    相关资源
    最近更新 更多