Ansible and YAML
From bib. source
Playbooks are written in YAML, a simple human-readable syntax popular for defining configuration.
That is to say, playbooks in Ansible are written in a language called YAML, a.k.a. YAML Ain’t Markup Language or Yet Another Markup Language. The YAML language for Ansible must have field names and nesting used that are valid for Ansible in addition to YAML as such. Luckily (Geerling 2023, 47):
From bib. source
Using the following bash shell script exemplar (Geerling 2023, 47-48):
# Install Apache
dnf install --quiet -y httpd httpd-devel
# Copy configuration files
cp httpd.conf /etc/httpd/conf/httpd.conf
cp httpd-vhosts.conf /etc/httpd/conf/httpd-vhosts.conf
# Start Apache and configure it to run at boot
service httpd start
chkconfig httpd onOne could translate it into an Ansible YAML playbook thusly (Geerling 2023, 78):
---
- hosts: all
tasks:
- name: Install Apache.
command: dnf install --quiet -y httpd httpd-devel
- name: Copy configuration files.
command: >
cp httpd.conf /etc/httpd/conf/httpd.conf
- command: >
cp httpd-vhosts-conf /etc/httpd/conf/httpd-vhosts.conf
- name: Start Apache and configure it to run at boot.
command: service httpd start
- command: chkconfig httpd onIn sum (Geerling 2023, 49):
From bib. source
Ansible is powerful in that you quickly transition to using playbooks if you know how to write standard shell commands–the same commands you’ve been using for years–and then as you get time, rebuild your configuration to take advantage of Ansible’s helpful features.
As an example of taking advantage of more Ansible features, one can rebuild the previous translation into playbook YAML using more diverse Ansible modules, like so (Geerling 2023, 49-50):
---
- hosts: all
become: yes
tasks:
- name: Install Apache.
dnf:
name:
- httpd
- httpd-devel
state: present
- name: Copy configuration files.
copy:
src: "{{ item.src }}"
dest: "{{ item.dest }}"
owner: root
group: root
mode: 0644
with_items:
- src: httpd.conf
dest: /etc/httpd/conf/httpd.conf
- src: httpd-vhosts.conf
dest: /etc/httpd/conf/httpd-vhosts.conf
- name: Make sure Apache is started now and at boot.
service:
name: httpd
state: started
enabled: yesThe playbook
hostfieldOne can limit the play of the playbook to “specific groups or individual hosts by changing the
hostdefinition,” whether by setting it “toallhosts, a group of hosts defined in [an] inventory, multiple groups of hosts (e.g.,webservers,dbservers), individual hosts (e.g.,at1.example.com), or a mixture of hosts” (Geerling 2023, 52-53). Wild card matches are also possible (Geerling 2023, 53).
YAML_Aint_Markup_Language Yet_Another_Markup_Language markup_language data_serialization_language data_serialization_format shell_script shell_scripting bash_script bash_scripting module modules configuration_management configuration_file
bibliography
- “Ansible Playbooks.” In Ansible for DevOps: Server and Configuration Management for Humans, 2nd ed., 47-83. Leanpub, 2023.