Writing Your First Ansible Playbook

Writing Your First Ansible Playbook

Introduction

Writing your first Ansible playbook is an exciting step towards harnessing the power of automation. Ansible playbooks are written in YAML (YAML Ain't Markup Language) format, making them human-readable and easily understandable. To write your first playbook, follow these simple steps:

  1. Open a text editor and create a new file with a .yml extension (e.g., my_playbook.yml).

  2. Start by defining the playbook's structure:

     ---
     - name: My First Playbook
       hosts: all
       become: yes
       tasks:
         - name: My First Task
           <module>: <parameters>
    
    • name: Provide a descriptive name for your playbook.

    • hosts: Specify the group of hosts on which the playbook should be executed (all for all hosts).

    • become: Indicate whether tasks should be executed with elevated privileges (sudo).

    • tasks: Define a list of tasks to be executed.

  3. Define tasks within the tasks section using Ansible modules:

     tasks:
       - name: Install Apache
         apt:
           name: apache2
           state: present
    
  4. Save the playbook file and execute it using the ansible-playbook command:

     ansible-playbook my_playbook.yml
    

Congratulations! You've written and executed your first Ansible playbook. From here, you can explore more advanced features, such as variables, conditionals, loops, and roles, to create sophisticated automation workflows tailored to your specific requirements.