2

How can I pass parameters from Jenkins to my Ansible playbook? Eg. I want to take IP address from users and pass it to the playbook so that it will execute only on those machines.

2 Answers 2

2

You can use -e switch for that purpose:

ansible-playbook -e 'foo=${FOO}'

where the FOO can be defined in the Jenkins envirionment variables. If it is defined within the parameters block of your Jenkinsfile, then you need to use ${params.foo}. Then, the value can be accessed by the Ansible playbook with {{ foo }}.

0

If you're using Jenkins Ansible plugin, Jenkins pipeline envvars (and build vars) are injected automatically into the playbooks, where they can be accessed like so:

---
- hosts: example
  tasks:
    - debug: msg="{{ lookup('env','MY_PIPELINE_ENVVAR') }}"

If you want to transit pipeline params to Ansible, you can define an environment block in your Jenkins pipeline where you convert the params to envvars simply:

pipeline {
  environment {
    MY_PIPELINE_ENVVAR = "${params.MY_PIPELINE_PARAM}"
  }
  ...
}

If you want all of your params automatically converted to envvars that are then automatically all injected via ansiblePlaybook to the playbooks, you can do something like this:

environment {
  script {
    params.each { key, value ->
      env."$key" = value
    }
  }
}

This way, if you have a params named, for example, VAR1, VAR2, and VAR3, they become envvars by the same names, and then subsequently can be accessed in the playbooks using the above-mentioned lookup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.