Global Variables with Ansible

Ansible is a great tool for IT automation. It’s similar to Chef and Puppet, just better! 

I wrote here already an introduction to Ansible. In Ansible you have roles and playbooks. A playbook can contain several roles. Inside a role you can have tasks, files, handlers and variables. But sometimes you want to use a variable across multiple roles. Unfortunately Ansible doesn’t have really a concept of global vars, but there is a trick 😉 

You can define group variables for ALL groups, that is indeed like a global variable. I manage my Ansible code in a git repo. The file tree looks like this: 

infrastructure
  \__ group_vars
     \__ all
        \__ vars_file.yml
  \__ roles 
  \__ ansible.cfg
  \__ site.yml
  \__ hosts

 

The variables defined in “group_vars/all/vars.yml” are accessible from ALL roles! 

Published by Robert Reiz

CEO @ VersionEye. Passionated software developer since 1998.

3 thoughts on “Global Variables with Ansible

  1. Defining variables under “group_vars/all” should also work.

    This is a much more elegant solution to global variables than to use vars_files, which is what I normally see people use.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: