Designing for reusability – Infrastructure as Code (IaC) with Terraform

Ansible provides variables for turning Ansible playbooks into reusable templates. You can substitute variables in the right places using Jinja2 markup, which we’ve already used in the last playbook. Let’s now look at Ansible variables, their types, and how to use them.

Ansible variables

Ansible variables, as with any other variables, are used to manage differences between managed nodes. You can use a similar playbook for multiple servers, but sometimes, there are some differences in configuration. Ansible variables help you template your playbooks so that you can reuse them for a variety of similar systems. There are multiple places where you can define your variables:

  • Within the Ansible playbook within the vars section
  • In your inventory
  • In reusable files or roles
  • Passing variables through the command line
  • Registering variables by assigning the return values of a task

Ansible variable names can include letters, numbers, and underscores. You cannot have a Python keyword as a variable, as Ansible uses Python in the background. Also, a variable name cannot beginwith a number but can start with an underscore.

You can define variables using a simple key-value pair within the YAML files and following the standard YAML syntax.

Variables can broadly be of three types—simple variables, list variables, and dictionary variables.

Simple variables

Simple variables are variables that hold a single value. They can have string, integer, double, or boolean values. To refer to simple Ansible variables within the playbook, use them within Jinja expressions, such as {{ var_name }}. You should always quote Jinja expressions, as the YAML files will fail to parse without that.

The following is an example of a simple variable declaration:

mysql_root_password: bar

And this is how you should reference it:

  • name: Remove the MySQL test database mysql_db:

name: test

state: absent

login_user: root

login_password: “{{ mysql_root_password }}”

Now, let’s look at list variables.

List variables

List variables hold a list of values you can reference using an index. You can also use list variables within loops. To define a list variable, you can use the standard YAML syntax for a list, as in the following example:

region:

  • europe-west1
  • europe-west2
  • europe-west3

To access the variable, we can use the index format, as in this example:

region: ” {{ region[0] }} “

Ansible also supports more complex dictionary variables. Let’s have a look.

Leave a Reply

Your email address will not be published. Required fields are marked *