Categories

Category cover

Automation
155 posts

Category cover

Learning paths
119 posts

Category cover

CISO
22 posts

Category cover

Security
20 posts

Category cover

Notes
19 posts

Category cover

Personal Security
18 posts

Category cover

Infrastructure
12 posts

Category cover

OT/ICS
5 posts

Category cover

Books
3 posts

Category cover

UNetLab
3 posts

Category cover

Write-up
3 posts

Category cover

OSInt
2 posts

Category cover

My life
1 posts

Ansible statements

Andrea Dainese
September 16, 2024
Post cover

If you’ve got some experience with programming languages, you might find Ansible’s constructs a bit clunky. But no worries, let’s break them

If you’ve got some experience with programming languages, you might find Ansible’s constructs a bit clunky. But no worries, let’s break them down with some practical examples to make things clearer.

Conditionals (if, then, else)

In Ansible, the if-then-else construct is simplified to a single word: when.

Unlike traditional languages, there’s no direct else or elif. You’ll handle them all with separate when statements and the right expressions.

If you’ve got a bunch of conditions that all need to be true at the same time (logical AND), you can list them out:

Each variable in Ansible can be one of the following types:

  • List
  • Dictionary
  • Boolean (True/true/yes/on or False/false/no/off)
  • Integer
  • Float
  • String (if it’s wrapped in quotes or doesn’t fit the above types)

Ansible heavily relies on Jinja , which adds a bit more complexity to the mix. Any variable created using Jinja is treated as a string, and you’ll often need to convert it before use. But sometimes Ansible takes care of this for you, like when it automatically converts a string containing JSON into a list or dictionary when used in a loop.

Here’s a quick breakdown to help you navigate this:

  • Variables can be either defined or undefined.
  • A defined variable might be empty (None) or have some data.
  • The variable’s type depends on the data it holds (Ansible uses weak typing).
  • Ansible often creates strings using Jinja, which may require conversion.
  • Ansible will automatically convert strings into lists or dictionaries when needed.
  • Before performing mathematical operations, it’s a good habit to explicitly convert variables using Jinja filters like | int or | float.

Continue reading the post on Patreon .