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?
The easiest way to pass Pass Variables value to Ansible Playbook in the command line is using the extra variables parameter of the “ansible-playbook” command. This is very useful to combine your Ansible Playbook with some pre-existent automation or script.
Ansible treats values of the extra variables as strings. To pass values that are not strings, we need to use JSON format. To pass extra vars in JSON format we need to enclose JSON in quotation marks: ansible-playbook extra_var_json.
Save and close the file when you're done editing. The vars section of the playbook defines a list of variables that will be injected in the scope of that play. All tasks, as well as any file or template that might be included in the playbook, will have access to these variables.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With