felix001
felix001

Reputation: 16691

Check for Value for a Key in Dict within Ansible

I want to run a Ansible Task in a string(vlan) is found within a keys (name) value. i.e

dict

interfaces_l3:
  - name: vlan101
    ipv4: 192.168.1.100/24
    state: present

task

- name: Enable Features
  nxos_feature:
     feature: interface-vlan
     state: enabled
  when: vlan in interfaces_l3.values()

This is what I have but currently, this is not working.

Upvotes: 0

Views: 213

Answers (1)

larsks
larsks

Reputation: 311288

There are a few problems with your expression:

  1. interfaces_l3.values() should just blow up, because interfaces_l3 is a list, and lists don't have a .values() method.

  2. You are referring to a variable named vlan rather than a string "vlan".

You are asking if any item in the interfaces_l3 list contains the string "vlan" in the value of the name attribute. You could do something like this:

---
- hosts: localhost
  gather_facts: false
  vars:
    interfaces_l3_with_vlan:
      - name: vlan101
        ipv4: 192.168.1.100/24
        state: present

    interfaces_l3_without_vlan:
      - name: something else
        ipv4: 192.168.1.100/24
        state: present

  tasks:
    - name: this should run
      debug:
        msg: "enabling features"
      when: "interfaces_l3_with_vlan|selectattr('name', 'match', 'vlan')|list"

    - name: this should be skipped
      debug:
        msg: "enabling features"
      when: "interfaces_l3_without_vlan|selectattr('name', 'match', 'vlan')|list"

Which produces the following output:

PLAY [localhost] ******************************************************************************************************************************************************************************

TASK [this should run] ************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": "enabling features"
}

TASK [this should be skipped] *****************************************************************************************************************************************************************
skipping: [localhost]

PLAY RECAP ************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0   

Upvotes: 2

Related Questions