Sobes.tech
Junior

What components does an Ansible playbook consist of?

sobes.tech AI

Answer from AI

The Ansible playbook consists of the following main components:

  1. Play: The main execution unit in a playbook. It represents a set of tasks executed on a specific group of hosts with a given configuration.
  2. Hosts: Specifies the target hosts or groups of hosts where the play will be executed. Defined using an inventory file or dynamic inventories.
  3. Become: Allows tasks to be run with elevated privileges (e.g., as root) or on behalf of another user. Used for operations requiring special access.
  4. Tasks: A list of steps that Ansible should perform on target hosts. Each task invokes an Ansible module to perform a specific action.
  5. Modules: Functional units of Ansible that perform specific actions (installing packages, copying files, running commands, etc.). For example: yum, apt, copy, shell.
  6. Name: An optional but recommended field for each play, task, and playbook. Provides a readable description of what the component does.
  7. Vars: Allows defining variables that can be used in tasks. Enhances flexibility and reusability of playbooks.
  8. Handlers: Special tasks that are executed only if a change in configuration is triggered by other tasks. Often used to restart services.
  9. Roles: A mechanism to organize playbooks, variables, files, and handlers into reusable structures. Simplifies managing more complex configurations.
  10. Tags: Allow marking plays or tasks for selective execution or skipping during playbook runs.

Example of a simple playbook:

---
- name: Install and start Apache
  hosts: webservers # Target host group
  become: yes       # Run with root privileges

  tasks:
    - name: Install Apache package
      yum:         # Using the yum module
        name: httpd
        state: present # Ensure it is installed

    - name: Ensure Apache service is running and enabled
      service:     # Using the service module
        name: httpd
        state: started # Ensure it is running
        enabled: yes   # Ensure it is enabled at startup

    - name: Copy index.html
      copy:        # Using the copy module
        src: files/index.html # Source file
        dest: /var/www/html/index.html # Destination
      notify: Restart Apache # Call handler Restart Apache if file changes

  handlers:
    - name: Restart Apache
      service:
        name: httpd
        state: restarted