How to Use Variables in an Ansible Playbook

In this post, I will show you a very simple example on how to use variables inside an Ansible playbook.

Variables

With Ansible, we can define variables in a few places, but today the main focus will be using variables inside a playbook.

Variables are good to use when you want to keep the code clean and make changes in one place rather than make multiple changes in the playbook. The following example shows how to uninstall Git (to install Git with ansible, visit this post)

Uninstall Git

As you can see in the following code, I am creating a section called vars. In the section, I have a var called package_name with the value of git.

Below is the code. I am removing a package using the name inside the package_name variable. To use the variable, I am using “{{ variable_name }}”

---
- hosts: servers
  vars:
    package_name: git 
  tasks:
    - name: Update repository
      apt_repository:
       repo: 'ppa:git-core/ppa'
       state: present
    - name: remove git
      apt: 
       name: "{{ package_name }}"
       state: absent
       update_cache: yes

In the above case, I have used one variable but you can use as many varialbles as you like.

Processing…
Success! You're on the list.

Posted

in

by