How To Use Variables in Ansible Playbooks: Useful Tips and Tricks

In this blog post, we will explore how variables work in Ansibles playbooks and what you can do with them!

Ansible is a popular IT automation tool that simplifies the process of managing servers and other pieces of infrastructure. Ansible playbooks are Ansible’s configuration management scripts, which can be used to create policies for organizations.

Variables in Ansible Playbook are useful because they allow you to change settings without having to edit or rewrite your playbook each time. They also allow you to reuse bits of code between tasks.

Ansible uses an Ansible Variables data structure to store all the variables used throughout your playbook.

When you run Ansible, it will look at all of the tasks in a given play and assign each variable its corresponding value from the host machine or other place where Ansible is storing information about how to configure that host. You can also use Ansible variables to group your Ansible tasks into logical units that make sense for the organization you are working with.

In Ansible, a variable can hold either a string or an array of strings. If you want to use multiple lines in a task’s body, it is easy to do by adding line breaks and indentations inside quotes.

Create Variable

The following playbook example creates a variable called myvar and prints it in the last line of the code.

---
- hosts: localhost
  vars:
    - myvar: "ntweekly.com"
  tasks:
    - name: print variables
      debug:
        msg: "Blog URL: {{ myvar }}"

The output of the playbook will look like this.

Processing…
Success! You're on the list.

Posted

in

by