ansible playbooks

https‮gi.www//:‬iftidea.com

Ansible playbooks are YAML files that define a set of tasks to be performed on a group of hosts. Playbooks provide a way to automate more complex tasks and allow for more customization and reusability than ad-hoc commands.

Here are the basic components of an Ansible playbook:

  1. Hosts: The hosts section defines the group of hosts on which the tasks will be performed. This can be a single host, a group of hosts, or all hosts in the inventory.

  2. Variables: Playbooks can define variables that can be used throughout the playbook. These can be defined at the playbook level or at the task level.

  3. Tasks: The tasks section defines the set of tasks to be performed on the hosts. Each task specifies a module to be executed, along with any necessary parameters.

  4. Handlers: Handlers are tasks that are triggered by other tasks. They are typically used to restart services or perform other actions that should only be done once all related tasks have been completed.

  5. Roles: Roles are collections of tasks, variables, and other files that can be reused across multiple playbooks.

Here's an example of an Ansible playbook:

- hosts: web_servers
  vars:
    http_port: 80
  tasks:
    - name: Install nginx
      apt:
        name: nginx
        state: present
      become: yes
    - name: Copy nginx config file
      copy:
        src: nginx.conf
        dest: /etc/nginx/nginx.conf
      become: yes
      notify: Restart nginx
  handlers:
    - name: Restart nginx
      service:
        name: nginx
        state: restarted
      become: yes

In this example, we define a playbook that performs two tasks on the web_servers group: installing the nginx package using the apt module, and copying the nginx configuration file using the copy module. We also define a variable called http_port that can be used throughout the playbook.

After the configuration file is copied, a handler is triggered to restart the nginx service using the service module. The notify keyword in the copy task is used to trigger the handler.

Roles can also be used in playbooks to reuse common tasks and configurations across multiple playbooks. A role can contain tasks, variables, templates, and other files, and can be easily included in a playbook using the roles keyword.