Ansible – Playbook example and execution

Ansible_Logo

In this example we will write a simple playbook in Ansible, that will create a new user in a managed host.

For this we need to ensure the managed host is present in the “inventory” file that will be used

[root@centos9vm ~]# cat inventory

===== ====

192.168.132.129
192.168.132.130

192.168.132.135
servera.example.com

[webservers]
servera.example.com
serverb.example.com

[dbservers]
serverc.example.com
serverb.example.com
servera.example.com

[myGroups:children]
webservers
dbservers

[testGRP]
192.168.132.135

[testGRP:vars]
theUser = shiju500

===== ====

Ensure the Ansible server can SSH to the managed node without a password

Let us create a new playbook named shijuplaybook.yml

[root@centos9vm ~]# cat shijuplaybook.yml

========= ========
– – –
– name: shiju sample playbook
    hosts: 192.168.132.130
    tasks:
        – name: Add a user shiju100
            ansible.builtin.user:
                name: shiju100
                state: present

        – name: Installing httpd package
            ansible.builtin.dnf:
                name: httpd
                state: present
========= ========

Now let us check the syntax of the newly created yml file before actually executing the playbook

[root@centos9vm ~]# ansible-navigator run -m stdout shijuplaybook.yml –syntax-check
playbook: /root/shijuplaybook.yml

[root@centos9vm ~]# ansible-navigator run -m stdout shijuplaybook.yml

==== ===

PLAY [shiju sample playbook] ***************************************************

TASK [Gathering Facts] *********************************************************
ok: [192.168.132.130]

TASK [Add a user shiju100] *****************************************************
changed: [192.168.132.130]

TASK [Install httpd server] ****************************************************
changed: [192.168.132.130]

PLAY RECAP *********************************************************************
192.168.132.130 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
[root@centos9vm ~]#

==== ===

Verify is the new user got added in the node 192.168.132.130