Ansible Playbook Basics

AnsibleAnsibleBeginner
Practice Now

Introduction

In this lab, you will learn the fundamentals of Ansible playbooks. Ansible playbooks are YAML files that describe a set of tasks to be executed on remote hosts. They are the building blocks for complex IT automation workflows. You'll create your first playbook, understand its structure, and learn how to execute it. By the end of this lab, you'll have hands-on experience with writing and running Ansible playbooks, which will serve as a foundation for more advanced Ansible usage.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) linux(("`Linux`")) -.-> linux/BasicFileOperationsGroup(["`Basic File Operations`"]) ansible(("`Ansible`")) -.-> ansible/InventoryManagementGroup(["`Inventory Management`"]) ansible(("`Ansible`")) -.-> ansible/PlaybookEssentialsGroup(["`Playbook Essentials`"]) linux/FileandDirectoryManagementGroup -.-> linux/mkdir("`Directory Creating`") linux/BasicFileOperationsGroup -.-> linux/touch("`File Creating/Updating`") ansible/InventoryManagementGroup -.-> ansible/host_variables("`Set Host Variables`") ansible/PlaybookEssentialsGroup -.-> ansible/playbook("`Execute Playbook`") subgraph Lab Skills linux/mkdir -.-> lab-390426{{"`Ansible Playbook Basics`"}} linux/touch -.-> lab-390426{{"`Ansible Playbook Basics`"}} ansible/host_variables -.-> lab-390426{{"`Ansible Playbook Basics`"}} ansible/playbook -.-> lab-390426{{"`Ansible Playbook Basics`"}} end

Creating Your First Playbook

Let's start by creating a simple Ansible playbook that will create a directory and a file on the local machine. This will help you understand the basic structure of a playbook and how to execute it.

First, let's create a new file named first_playbook.yml in the /home/labex/project directory:

nano /home/labex/project/first_playbook.yml

This command opens the nano text editor. If you're not familiar with nano, don't worry - it's a simple text editor. You can type directly into it.

Now, add the following content to the file:

---
- name: My First Playbook
  hosts: localhost
  connection: local
  tasks:
    - name: Create a directory
      file:
        path: /home/labex/project/test_directory
        state: directory
        mode: "0755"

    - name: Create a file
      copy:
        content: "Hello from Ansible!"
        dest: /home/labex/project/test_directory/hello.txt

Let's break down this playbook to understand each part:

  • The --- at the top marks the start of a YAML file. YAML is the format used for Ansible playbooks.
  • name: My First Playbook is a descriptive name for this play. It helps you identify what this playbook does.
  • hosts: localhost specifies that this playbook will run on the local machine. In a real-world scenario, you might specify remote hosts here.
  • connection: local tells Ansible to run the playbook locally instead of using SSH. This is useful for testing and for tasks that need to be performed on the Ansible control node itself.
  • tasks: is followed by a list of tasks to be executed. Each task is an action you want Ansible to perform.
  • Each task has a name for description. This helps you understand what each task does and makes troubleshooting easier.
  • The tasks use Ansible modules:
    • The file module is used to create the directory.
    • The copy module is used to create a file with specific content.

Don't worry if you don't understand all the modules yet. As you progress, you'll learn about many more modules and their uses.

Save and exit the editor. In nano, you can do this by pressing Ctrl+X, then Y, then Enter.

Now, let's run this playbook. In your terminal, type:

ansible-playbook /home/labex/project/first_playbook.yml

This command tells Ansible to run the playbook we just created. You should see output similar to this:

PLAY [My First Playbook] ******************************************************

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [Create a directory] ******************************************************
changed: [localhost]

TASK [Create a file] ***********************************************************
changed: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

This output shows that Ansible executed our tasks successfully. The "changed" status indicates that Ansible made changes to the system (created a directory and a file).

If you want to verify the results manually, you can use these commands:

ls -l /home/labex/project/test_directory
cat /home/labex/project/test_directory/hello.txt

The first command should show the directory we created, and the second should display the content of the file we created.

Understanding Playbook Structure

Now that you've created and run your first playbook, let's dive deeper into its structure. Understanding the structure of a playbook is crucial for writing more complex automation tasks in the future.

Ansible playbooks are composed of one or more plays, and each play consists of several key elements. Let's edit our first_playbook.yml file to add comments explaining each part:

nano /home/labex/project/first_playbook.yml

Update the content as follows:

---
## Playbook starts with three dashes
- name: My First Playbook ## Name of the play
  hosts: localhost ## Target host(s) for this play
  connection: local ## Connection type (local in this case)

  tasks: ## List of tasks to be executed
    - name: Create a directory ## Name of the first task
      file: ## The 'file' module is used for this task
        path: /home/labex/project/test_directory ## Path of the directory to create
        state: directory ## Desired state (create the directory)
        mode: "0755" ## Permissions for the directory

    - name: Create a file ## Name of the second task
      copy: ## The 'copy' module is used for this task
        content: "Hello from Ansible!" ## Content to be written to the file
        dest: /home/labex/project/test_directory/hello.txt ## Destination path for the file

Save and exit the editor.

This commented version of the playbook helps to understand the structure and purpose of each element. Here are some key points to remember:

  1. A playbook can contain multiple plays, each starting with a dash (-). In this case, we have only one play.
  2. Each play targets specific hosts and defines a list of tasks. The hosts field specifies which machines the play should run on.
  3. Tasks use Ansible modules (like file and copy) to perform actions. Ansible has many built-in modules for various purposes.
  4. Each task should have a descriptive name. This helps in understanding what the task does and in troubleshooting.
  5. Indentation is crucial in YAML files. Make sure your playbook is properly indented. Incorrect indentation can cause errors when running the playbook.

The file module is versatile and can be used to create, modify, or delete files and directories. In our case, we're using it to create a directory.

The copy module is used to copy files to remote locations or, as in our case, to create a new file with specific content.

Understanding these basic structures will help you as you move on to create more complex playbooks in the future.

Adding Variables to Playbooks

Variables make your playbooks more flexible and reusable. They allow you to write playbooks that can adapt to different scenarios without needing to change the playbook itself. Let's modify our playbook to use variables.

Edit the first_playbook.yml file:

nano /home/labex/project/first_playbook.yml

Update the content as follows:

---
- name: My First Playbook
  hosts: localhost
  connection: local
  vars:
    dir_path: /home/labex/project/test_directory
    file_content: "Hello from Ansible! The time is {{ ansible_date_time.iso8601 }}"

  tasks:
    - name: Create a directory
      file:
        path: "{{ dir_path }}"
        state: directory
        mode: '0755'

    - name: Create a file
      copy:
        content: "{{ file_content }}"
        dest: "{{ dir_path }}/hello.txt"

    - name: Display file content
      debug:
        msg: "The content of the file is: {{ file_content }}"

Let's break down the changes and new elements in this updated playbook:

  1. We've added a vars section to define variables. This is where you can set values that you'll use multiple times in your playbook.

  2. dir_path and file_content are now variables. We can easily change these values in one place to affect multiple tasks.

  3. We're using the {{ }} syntax to reference variables. This tells Ansible to replace the variable with its value.

  4. We've used Ansible's built-in ansible_date_time.iso8601 variable to include the current timestamp. Ansible provides many such variables that you can use in your playbooks.

  5. A new task using the debug module has been added. The debug module is very useful for displaying information during playbook execution, which can help with troubleshooting.

The use of variables makes this playbook more flexible. For example, if you wanted to change the directory path, you would only need to change it in the vars section, not in every task.

Save and exit the editor.

Now, let's run the updated playbook:

ansible-playbook /home/labex/project/first_playbook.yml

You should see output showing the tasks being executed, including the debug message displaying the file content with the current timestamp. The output will look something like this:

PLAY [My First Playbook] ******************************************************

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [Create a directory] ******************************************************
ok: [localhost]

TASK [Create a file] ***********************************************************
changed: [localhost]

TASK [Display file content] ****************************************************
ok: [localhost] => {
    "msg": "The content of the file is: Hello from Ansible! The time is 2023-06-09T12:34:56Z"
}

PLAY RECAP *********************************************************************
localhost                  : ok=4    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

The actual timestamp will be different when you run the playbook.

This demonstrates how variables can make your playbooks more dynamic. The file content now includes a timestamp that will be different each time you run the playbook.

Summary

In this lab, you've learned the basics of Ansible playbooks. You've gone from creating your first simple playbook to understanding its structure and using variables to make your playbooks more dynamic and reusable.

Key takeaways from this lab:

  1. Ansible playbooks are written in YAML format and describe a set of tasks to be executed on specified hosts.
  2. A playbook consists of one or more plays, each containing a list of tasks.
  3. Tasks use Ansible modules to perform actions on the target hosts. We used the file, copy, and debug modules in this lab.
  4. Variables can be defined and used in playbooks to increase flexibility and reusability. They are referenced using the {{ }} syntax.
  5. The debug module is useful for displaying information during playbook execution, which can help with troubleshooting.
  6. Proper indentation is crucial in YAML files and Ansible playbooks.

As you continue your Ansible journey, you'll find playbooks to be a powerful tool for automating complex IT tasks. Practice writing playbooks for various scenarios to become more comfortable with their structure and capabilities. Try modifying the playbooks we created today - change the directory path, add more tasks, or use different modules.

In future labs, you'll learn about more advanced playbook features, such as conditionals, loops, and roles, which will allow you to create even more powerful and flexible automation workflows.

Remember, the key to mastering Ansible is practice and exploration. Don't be afraid to experiment with different modules and structures in your playbooks. The Ansible documentation is an excellent resource as you continue to learn and grow your skills.

Other Ansible Tutorials you may like