ansible

How to pass variables to included tasks in ansible?


I have an ansible file (my_file.yml) that looks something like this:

---
- name: The name
  hosts: all
  tasks:

    - include:my_tasks.yml
      vars:
          my_var: "{{ my_var }}"

my_tasks.yml looks like this:

- name: Install Curl
  apt: pkg=curl state=installed

- name: My task
  command: bash -c "curl -sSL http://x.com/file-{{ my_var }} > /tmp/file.deb"

I'd like to pass my_var as a command-line argument to ansible so I do like this:

ansible-playbook my_file.yml --extra-vars "my_var=1.2.3"

But I end up with the following error:

... Failed to template {{ my_var }}: Failed to template {{ my_var }}: recursive loop detected in template string: {{ my_var }}

If I the vars in my_file.yml to look like this:

- include:my_tasks.yml
  vars:
      my_var: "1.2.3"

it works! I've also tried changing the variable name to something that is not equal to my_var, for example:

- include:my_tasks.yml
  vars:
      my_var: "{{ my_var0 }}"

but then I end up with an error. It seems to me that the variable is not expanded and instead the string "{{ my_var }}" or {{ my_var0 }} is passed to my_tasks.yml. How do I solve this?


Solution

  • You shouldn't need to explicitly pass my_var to the include. All variables including extra-vars should be directly available everywhere. So simply calling

    ansible-playbook my_file.yml --extra-vars "my_var=1.2.3"
    

    and using it as {{ my_var }} in the tasks should work.

    - name: My task
      command: bash -c "curl -sSL http://x.com/file-{{ my_var }} > /tmp/file.deb"