Today's repeating pattern by Kevin Dooley

My biggest problem with Ansible is linearity.

Ansible roles are plain YAML files describing various tasks you want to achieve. You have no class, no function and no reusable component between roles. Since there are no functions, you have no way to easily document the variables you need to define in your inventory unless you cut / past an existing one. You also won’t know when variables are unset, if they’re set to something impossible, or if you made a typo in your inventory.

Today, Greg found an amazing Ansible trick to both document your roles interface and ensure your variables are set.

Let’s say you want to setup a database connection. You need a host, a port, a user, a password and a database name.

- assert: that: - db_host != '' - db_port != '' - db_user != '' - db_user != 'root' - db_password != '' - db_name != '' tags: ['check_vars']

Placed at the beginning of your role main.yaml, or even better in an included init.yaml, it will prevent your role from being applied if any of the mandatory variables is empty, or if you try to connect as root, which is insecure.

It also acts as a function documentation. Every variable your role uses are described in your init file so you know what you need at a glance. Awesome isn’t it?

One more thing.

You’re missing the smartest part of Greg’s trick. See the tags: ['check_vars'] part in the snippet? You can use it to check all your variables are set before running your playbook with a simple:

$ ansible-playbook -i your_inventory -t check_vars site.yml

Sure, I could have stayed in the past. I could have even been king. But in my own way, I am king.

Hail to the king, baby.

Perry the Platypus wants you to subscribe now! Even if you don't visit my site on a regular basis, you can get the latest posts delivered to you for free via Email: