Johan
Johan

Reputation: 40510

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?

Upvotes: 40

Views: 85619

Answers (2)

Vasudev
Vasudev

Reputation: 1017

Faced the same issue in my project. It turns out that the variable name in the playbook and the task have to be different.

---
- name: The name
  hosts: all
  vars:
    my_var_play: "I need to send this value to the task"
    some_other_var: "This is directly accessible in task"
  tasks:
    - include:my_tasks.yml
      vars:
          my_var: "{{ my_var_play }}"

Also on a sidenote, all the variables in the playbook is accessible in the task. Just use {{ some_other_var }} in task and it should work fine.

Upvotes: 41

udondan
udondan

Reputation: 59989

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"

Upvotes: 16

Related Questions