How to pass parameter from Jenkins job to Ansible playbook
Sat, Oct 15, 2016
Sometimes, we might need to pass parameter from a Jenkins job to our Ansible playbook, for example, release version number. On my other post, I’ve written about how to run Ansible playbook from Jenkins job. And now, I am going to show you how to pass a parameter from Jenkins job to Ansible playbook.
First, let’s prepare a simple Ansible playbook that takes a parameter and display it.
---
- hosts: localhost
vars:
- name: "John"
tasks:
- name: Print message
debug: msg="Hello to {{name}}, from Ansible!!"
And when we run it, it will use the default value for variable “name”, which is “John”
$ ansible-playbook ansible.yml
[WARNING]: Host file not found: /etc/ansible/hosts
[WARNING]: provided hosts list is empty, only localhost is available
PLAY [localhost] ***************************************************************
TASK [setup] *******************************************************************
ok: [localhost]
TASK [Print message] ***********************************************************
ok: [localhost] => {
"msg": "Hello to John, from Ansible!!"
}
PLAY RECAP *********************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0
And if we specify the variable value for “name”.
$ ansible-playbook --extra-vars '{"name":"Thor"}' ansible.yml
[WARNING]: Host file not found: /etc/ansible/hosts
[WARNING]: provided hosts list is empty, only localhost is available
PLAY [localhost] ***************************************************************
TASK [setup] *******************************************************************
ok: [localhost]
TASK [Print message] ***********************************************************
ok: [localhost] => {
"msg": "Hello to Thor, from Ansible!!"
}
PLAY RECAP *********************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0
As we can see here, it’s printing out “Hello to Thor, from Ansible!!” now. Looking good, let’s continue configuring the Jenkins job.
- Create a new Jenkins job
- Click on “Configure”
- Check on the “This project is parameterized” checkbox
- Select “String parameter” from “Add Parameter” dropdown
- In the “Name” field, put the valu “NAME”
- Then select “Invoke Ansible Playbook” from “Add build step” dropdown
- Enter the location of the Ansible playbook and click on the “Advance” button
- Enter “–extra-vars ‘{“name”:“${NAME}”}‘” in the “Additional parameters” textbox
- Save the configuration.
- Click on “Build with Parameters”
- Enter anything in the “NAME” input box, for example, “Jackie”
- Run and you can see the parameter is passed to Ansible playbook
Summary
In this post we’ve learned
- how to create a parameterized Jenkins job
- how to run and pass parameter to Ansible playbook
- how to pass parameter from a Jenkins job to Ansible playbook