Frank van Tol
Frank van Tol
Creator of this blog.
📅 Dec 1, 2019 🕘 1 min read 💬 205 words

Ansible tips & tricks

or things you should know before you start writing playbooks.

Substrings

Ansible does not have functions for dealing with substrings but because the foundation is python, you can actually use the python contructs [ : ], like for example:

- set_fact: mystring="abcdefg"

- debug: msg={{ mystring[1:3] }}


Output: abc

if() statements

Jinja2 has a {% if %} {% endif %} construction that is upported in most programming languages and you probably know this. Unfortunately Ansible does not have this and you must use the ternary filter to build a if statement, for example:

- debug: msg=Is it Friday yet?  {{ today == 'Friday' | ternary('Yes weekend coming', 'not yet') }}

Shell output from curl

When you use a shell script with the command/shell modules, you need a way of telling if the script was successfull. The command/shell modules always return Changed=true, so you can not use that. The solution lies in the exit code in the script, which you can check like so:

#!/bin.bash

ls -l
exit 5

and the example playbook snippet:

- name Check script result
  command: mytest.sh
  register: myresult
  
- fail:
  when:  myresult.rc != 5

Format numbers with leading 0’s

- set_fact:  myvar=5

- debug: msg={{'%02d'| format( myvar ) }}

outputs: 05

Do you have an idea or suggestion for a blog post? Submit it here!