Create a playbook in Ansible

Prerequisite

  • Ubuntu 20.04
  • Ansible installed

Ansible is a great tool to automate IT infrastructure. In my case I use it to manage my Linux hosts. Instead of typing one command on each host, I can send one command to multiple hosts, using something called playbook. Ansible playbook is a set of instructions that you send to run on a single or a group of hosts.

Generate and send SSH keys to hosts

In order for ansible to execute your commands on the host, ansible need to have SSH access without password to the host

Follow this guide to achieve this.

Add hosts to inventory

In order to setup a playbook you first need to setup a hosts file. You can find the hosts file in /etc/ansible. The file is called “hosts”.

You can add ungrouped hosts or a collection of hosts.

# Ungroupd hosts
Host01 ansible_host=192.168.1.100
Host10 ansible_host=192.168.1.110

# Grouped hosts
[Servers01]
Host20 ansible_host=192.168.1.150
Host30 ansible_host=192.168.1.151
Host40 ansible_host=192.168.1.152

Create a playbook

Ansible playbooks uses YAML language. YAML is ident sensitive, so make sure your indents are correct.

Create a YAML config.

sudo vim playbook1.yml

You can send any type of command to your hosts. I send update and upgrade commands to my hosts everyday using crontab. My Playbook looks like this.

---
- hosts: Servers01
  become: true
  become_user: root
  tasks:
    - name: Update apt repo and cache on all Debian/Ubuntu boxes
      apt: update_cache=yes force_apt_get=yes cache_valid_time=3600

    - name: Upgrade all packages on servers
      apt: upgrade=dist force_apt_get=yes

We will break down the commands.

hosts: Servers01 – Specify a list of hosts that the instructions will be sent to.

become: true – We’re telling ansible that the instructions we are sending, requires root access to exectue.

become_user:root – We are running the commands as the user root.

tasks: – The tasks initiates the lists of task that is going to be executed. Each task have a unique name using “name”. We use “apt” module to update our hosts, or in other instances, install packages.

Run the playbook

To run your playbook, simply type:

sudo ansible-playbook /etc/ansible/roles/playbook1.yml

And that is all you have to do. You can create a schedule using crontab to run this playbook everyday


0 00 * * * ansible-playbook /etc/ansible/roles/playbook1.yml

There is much more you can do in ansible. I recommend you read the docs.

Similar Posts