1

In Jenkins pipeline code we can set environment variables and use them later as parameters when executing different stages:

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

This trick, however, doesn't seem to work when specifying a docker image as an agent:

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"
    }
  }
}

It fails miserably with:

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)
  ...

UPDATE:

Declaring image "${env.DOCKER_IMAGE}" does help with not breaking things immediately but the agent declaration section doesn't seem to see the same environment steps do:

[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'
  • Is what I'm trying to do illegal?
  • If so, why?
  • What are my options for parametric selection of docker agent?
AlexanderF
  • 919
  • 1
  • 13
  • 28
  • Have you tried `${env.DOCKER_IMAGE}`? – Vasan Jan 25 '18 at 00:59
  • @Vasan, yes, I have. It does not work either. Seems to return the environment variable as null and then fails when trying to find a docker container named "null". It seems like declaring agents happens on a different scope separate from everything else. – AlexanderF Jan 25 '18 at 17:39
  • See also https://stackoverflow.com/a/51143675/6309 – VonC Jul 02 '18 at 21:01

1 Answers1

0

Got it... Not sure I'm happy about it, but got it to work, just I wonder why it has to be so hard...

try :

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"
    }
  }
}

Yes it's counter intuitive but the quotes made the trick.

jnrg
  • 1,871
  • 1
  • 11
  • 7