MFH LABS : Ansible Playbook – Install Apache

---
  - name: Playbook
    hosts: webservers
    become: yes
    become_user: root
    tasks:
      - name: ensure apache is at the latest version
        yum:
          name: httpd
          state: latest
      - name: ensure apache is running
        service:
          name: httpd
          state: started

name Name of the playbook
hosts A set of hosts usually grouped together as a host group and defined in inventory file
become To tell ansible this play has to be executed with elevated privileges
become_user the user name that we want to switch to like compare it with sudo su - user
tasks set of tasks to execute, All tasks would be defined below this
and then we have two tasks with two modules, the first module is yum and the second module is service
in the first task with yum  the state latest represents that the forementioned package httpd should be installed if it is not installed (or) if it is already installed it should be upgraded to the latest version available. If you do not want it to be upgraded if present, You can change it to state: present

On the Second task with service module, we are making sure that the service named httpd is started and running using the state: started Ansible would not restart the service if it is already started and running.

Ansible playbook can be executed with ansible-playbook command. like you have ansible command to execute ad hoc command. This is dedicated for ansible playbooks

Let us see how to execute the preceding playbook and install apache on the webservershost group

Note*: a host group is a group of hosts and servers mentioned in the ansible inventory file.

➜  Ansible-Examples git:(master) ✗ cat ansible_hosts

[webservers]

mwivmweb01 mwivmweb02

Here is the customized Ansible inventory file with two hosts grouped as webservers

Here the host group name is webservers and it is mentioned in the hosts: directive on the playbook

Given below is the command syntax or sample to run an ansible playbook.

➜ ansible-playbook sampleplaybook.yml -i ansible_hosts

If you have mentioned all the host groups in your default inventory file /etc/ansible/hosts  then you do not have use -i argument.  this is only when you have a customized inventory file like I do.