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

Benson Jin picture Benson Jin · Apr 24, 2015 · Viewed 17.3k times · Source

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?

Answer

Norio Kimura picture Norio Kimura · Jul 3, 2015

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.