Pass extra variables to Ansible playbook

Just like any other scripting language, you can pass extra variables to ansible playbook. Variables are very much important because It makes your ansible-playbook more dynamic and reusable.

Pass extra variables to Ansible playbook
This is how your ansible-playbook would look if you would use the extra-vars feature. Don’t skip, read the whole post.

Why pass extra variables to Ansible playbook?

  • To make your script more dynamic and reusable.
  • Imagine there is something in your ansible-playbook, which need to be changed multiple time, It’s not a good idea to change your script every time.

This is just the tip of the iceberg, when you start using the ansible extra variables feature you will release the whole power of it.

Hard-coding in Ansible playbook

Lets see why hard-coding in ansible is a very bad idea. We are using an ansible copy module, for now, but this login applies to almost any language.

While using the copy module, we mention source and destination in the playbook.

Without extra variables, your playbook would look like this. Below playbook will copy file.txt to all web servers

gather_facts: no
  hosts:
       - webserver

  tasks:
   - name: Copy file
     copy:
         dest: /home/justgeek/file.txt
         src: /home/justgeek/file.txt

In the example above, we have hard-coded in the ansible-playbook to copy file.txt. By hardcoding in ansible-playbook you will have to edit your playbook every time you need to copy a different file.

How to pass extra variables to Ansible playbook?

The example below will demonstrate, how to use the extra variable feature using the copy module.

To pass the variable from the command line, we need to first update the ansible-playbook to accommodate. In the copy module, you need to change the file.txt as below.

dest: /home/justgeek/{{ filename }}
src: /home/justgeek/{{ filename }}

Your updated playbook should look like this.

-
  gather_facts: no
  hosts:
       - webserver

  tasks:
   - name: Copy file
     copy:
         dest: /home/justgeek/{{ filename }}
         src: /home/justgeek/{{ filename }}

Now, just need to mention the file name which needs to be copied, whenever you run the playbook. No need to change your playbook every time when the file changes.

$ ansible-playbook -i Inventory.yml test.yml -k -K --extra-vars name=newfile.txt

In the same playbook, you can update the hosts line, so you can reuse the playbook to copy different files on different servers. You can extra vars in ansible playbook to start services to make it dynamic.

Spread the love

Leave a Comment