In this blog post, I will share some (basic) tricks about Ansible ๐
It could possibly prevent you to get bitten ๐ท
Quote when using vars
When not using variables, you can quote (or not) indifferently:
- name: Copy
copy:
src: foobar
dest: /tmp/foobar
Or (with quotes):
- name: Copy
copy:
src: "foobar"
dest: "/tmp/foobar"
But as soon as you use variables, you should use quotes!
- name: Copy
copy:
src: "{{ filename }}"
dest: "/tmp/{{ filename }}"
Not all ansible versions have the same behaviour for this! Latest versions of Ansible are more flexible, but are not able to completely handle it (depends where the variable is positioned).
For more info, see YAML gotcha
Extra quote when passing extra variable in command line
When using the --extra-vars
(or -e
) to pass variables in the command line, take care of adding an extra quote to protect spaces:
# here v and here v
$ ansible-playbook playbook.yml -e 'protectme="foo bar"'
# to protect this ^
sh gotcha
This is broken:
---
- hosts: servers
tasks:
- name: Broken
shell: '[[ -z "" ]] && true'
Why? Because it is executed by /bin/sh
... not bash
!
You can transform it to a sh
compatible version like this:
---
- hosts: servers
tasks:
- name: Working
shell: 'test -z "" && true'
Or specify the executable in the args
:
--------
- hosts: servers
tasks:
- name: Broken
shell: '[[ -z "" ]] && true'
args:
executable: /bin/bash
Precedence of vars
Some are obvious, but not all ๐
Here is my reminder:
- CLI extra var
-e variable="foo"
will override... - role vars (
roles/common/vars/main.yml
) that overrides... - playbook vars (
playbook.yml
) that are taken in priority over... - role default vars (
roles/common/default/main.yml
)
For more infos, check the official doc about complete list of precedence
Edit variable after initialization
You can do this with the module set fact!
- name:
set_fact:
var1: "new value"
Conclusion
That's all for the tricks.
Happy provisioning! ๐
Top comments (0)