DEV Community

Tib
Tib

Posted on

Some ansible tricks

Ansible

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 
Enter fullscreen mode Exit fullscreen mode

Or (with quotes):

- name: Copy copy: src: "foobar" dest: "/tmp/foobar" 
Enter fullscreen mode Exit fullscreen mode

But as soon as you use variables, you should use quotes!

- name: Copy copy: src: "{{ filename }}" dest: "/tmp/{{ filename }}" 
Enter fullscreen mode Exit fullscreen mode

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 ^ 
Enter fullscreen mode Exit fullscreen mode

sh gotcha

This is broken:

--- - hosts: servers tasks: - name: Broken shell: '[[ -z "" ]] && true' 
Enter fullscreen mode Exit fullscreen mode

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' 
Enter fullscreen mode Exit fullscreen mode

Or specify the executable in the args:

-------- - hosts: servers tasks: - name: Broken shell: '[[ -z "" ]] && true' args: executable: /bin/bash 
Enter fullscreen mode Exit fullscreen mode

Precedence of vars

Some are obvious, but not all 😁

Here is my reminder:

  1. CLI extra var -e variable="foo" will override...
  2. role vars (roles/common/vars/main.yml) that overrides...
  3. playbook vars (playbook.yml) that are taken in priority over...
  4. 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" 
Enter fullscreen mode Exit fullscreen mode

Conclusion

That's all for the tricks.

Happy provisioning! πŸ˜ƒ

Happy provisioning

Top comments (0)