Ansible Playbook Samples

Here’s a sample Ansible playbook that installs and configures Nginx on a remote server:

---
- name: Install and configure Apache web server
  hosts: webserver
  become: true

  tasks:
    - name: Update apt cache
      apt:
        update_cache: yes
      when: ansible_os_family == 'Debian'

    - name: Install Apache package
      package:
        name: apache2
        state: present
      when: ansible_os_family == 'Debian'

    - name: Start Apache service
      service:
        name: apache2
        state: started
        enabled: true
      when: ansible_os_family == 'Debian'

    - name: Enable Apache service
      service:
        name: httpd
        state: started
        enabled: true
      when: ansible_os_family == 'RedHat'

    - name: Configure Apache virtual host
      template:
        src: templates/apache_vhost.conf.j2
        dest: /etc/apache2/sites-available/mywebsite.conf
      notify:
        - Reload Apache

  handlers:
    - name: Reload Apache
      service:
        name: apache2
        state: reloaded

In this playbook:

  • The playbook targets the hosts defined under the webserver group in the Ansible inventory.
  • The become: true statement enables privilege escalation to execute tasks with administrative privileges.
  • The playbook first updates the apt cache (for Debian-based systems) to ensure the package lists are up to date.
  • Then, it installs the Apache package using the apt module for Debian-based systems or the yum module for Red Hat-based systems.
  • After that, it starts and enables the Apache service using the service module.
  • Next, it uses the template module to copy a custom Apache virtual host configuration file to the target machine.
  • Finally, it defines a handler that triggers the Apache service reload whenever the virtual host configuration changes.

Note: Make sure to replace templates/apache_vhost.conf.j2 with the actual path to your Apache virtual host configuration template file.

You can save this playbook to a file, such as install_apache.yaml, and run it using the ansible-playbook command:

ansible-playbook -i inventory.ini install_apache.yaml

Make sure to replace inventory.ini with the path to your Ansible inventory file containing the target hosts.