Hello Ansible
Ansible is an automation tool for managing the state of a system.1 Ansible playbooks can target remote or local systems. I mainly use ansible playbooks to provision linux virtual machines.
Prerequisites:
- Ubuntu 20.04 with Python3 installed.
Part 1: Installation
More details can be found in the official Ansible documentation2, these are the steps I took on a fresh Ubuntu virtual machine.
Check python3 and pip installation
$ which python3
/usr/bin/python3
$ python3 -m pip -V
pip 22.0.2 from /usr/lib/python3/dist-packages/pip (python 3.10)
Install ansible via pip.
$ python3 -m pip install --user ansible
$ ansible --version
ansible [core 2.14.3]
Install Python and Pip
If needed install python3 and pip, process will be different depending on things, ymmv but this womm
$ apt-get update -y
$ apt-get install python3
$ apt-get install python3-pip
Part 2: Use a Playbook
Create project directory and set location for ansible config file. Probably not strictly necessary because ansible checks the current directory for a config anyway.
~/
$ mkdir hello-ansible
$ cd hello-ansible
$ export ANSIBLE_CONFIG=~/hello-ansible/ansible.cfg
Define ansible configuration variables in a config file. In this case we’re going to run this playbook on the target machine, so we can ignore the warning from ansible about using the “implicit localhost”.
~/hello-ansible/ansible.cfg
[defaults]
localhost_warning=false
Place the following in a new file named playbook.yml
3
~/hello-ansible/playbook.yml
---
- name: Hello World playbook
hosts: localhost
tasks:
- name: Hello World - debug
ansible.builtin.debug:
msg:
- "Hello World"
Run the playbook.
$ ansible-playbook playbook.yml
PLAY [Hello World playbook] ****************************************************
TASK [Gathering Facts] *********************************************************
ok: [localhost]
TASK [Hello World - debug] ****************************************************
ok: [localhost] => {
"msg": [
"Hello World"
]
}
PLAY RECAP *********************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Part 3: Use a Role
We can refactor our playbook into a role4. Roles are useful if we wanted to reuse this set of tasks in different playbooks, or with use a set of tasks with different input variable values.
$ mkdir -p ~/hello-ansible/roles/hello/tasks
~/hello-ansible/roles/hello/tasks/main.yml
---
- name: Hello World - role
ansible.builtin.debug:
msg:
- "Hello World"
~/hello-ansible/playbook.yml
---
- name: Hello World playbook
hosts: localhost
roles:
- hello
Our directory structure should look like this now.
├── playbook.yml
└── roles
└── hello
└── tasks
└── main.yml
Running ansible-playbook playbook.yml
should give the same output as above.
Wrapping up
At this point the hello-ansible
directory contains a working playbook. Building
on from here we can add tasks and roles to accomplish all sorts of things.