How do Ansible playbooks work?

Ansible playbooks are YAML files that define a series of tasks to be executed on specified hosts. They are the primary way to automate tasks in Ansible. Here's how they work:

  1. Structure: A playbook consists of one or more "plays." Each play targets a group of hosts and defines the tasks to be executed on those hosts.

  2. Hosts: You specify which hosts the playbook will run on, typically defined in an inventory file.

  3. Tasks: Each play contains a list of tasks. Tasks use Ansible modules to perform actions, such as installing packages, copying files, or managing services.

  4. Variables: You can define and use variables within playbooks to make them more dynamic and reusable. Variables are referenced using the {{ variable_name }} syntax.

  5. Execution: When you run a playbook, Ansible connects to the specified hosts and executes the tasks in the order they are defined.

Example Playbook

Here's a simple example of an Ansible playbook:

- hosts: webservers
  tasks:
    - name: Install Apache
      yum:
        name: httpd
        state: present

    - name: Start Apache service
      service:
        name: httpd
        state: started

In this example:

  • The play targets hosts in the webservers group.
  • It installs the Apache web server and ensures the service is started.

For more hands-on practice, consider exploring LabEx labs focused on writing and executing Ansible playbooks!

0 Comments

no data
Be the first to share your comment!