programpee
programpee

Reputation: 13

How do I search within variables on Yaml files for my jinja 2

How do I check for a string within a variable, and return another part of that variable?

I have the following within my host_vars

vrfs:
  - { vrf: vrf-sitea, enabled: y,}
  - { vrf: vrf-siteb, enabled: n,}
  - { vrf: vrf-sitec, enabled: y,}
  - { vrf: vrf-sited, enabled: y,}

And I am trying to figure out how I search a string within it, and when that is matched, check if y is there.

For example, if the vrf = vrf-siteb, then see if enabled is y.

I want to be able to make vrf-siteb a variable but not sure where to start.

Upvotes: 1

Views: 271

Answers (3)

Vladimir Botka
Vladimir Botka

Reputation: 68024

Create a dictionary. For example, use items2dict

    - set_fact:
        vrfs_dict: "{{ vrfs|items2dict(key_name='vrf', value_name='enabled') }}"
    - debug:
        var: vrfs_dict

gives

  vrfs_dict:
    vrf-sitea: y
    vrf-siteb: n
    vrf-sitec: y
    vrf-sited: y

Then the searching is trivial. For example

    - debug:
        var: vrfs_dict['vrf-siteb']

gives

  vrfs_dict['vrf-siteb']: n

Because of the dash "-" inside the names, the keys are not valid variables. As a result, dotted format can't be used

    - debug:
        var: vrfs_dict.vrf-siteb

gives

  vrfs_dict.vrf-siteb: VARIABLE IS NOT DEFINED!

Upvotes: 0

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39119

You could use json_query and the JMESPath query language for this :

- hosts: localhost
  gather_facts: no
  
  tasks:
    - debug: 
        msg: "{{ vrfs | json_query('[?enabled == `y`].vrf') }}"
      vars:
        vrfs:
          - { vrf: vrf-sitea, enabled: y,}
          - { vrf: vrf-siteb, enabled: n,}
          - { vrf: vrf-sitec, enabled: y,}
          - { vrf: vrf-sited, enabled: y,}

Gives:

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

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": [
        "vrf-sitea",
        "vrf-sitec",
        "vrf-sited"
    ]
}

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

Upvotes: 2

flyx
flyx

Reputation: 39678

You can use filters to get the right object with selectattr and then get the enabled value with map:

{{ vrfs | selectattr('vrf', 'vrf-siteb') | map(attribute='enabled') }}

Upvotes: 1

Related Questions