Ansible explained

Introducing Ansible

There is a line (37) in the previous part where we just called an Ansible script to setup our server. It is time to explain that a bit.

Ansible is an IT automation platform. You write YAML files and Ansible transform them to actual commands and execute them line-by-line. Actually, it is even better than that: You define the state what is expected and Ansible will check and change it only when necessary.

At the beginning I only added a script to terraform and run that after initialization. This work fine as long You do not mess up the order of the commands. If You only want to change 1-2 line You have to comment the rest to make sure nothing goes wrong and run the full terraform deploy which is quite slow.

With Ansible You write the state file once and You can run it as many time as You want, it will skip those parts matching with the desired state. Amazingly powerful.

You do not have to install Ansible on every computer You would like to work with. It create a network connection (via ssh in this case) and run the state commands on the remote machine.

Setup for admin server

The YAML file describing the desired state is called a playbook. Our playbook is only one file which includes firewall (iptables) rules with the ansible.builtin.include_tasks: "admin-rules.yml" line.

We use separate file for iptables because:

  • By removing the comment marker for the first couple of lines we get a separate playbook. (I wanted to include the full playbook, but I run into some weird bug. This is just a workaround until I figure out what is wrong.)
  • Firewall rules are quite long and handle a specific use case.
  • When You work on firewall rules it is quite handy to only recreate firewall rules instead of running the whole playbook.

Explaining the playbook

I do not want to go over every line of the playbook, but I will show You some of the features. Each task or block has a name where I try to explain what is happening. Feel free to ask if something does not click.

Variables

We can define variables in the playbook. Ansible will ask for those values or You can add them on the command line. For example in the Terraform script the Ansible command has a -e 'wheel_login=${var.wheel_login} hostname=${self.label}' part. This parameter passes the terraform variables toward Ansible.

Hosts

The hosts tag defines the host machines we would like to run the playbook on. When set to all it will run on every machine.

There is a chicken-egg problem here: When running terraform we do not know the IP address of the newly deployed yet. Adding -i '${self.ip_address},' to the Ansible command line solves that: Terraform fills in the self.ip_address value with the IP of the fresh deployment, so we can pass that. This way the Ansible inventory contains only one item, all only refers to that single item.

It is time to check those firewall rules.