Ansible: Introduction to Playbooks
What is a Playbook
A Playbook in ansible is a file containing a set of instructions for automating systems configuration. It like a bash script but in ansible "language". A ad-hoc command is suitable for a basic single line task. But if we want to perform a complex and repeatable deployement, we certainly must use a playbook.
Playbooks are written in YAML following a structured syntax. A playbook contains an ordered list of plays that runs in order from top to bottom by default.
---
- name: Update servers
hosts: servers
remote_user: ans-user
tasks:
- name: Update nginx
ansible.builtin.dnf:
name: nginx
state: latest
To ping all hosts;
---
- name: Ping all hosts
hosts: servers
tasks:
- name: Ping servers
ansible.builtin.ping:
This is how you run a playbook:
ansible-playbook my_playbook.yml
or in dry run mode:
ansible-playbook --check my_playbook.yml
or to check the syntax of our playbook:
ansible-playbook --syntax-check my_playbook.yml
or to list all hosts:
ansible-playbook --list-hosts my_playbook.yml
or to list all tasks:
ansible-playbook --list-tasks my_playbook.yml
We can a lot more configuration to the playbook to perform advanced automation tasks. We are going to leave that for a future post.
By default, ansible gather facts about the nodes before executing the playbook To disable this feature, we can add gather_facts: false to our playbook:
---
- name: Ping all hosts
hosts: servers
gather_facts: false
tasks:
- name: Ping servers
ansible.builtin.ping:
Example of Simple Playbooks
Ping hosts
We've already seen how to do that. This is a simple way to ping nodes using ansible playbook:
---
- name: Ping Linux hosts
hosts: servers
gather_facts: false
tasks:
- name: Ping servers
ansible.builtin.ping:
Install/Uninstall packages
---
- name: Install/uninstall packages
hosts: servers
become: 'yes'
tasks:
- name: Install OpenSSH on Linux servers
ansible.builtin.dnf:
name: openssh
state: present
- name: Uninstall Apache
ansible.builtin.dnf:
name: httpd
state: absent
Update packages
---
- name: Update packages
hosts: servers
become: 'yes'
tasks:
- name: Update OpenSSH on Linux servers
ansible.builtin.dnf:
name: openssh
state: latest
- name: Uninstall Apache
ansible.builtin.dnf:
name: nginx
state: latest
Enable/Disable services
---
- name: Enable nginx service
hosts: servers
become: 'yes'
tasks:
- name: Install nginx
ansible.builtin.service:
name: nginx
state: present
- name: Enable nginx service
ansible.builtin.service:
name: nginx
state: started
enabled: yes
- name: Disable Apache service
ansible.builtin.service:
name: cups
state: stopped
enabled: no