Using special variables in blocks to improve code readability
This post will cover using special variables that Ansible provides when using blocks for error handling.
I know that it has been a while since i’ve posted. I took a lovely vacation to Japan for 3 weeks and the pre and post trip logistics have me a bit bogged down. This will be a short one.
I just recently discovered that when using a block (and rescue) that two special variables are created that are very useful in limiting the amount of YAML that needs to be written.
Creating an execution environment image
This post will cover the process of using bash, podman, and ansible builder.
We’ll tackle this using various files as the container definition. Then a small bash script to run the build, create the container, and upload it to Private Automation Hub. This post is a bit long, check the links if you need to jump around.
Using default jinja values in Ansible playbooks
Have you ever had a fact that you set earlier in the playbook that can occasionally be empty? If you have, then you know it can sometimes derail tasks later in the playbook.
Luckily jinja offers a default filter that can be used to set a particular value.
Let’s look at an example and how it can be improved by using a default filter. In the example we’re checking to see if there is an IP address before kicking off some node removal tasks in SolarWinds. Note: I’m using my naming scheme here that I use for any include_tasks actions. I’ll cover this in a future post.
Improving code readability for Ansible conditionals
Improving readability when using the when conditional
The when condition is very commonly used in Ansible and gives playbook writers an if like conditional. It must be placed at the same level as the task name and the task itself.
The official documentation uses the example below.
tasks:
- name: Configure SELinux to start mysql on any port
ansible.posix.seboolean:
name: mysql_connect_any
state: true
persistent: true
when: ansible_selinux.status == "enabled"
I think we can improve the readability of this code by moving the when block as shown below.
Welcome to Automation Adventures
Automation Adventures
This is a site by Justin Leopold covering my automation journey using Ansible, Python, UiPath, and anything else related to automation and integration.
My goal with this site is to cover small tips, syntax, and other useful snippets related to my current role as an Automation Architect in the public sector.
Follow me: