Working with Ansible Playbook

Semih Üstündağ
2 min readAug 27, 2021

Playbooks are Ansible’s configuration, deployment, and orchestration language. They can describe a policy you want your remote systems to enforce, or a set of steps in a general IT process.
At a basic level, playbooks can be used to manage configurations of and deployments to remote machines.

You can read more about ansible-playbook here.

Playbooks are written in YAML format. For this lab we need to have at least a server, preferably provisioned with Terraform.

After the instance is up, first edit the /etc/ansible/hosts file to point our instance.

$ cat /etc/ansible/hosts 
[web]
52.59.224.238 ansible_user=ubuntu

Now create a folder named ansible and a yml file in it.

$ mkdir -p ansible && cd ansible && touch playbook.yml

In the block below, we are specifying which hosts we want to work on and which tasks we want to run. Since installing packages in the server requires being root, we are using become: yes parameter.

---
- hosts: web
become: yes
tasks:
- name: install nginx
apt:
name: nginx
state: latest

Let’s now run the playbook to install nginx in our server.

$ ansible-playbook playbook.yml -e "ansible_ssh_private_key_file=keys/terraform-key-pair"

After running the command, you should see a similar output as below. We can see that status for the task install nginx has changed.

PLAY [web] *********************************************************************TASK [Gathering Facts] *********************************************************
ok: [52.59.224.238]
TASK [install nginx] ***********************************************************changed: [52.59.224.238]PLAY RECAP *********************************************************************
52.59.224.238 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

If we curl against to the IP address, assuming that port 80 is open in security groups for the instance, we should see the default web page for nginx.

Now let’s try to add the classic hello world page through our playbook.

For this, we will use Ansible’s copy module.

...
...
- name: copy index.html to /var/www/html
copy:
src: index.html
dest: /var/www/html/index.html

If we run the playbook again, it will not install nginx again, because it is already installed and it show its status as ok.

PLAY [web] *********************************************************************TASK [Gathering Facts] *********************************************************
ok: [52.59.224.238]
TASK [install nginx] ***********************************************************
ok: [52.59.224.238]
TASK [copy index.html to /var/www/html] ****************************************
changed: [52.59.224.238]
PLAY RECAP *********************************************************************
52.59.224.238 : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

If we curl against the server, we can see our little Hello World page.

$ curl 52.59.224.238
Hello World!

--

--