Skip to content

Managing Ansible Variables

Avatar photo

https://www.linkedin.com/in/gineesh/ https://twitter.com/GiniGangadharan

Ansible Variables

You can use variables in ansible plays to store values like users to create, packages to install etc. By using variables, you can manage your plays with dynamic input values.

See Automation with Ansible full chapters.

Example Variable usages:

  • Users to create
  • Packages to install
  • Services to restart
  • Files to more or create

Refer : Ansible Documentation

Variables Naming

You can use any custom naming for your variable but remember to start with a letter and only include letters, numbers and underscores.

Valid Variable NamesInvalid Names
file_namefile name
new_servernew.server
webserver_11st webserver
router_ip_101router-ip-$1

Defining Variables

You can define variables at different levels in Ansible project and in a simple view, we must learn below scopes.

  • Global Scope – when you set variables in Ansible configuration or via command line.
  • Play Scope – set in the play
  • Host Scope – when you set variables for hosts or groups inside inventory, fact gathering or registered tasks.

Variables in Playbook

You can define variables simply inside playbook by vars block or by vars_files directive.

- name: Install and configure lamp
  hosts: lamp
  vars:
    firewall_service: firewalld
    web_package: httpd

If you are using vars_files, you need to define variables inside a yaml file and call it inside playbook.

$ cat vars/myvars.yml
web_package: httpd
firewall_service: firewalld

And use vars_files directive as below

.......
  tasks:
    - name: Include the variable file
      include_vars: vars/myvars.yml
....

So, how can you use these variables inside playbook ?

You can simply call the variable as below.

    # This line will read as : "Install httpd"
    - name: Install {{ web_package }}
      yum:
        name: "{{ web_package }}"
        state: latest

Please note, when you call variable as first element, make sure you have used quotes as shown above.

Host Variables and Group Variables

You can define variable on host level or group level via inventory; but please note, variable defined in playbook will take precedence of both.

# example for host variable
[servers]
servera.example.com ansible_user=devops
serverb.example.com ansible_user=sysadmin

# example for group variable
[servers:vars]
web_package=httpd

Defining variables inside inventory will make the inventory file messy. So the recommended way is to use group_vars and host_vars directories where you can save files with variables for each hosts or groups.

$ cat group_vars/servers
# This is the group variable for hostgroup servers.
user: devops

$ cat group_vars/webservers
# This is the group variable for hostgroup webservers.
web_package: httpd

$ cat host_vars/servera.example.com
# This is the host variable for servera.example.com
ansible_user: devops

$ cat host_vars/serverb.example.com
# This is the host variable for serverb.example.com
ansible_user: sysadmin

How to override variable from command line ?

Okay, you have defined variables in playbook or host_vars or group_vars. But, what if you need to test with different value for a variable ? Simple, you don’t need change anything in playbook or host_vars; you can simply override the variable while executing playbook as below; using option -e.

$ ansible-playbook web.yml --limit=server2.example.com -e "package=apache"

Usage of Variable Arrays

When you have multiple variables which are related, you can easily define them as arrays instead of individual variables. See below, the variables on left side can easily define as array as right side.

user1_firstname: John
user1_lastname: Brandon
user1_designation: SysAdmin
user2_firstname: Marry
user2_lastname: Brown
user2_designation: Developer
users:
  bjohn:
    firstname: John
    lastname: Brandon
    designation: SysAdmin
  bmarry:
    firstname: Marry
    lastname: Brown
    designation: Developer

And you can call them conveniently as below

users.bjohn.firstname
users.bmarry.designation

# or in Python style dictionary, which is better than dot notation.
users['bmarry']['lastname']

Registered Variables

We can capture the output of a task in a variable using register statement; which is called registered variable. The content of registered variable can use for checking some conditions or for debugging purposes.

   - name: install the web package
     yum:
      name: nginx-new
      state: latest
     register: package
   - name: print jason output
     debug: var=package
   - name: print package failed
     debug:
      msg: "Package Failed"
     when: package.failed == true

See Automation with Ansible full chapters.

Disclaimer:

The views expressed and the content shared in all published articles on this website are solely those of the respective authors, and they do not necessarily reflect the views of the author’s employer or the techbeatly platform. We strive to ensure the accuracy and validity of the content published on our website. However, we cannot guarantee the absolute correctness or completeness of the information provided. It is the responsibility of the readers and users of this website to verify the accuracy and appropriateness of any information or opinions expressed within the articles. If you come across any content that you believe to be incorrect or invalid, please contact us immediately so that we can address the issue promptly.

Avatar photo


https://www.linkedin.com/in/gineesh/ https://twitter.com/GiniGangadharan
Gineesh Madapparambath is the founder of techbeatly and he is the co-author of The Kubernetes Bible, Second Edition. and the author of 𝗔𝗻𝘀𝗶𝗯𝗹𝗲 𝗳𝗼𝗿 𝗥𝗲𝗮𝗹-𝗟𝗶𝗳𝗲 𝗔𝘂𝘁𝗼𝗺𝗮𝘁𝗶𝗼𝗻. He has worked as a Systems Engineer, Automation Specialist, and content author. His primary focus is on Ansible Automation, Containerisation (OpenShift & Kubernetes), and Infrastructure as Code (Terraform). (aka Gini Gangadharan - iamgini.com)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.