Vasyl Stepulo
Vasyl Stepulo

Reputation: 1623

Not able to pass variables from Jenkins pipeline's script part to Ansible playbook

I have a problem with a partial pass of variables from Jenkins pipeline to Ansible playbook.

My variables in pipeline:

pipeline {
agent {
    label agentLabel
}
parameters {
    string(
        defaultValue: 'build/promo-api.zip',
        description: 'name and path of the artifact',
        name: 'ARTIFACT_ZIP')
    string(
        defaultValue: 'qa-promoapi-mbo.example.com',
        description: 'name and path of the vhost QA',
        name: 'QA_NGINX_VHOST')
}
stages {
        [...]
    stage ('Deploy') {
        steps {
            script {
                if (env.DEPLOY_ENV == 'staging') {
                    echo 'Run LUX-staging build'
                    def ENV_SERVER = '192.168.1.30'
                    def UML_SUFFIX = 'stage-mon'
                    sh 'ansible-playbook nginx-depl.yml --limit 127.0.0.1'                  
                    
                    echo 'Run STAGE SG deploy'
                    ENV_SERVER = 'stage-sg-mbo-api.example.com'
                    UML_SUFFIX = 'stage-sg'
                    sh 'ansible-playbook nginx-depl.yml --limit 127.0.0.1'                                              
                } else {
                    echo 'Run QA build'
                    def ENV_SERVER = '192.168.1.28'
                    def UML_SUFFIX = 'qa'
                    sh "ansible-playbook nginx-depl.yml --limit 127.0.0.1"  
                }
            }
        }
    }
}

Using this command I'm able to see in Ansible scope variables, defined in parameters part - ARTIFACT_ZIP and QA_NGINX_VHOST:

  tasks:
    - name: "Ansible | List all known variables and facts"
      debug:
        var: hostvars[inventory_hostname]

Problem is that I cannot pass variables from the script part - ENV_SERVER and UML_SUFFIX (these variables are unique to each server and must be changed accordingly).

In playbook vars are defined like this:

vars:
  params_ENV_SERVER: "{{ lookup('env', 'ENV_SERVER') }}"
  params_ARTIFACT_ZIP: "{{ lookup('env', 'ARTIFACT_ZIP') }}"
  params_STG_NGINX_VHOST: "{{ lookup('env', 'STG_NGINX_VHOST') }}"
  params_UML_SUFFIX: "{{ lookup('env', 'UML_SUFFIX') }}"

How to define variables correctly, to pass to Ansible playbook from Jenkins pipeline script block?

Upvotes: 1

Views: 1612

Answers (1)

guido
guido

Reputation: 19224

To make the env variables available to the bash task that executes ansible, you can use the withEnv step as follows:

[...]
script {
   if (env.DEPLOY_ENV == 'staging') {
       echo 'Run LUX-staging build'
       withEnv(["ENV_SERVER=192.168.1.30","UML_SUFFIX=stage-mon"]) {
           sh 'ansible-playbook nginx-depl.yml --limit 127.0.0.1'                  
       }
[...]
                

Upvotes: 1

Related Questions