Jacob Evans
Jacob Evans

Reputation: 323

how can I override a key value in ansible arrays without destroying the array

I'm looking for a way to override a specific key in my array without overriding the entire array.

Example:

Playbook:

---
- hosts: hostgroup
  vars:
    program:
      name: customname
      option1: customoption

Inventory:

program:
  name: groupname
  option2: group

Defaults/main

program:
  name: defaultname
  option1: default
  option2: default
  option3: default

I'm expecting these values to override as such:

program:
  name: customname
  option1: customoption
  option2: group
  option3: default

However, my actual values are:

program:
  name: customname
  option1: customoption

Source https://gist.github.com/JakeDEvans/ed13514e6d3614c3381a

Upvotes: 0

Views: 2479

Answers (2)

Petro026
Petro026

Reputation: 1309

I'm assuming defaults_main.yml is really a role defaults variable file (e.g. roles/role_name/defaults/main.yml) and the "actual values" are what you're seeing inside the role.

Another option would be to template out the program struct in your play definition. For example you would have:

- hosts: hostgroup
  vars:
    program:
      name: customname
      option1: customoption
      option2: "{{ program_inv.option2 | default('some_value') }}"
      option3: "{{ program_role.option3 | default('other_value') }}"
  roles:
  .......

where program_inv is defined in a host_var or group_var file and program_role is defined in the role_name/defaults/main.yml. This way you can at least run your role with the expected values in one dict.

EDIT: added some defaults but as you point out....still messy

Upvotes: 0

Jacob Evans
Jacob Evans

Reputation: 323

This is not possible in Ansible 1.9.4, but it is possible in 2.0 as vars become hashes.

To combine hashes, use the filter combine: http://docs.ansible.com/ansible/playbooks_filters.html

{{ program|combine(program_inventory|combine(program_playbook)) }}

Upvotes: 1

Related Questions