Jenkinsfile Declarative Pipeline defining dynamic env vars

DEL picture DEL · May 9, 2017 · Viewed 69.8k times · Source

I'm new to Jenkins pipeline; I'm defining a declarative syntax pipeline and I don't know if I can solve my problem, because I didn't find a solution.

In this example, I need to pass a variable to ansible plugin (in old version I use an ENV_VAR or injecting it from file with inject plugin) that variable comes from a script.

This is my perfect scenario (but it doesn't work because environment{}):

pipeline {
  agent { node { label 'jenkins-node'}}

  stages {
    stage('Deploy') {
      environment {
        ANSIBLE_CONFIG = '${WORKSPACE}/chimera-ci/ansible/ansible.cfg'
        VERSION = sh("python3.5 docker/get_version.py")
      }
      steps {
        ansiblePlaybook credentialsId: 'example-credential', extras: '-e version=${VERSION}', inventory: 'development', playbook: 'deploy.yml'
      }
    }
  }
}

I tried other ways to test how env vars work in other post, example:

pipeline {
  agent { node { label 'jenkins-node'}}

  stages {
    stage('PREPARE VARS') {
      steps {
        script {
          env['VERSION'] = sh(script: "python3.5 get_version.py")
        }
        echo env.VERSION
      }
    }
  }
}

but "echo env.VERSION" return null.

Also tried the same example with: - VERSION=python3.5 get_version.py - VERSION=python3.5 get_version.py > props.file (and try to inject it, but didnt found how)

If this is not possible I will do it in the ansible role.

UPDATE

There is another "issue" in Ansible Plugin, to use vars in extra vars it must have double quotes instead of single.

ansiblePlaybook credentialsId: 'example-credential', extras: "-e version=${VERSION}", inventory: 'development', playbook: 'deploy.yml'

Answer

burnettk picture burnettk · May 10, 2017

You can create variables before the pipeline block starts. You can have sh return stdout to assign to these variables. You don't have the same flexibility to assign to environment variables in the environment stanza. So substitute in python3.5 get_version.py where I have echo 0.0.1 in the script here (and make sure your python script just returns the version to stdout):

def awesomeVersion = 'UNKNOWN'

pipeline {
  agent { label 'docker' }
  stages {
    stage('build') {
      steps {
        script {
          awesomeVersion = sh(returnStdout: true, script: 'echo 0.0.1')
        }
      }
    }
    stage('output_version') {
      steps {
        echo "awesomeVersion: ${awesomeVersion}"
      }
    }
  }
}

The output of the above pipeline is:

awesomeVersion: 0.0.1