How to define hash (dict) in ansible inventory file?
Asked Answered
P

2

12

I am able to define a hash(dict) like below in group_vars/all:

region_subnet_matrix:
  site1:
    region: "{{ aws_region }}"
    subnet: "subnet-xxxxxxx"
    zone: "{{aws_region}}a"
  site2:
    region: "{{ aws_region }}"
    subnet: "subnet-xxxxxxx"
    zone: "{{aws_region}}b"

but for the life of me, I could not figure out how to define it under hosts file

[all:vars]
region_subnet_matrix="{
  site1:
    region: "{{ aws_region }}"
    subnet: "subnet-xxxxxxx"
    zone: "{{aws_region}}a"
  site2:
    region: "{{ aws_region }}"
    subnet: "subnet-xxxxxxx"
    zone: "{{aws_region}}b"
}"

I know it was incorrect, but I don't know the right way. Can someone enlighten me, please?

Popelka answered 24/4, 2015 at 20:19 Comment(0)
F
14

As I read the source code of Ansible, values of variables in inventory files are evaluated by "ast.literal_eval()" of Python. So you can describe dict variables in inventory files by one-line Python literals.

Your example might look like:

[all:vars]
region_subnet_matrix={'site1': {'subnet': 'subnet-xxxxxxx', 'region': '{{ aws_region }}', 'zone': '{{aws_region}}a'}, 'site2': {'subnet': 'subnet-xxxxxxx', 'region': '{{ aws_region }}', 'zone': '{{aws_region}}b'}}

Make sure that no variables are evaluated in this example.

N.B.: I don't know this kind of inventory variable definition is officially permitted.

Favorite answered 3/7, 2015 at 5:46 Comment(2)
A few years later, this is not working anymore and ansible (2.9) outputs a warning with the parsing failure: Expected key=value host variable assignment.Potpourri
My bad, it works when putting the dictionary between quotes, e.g. data_partition="{'shard1': '/data', 'shard2': '/data2'}". See: #18572592Potpourri
S
7

You can't use dict in inventory file because it use ini format. The preferred practice in Ansible is actually not to store variables in the main inventory file. Host and group variables can be stored in individual files relative to the inventory file.

Assuming the inventory file path is: /etc/ansible/hosts

If the host is named ‘testserver’ variables in YAML file at the following location will be made available to the host: /etc/ansible/host_vars/testserver.

The data in the this file might look like:

region_subnet_matrix:
  site1:
    region: "{{ aws_region }}"
    subnet: "subnet-xxxxxxx"
    zone: "{{aws_region}}a"
  site2:
    region: "{{ aws_region }}"
    subnet: "subnet-xxxxxxx"
    zone: "{{aws_region}}b"

Read more here.

Situs answered 25/4, 2015 at 10:15 Comment(2)
Also a host_vars folder is part of the Ansible best practices directory layout.Quirinal
As of 2.4, you can use YAML in an inventory file: docs.ansible.com/ansible/latest/plugins/inventory/yaml.htmlScrape

© 2022 - 2024 — McMap. All rights reserved.