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?
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 '.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With