How to pass variables to Ansible from command

Just like any other scripting language , you can also use variables in Ansible.
You can use variables so your playbooks become more dymanic and re-usable in multiple scenarios.

To demonstrate, I will use copy module in ansible, however you can use variable in any where in your playbook.
so when you use copy module you normally define source and destination as shown below.

dest: /home/justgeek/example.txt
src: /home/justgeek/example.txt

However, eveytime the file name cannot be example.txt so there is a way to pass the file name when you run the ansible-playbook command. So you need to define the variable as shown below.

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

So your complete playbook would look like this.

  gather_facts: no
       - webserver

   - name: Copy file
         dest: /home/mumrethwala/{{ filename }}
         src: /home/mumrethwala/{{ filename }}

So when running playbook, you ansible command would look like below.

ansible-playbook -i Inventory.yml test.yml -k -K --extra-vars

You can use these variable and define dynamic hosts as well.

Defining Variables inside playbooks.

You can also define variables inside playbook as well.

- hosts: all
      message: "Hello World"
    - name: Testing Ansible variable
         msg: "{{ message }}"

So when you run playbook it will print as below

TASK [Testing Ansible variable] *******************************************************************************************
ok: [server01] => {
    "msg": "Hello World"

You can also check other ansible Articles to learn more.

Leave a Reply

Your email address will not be published. Required fields are marked *