Variables could be defined in #202204272036 and #202204272043. However, it is recommended to put variables, primarily credentials that are essential for connection such as username and password, into Inventory.
Note: Variables stored in #202204300820 are called facts.
To access a variable or fact in Playbook, use the filter syntax or Jinja syntax {{ variable }}
. The variable could be stored as YAML file inside directories named host_vars
or group_vars
for the Playbook to access. The variables for hosts will take precedence over variables for groups since they are more specific.
Control Flow
For conditionals, we could use the #202204300820 when
. One can use comparison operators such as ==
, !=
, >
, >=
, <
and <=
, or in
keyword to check whether the value is found in a list. It has some limitation for potential large amount of tasks. For this, it is advised to use handler or separate the tasks into a #202204272036 and then included later. The usage is shown as below:
...
tasks:
- name: Install apache
apt:
name: apache2
state: latest
when: ansible_distribution == 'Debian' or
ansible_distribution == 'Ubuntu'
...
register
module could be used in order to store the return status of a task in order to be used in a later stage. A better approach in control flow could be by using handlers
. The following shows the example use case:
...
tasks:
- name: Ensure httpd package is present
yum:
name: httpd
state: latest
register: httpd_results
- name: Restart httpd
service:
name: httpd
state: restart
when: httpd_results.changed
...
Module notify
is used to notify the handlers when there is a change of state of the task. Use the module handlers
to define handler. Its format is quite similar to #the tasks module. For example:
...
tasks:
- name: Ensure httpd package is present
yum:
name: httpd
state: latest
notify: restart_httpd
handlers:
- name: restart_httpd
service:
name: httpd
state: restart
...
We could loop over a list of variables or items using the module loop
. This could become handy when there is a task should be repeated with multiple variables. That being said, using loop
is unfavourable due to the performance hit. A lot of times, #202204300820 has better built-in than loop
. The following code shows how to use loop
:
...
tasks:
- name: Ensure user is present
user:
name: "{{ item }}"
state: present
loop:
- dev_user
- qa_user
- prod_user
...
Note: item
can store an object, meaning it could be a JSON list instead of just value.