stephen mayo
stephen mayo

Reputation: 21

Passing elements of multi-dimensional array in Ansible using Extra-vars

I have a harness to build VMs using Packer that in turn calls Ansible (in local mode) to do the heavy lifting.
I'd like to be able to parameters to Packer (got that), which is passes to Ansible as extra vars.

I can pass an external variables files and also a simple variable such as the example below.

ansible-playbook -v -c local something.yml --extra-vars "deploy_loc=custom"

Thats okay, but I really need to pass more complex array of variables, such as the examples below.
I've tried a number of formatting such as the one below and usually get some kind of delimiter error.

ansible-playbook -v -c local something.yml --extra-vars 'deploy_loc=custom deploy_scen: [custom][ip=1.2.34]}'

Role variable file

# Which location
deploy_loc: 'external-dhcp'

# location defaults
deploy_scen:
  custom:
     ipv4: yes
     net_type: dhcp
     ip: '1.1.1.1'
     prefix: '24'
     gw: '1.1.1.1.254'
     host: 'custom'
     domain: 'domain.com'
     dns1: '1.1.1.2'
  standard-eng:
     ipv4: yes
     net_type: none
     ip: '12.12.12.5'
     prefix: '24'
  external-dhcp:
     ipv4: yes
     net_type: dhcp

Upvotes: 2

Views: 4102

Answers (2)

Bruce P
Bruce P

Reputation: 20759

You can pass a json structure in to ansible via the extra-vars parameter. You have to be a little careful to make sure it's set up properly though. You want to have the parameter look something like this:

--extra-vars {"param1":"foo","param2":"bar","file_list":[ "file1", "file2", "file3" ]}

When I do things like this I typically write a small bash wrapper script that will ensure extra-vars is set up properly and then invokes ansible.

Upvotes: 0

hkariti
hkariti

Reputation: 1719

I think it's more robust and readable to generate a yaml file and use that with vars_files.

Alternatively you can generate a json file and read and parse it using a file lookup and the from_json filter. Something like this:

- name: Read objects
  set_fact: deploy_scen={{lookup('file', 'deploy_scen.json') | from_json}}

However, if you really want --extra-var you can use the dict() function:

-e 'var={{dict(key1=dict(subkey1="value"),key2=dict(subkey1="value2"))}}'

Upvotes: 2

Related Questions