Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible global inventory variables

I have a variable that is different for every inventory which i need to access from the playbook. i have tried:

[globalvars]
db=dbhost

[atlanta]
host1
host2

[boston]
host3

I want to use the "db" variable somehow in my playbooks, i have tried various combinations but i have not been able to access the "db" variable from within the playbook.

How can i accomplish this?

like image 261
ShinySpiderdude Avatar asked Apr 10 '16 08:04

ShinySpiderdude


People also ask

How do you declare variables in Ansible inventory?

The preferred practice in Ansible is actually not to store variables in the main inventory file. In addition to storing variables directly in the INI file, host and group variables can be stored in individual files relative to the inventory file. These variable files are in YAML format. Valid file extensions include '.

What is global variables in Ansible?

Ansible has 3 main scopes: Global: this is set by config, environment variables and the command line. Play: each play and contained structures, vars entries, include_vars, role defaults and vars. Host: variables directly associated to a host, like inventory, facts or registered task outputs.

How do you pass multiple vars in Ansible?

Ansible treats values of the extra variables as strings. To pass values that are not strings, we need to use JSON format. To pass extra vars in JSON format we need to enclose JSON in quotation marks: ansible-playbook extra_var_json.

How do you get dynamic inventory in Ansible?

Ways to manage inventories in Ansible Convert inventories from legacy formats into Ansible. Use dynamic inventories with plugins, specifically Nmap. Write your own inventory script to generate inventories dynamically. Write an Ansible inventory plugin.


1 Answers

To define a "global" variable you will need to define it as a variable for the all group

[all:vars]
db=dbhost

[atlanta]
host1
host2

[boston]
host3

This is considered not to be a best practice. In ansible you can define group_vars in a separate directory/file like the following:

# file: group_vars/all
db: "dbhost"

# file: inventory/hosts
[atlanta]
host1
host2

[boston]
host3

group_vars is a directory in your top dir ( where your playbook is ), ansible will include the var files of the group(s) in the play.

Anyway, in both cases you will be able to access the variable as {{ db }} in your templates/playbooks

like image 60
shaps Avatar answered Sep 28 '22 06:09

shaps