Red Hat Ansible is a powerful and easy-to-learn automation product. Simplicity is one of the basic principles of the language. Open the product description or documentation; it states simplicity and easy-to-use as key differentiators. And they are not wrong; this paradigm pays with the clean YAML code, one of the most human-compatible formats. Yet, any task a titbit more complex than installing and starting an HTTPD server requires good old procedural control flows.

I plan to create a series of posts about how I work around Ansible limitations and create custom roles without creating custom modules. Not that I don't know Python, everyone who spends more than a year with WebLogic knows it a bit. But custom modules require a different level of commitment and involvement. With playbooks and custom roles, you automate daily routines and deliver perfectly unified environments. When you create modules, you are a Python developer and create code that someone would use for the automation.

Anyway, procedural language has three types of command flow:

  • Sequential flow - the most natural way for Ansible. The engine executes plays in the playbook and tasks in plays in the same order they appear in the code. The Ansible does not maintain the sequence of targets or tags, but an order of tasks is sacred. So you don't need to do anything special to keep your task execution in order.
  • Subroutines - Ansible has no formal functions or procedures that you can define and reuse. The closest to the procedure by meaning is a role:  a predefined set of tasks, facts, and artifacts to perform repeatable tasks on targets. And this is what I use the most on the playbook level.
  • Selections - With the "Simpler is merrier" on the banner, Ansible does not have proper selection controls, yet even simple by choice language must check conditions and act accordingly. Any Ansible task can be paired with the when clause. That and perks of the Jinja2 templates allow you to mimic if ... then and case controls.
  • Iterations - When you reflect on the fact that the Ansible engine executes multiple tasks simultaneously on the scores of hosts, you would better understand why Ansible developers do not like iterations. Yet, Ansible allows you to iterate a task and even offers nested loops (two levels limit). Yet can't iterate over a block of tasks and use language loopholes to implement complex loop clauses.