Ansible Variables


In Ansible, we use Variables as a way to deal with things that differ between one system and the next.

There's nothing particularly complicated about using Variables inside a Playbook. We use a very similar syntax to that which you've already seen:

---
- hosts: all
  vars: 
    - variable_name: /our/variable/contents
    - another_variable: "some text here"

As part of the video, we will use the variable we define to tell Ansible where we expect our website content directory to be created - /var/www/oursite.dev/web - and take advantage of the Ansible File Module to actually create the expected directory on our target system.

To use a variable in a task is really easy, we just enclose the variable name in some {{ double handlebars }}.

As such, our Playbook becomes (shortened for brevity):

- hosts: all
  vars: 
    - website_dir: /var/www/oursite.dev/web

  tasks:
    - name: Create website directory
      file: dest={{ website_dir }} mode=775 owner=www-data group=www-data

Pretty easy really. Nothing crazy happening, just declaring a variable and then using it.

Naming Variables

One quick heads up - naming variables is pretty straightforward. Either stick to single words:

  • foo
  • bar
  • fooBar

Or go with underscores:

  • foo_bar
  • baz_qux

Hyphens, spaces, and all numbers are not allowed. More info here if unsure.

Of course, there is more to be done with Variables inside Ansible, but that's enough to get you started.

Default Variables

Occasionally you may wish to have a variable defined in a task which may or may not be provided by the playbook.

In this instance, to avoid errors, you are best setting a default variable:

- name: symfony logs
  file: >
    path="{{ item.log_directory }}"
    state=directory
    owner="{{ item.root_directory_owning_user | default('www-data') }}"
    group="{{ item.root_directory_owning_group | default('www-data') }}"
    mode=0775
    recurse=true
  sudo: yes
  with_items: "{{ symfony_websites }}"

Seems ok, but a really useful feature here is to have a default which itself is a variable:

- name: symfony logs
  file: >
    path="{{ item.log_directory }}"
    state=directory
    owner="{{ item.root_directory_owning_user | default(symfony_web_server_user) }}"
    group="{{ item.root_directory_owning_group | default(symfony_web_server_group) }}"
    mode=0775
    recurse=true
  sudo: yes
  with_items: "{{ symfony_websites }}"

Notice the single pipe. This is not an or statement, but rather a pipe into the Jinja2 default filter.

We could then set the symfony_web_server_user inside the your-role/defaults/main.yml file:

symfony_web_server_user: "www-data"
symfony_web_server_group: "www-data"

Which allows anyone using the playbook to override this value as required, without needing us to hardcode a specific user as the default across multiple lines / files in our playbook.

Code For This Course

Get the code for this course.

Episodes