如何以参数方式指定docker agent?

时间:2018-01-25 00:47:33

标签: jenkins jenkins-pipeline

在Jenkins管道代码中,我们可以设置环境变量,稍后在执行不同阶段时将它们用作参数:

pipeline {
  agent any
  environment {
    MY_VAR = 'hello'
  }
  stage('Greetings') {
    steps {
      echo "Say $MY_VAR first"
      sh "./make-all-greetings"
      echo "This worked as expected!"          
    }
  }
}

但是,当将docker镜像指定为代理时,这个技巧似乎不起作用:

pipeline {
  agent any
  environment {
    MY_VAR = 'hello'
    DOCKER_IMAGE = 'python:3'
  }
  stage('Greetings') {
    steps {
      echo "Say $MY_VAR first"
      sh "./make-all-greetings"
      echo "This worked as expected!"
    }
  }
  stage('Build in docker') {
    agent {
      image "$DOCKER_IMAGE"
      reuseNode true
    }
    steps {
      echo "Who cares... Pipeline breaks"
    }
  }
}

它失败了:

groovy.lang.MissingPropertyException: No such property: DOCKER_IMAGE for class: groovy.lang.Binding
  at groovy.lang.Binding.getVariable(Binding.java:63)
  at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:242)
  at org.kohsuke.groovy.sandbox.impl.Checker$6.call(Checker.java:284)
  ...

更新

声明image "${env.DOCKER_IMAGE}"确实有助于不立即破坏,但agent声明部分似乎没有看到相同的环境steps

[job-name] Running shell script
+ docker inspect -f . null

Error: No such object: null
[Pipeline] sh
[job-name] Running shell script
+ docker pull null
Using default tag: latest
Error response from daemon: pull access denied for null, repository does not exist or may require 'docker login'
  • 我试图做的是非法的吗?
  • 如果是这样,为什么?
  • 我对docker agent的参数选择有哪些选择?

1 个答案:

答案 0 :(得分:0)

知道了...不确定我对此感到高兴,但是让它发挥作用,只是我想知道为什么它必须这么难......

尝试:

pipeline {
  agent any
  environment {
    MY_VAR = 'hello'
    DOCKER_IMAGE = 'python:3'
  }
  stage('Greetings') {
    steps {
      echo "Say $MY_VAR first"
      sh "./make-all-greetings"
      echo "This worked as expected!"
    }
  }
  stage('Build in docker') {
    agent {
      image '$DOCKER_IMAGE'
      reuseNode true
    }
    steps {
      echo "Who cares... Pipeline breaks"
    }
  }
}

是的,它的反直觉,但引号成了伎俩。