Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a var into a selectattr statment in Ansible

I am looping through a dict "aws_ec2_volums_setting" and i am trying to pass the loop variable item.id to a "selectattr" statement to get a list that meets the criteria.

- name: Set Filters
  set_fact:
    snapshot_list: "{{ ec2_snapshot_facts.snapshots | selectattr('volume_id', 'equalto', vars[item.id] ) | list }}"
  with_items: "{{ aws_ec2_volums_setting }}"

if I hardcode the value it works fine:

- name: Set Filters
  set_fact:
    snapshot_list: "{{ ec2_snapshot_facts.snapshots | selectattr('volume_id', 'equalto', 'vol-xxxxxxxxx' ) | list }}"
  with_items: "{{ aws_ec2_volums_setting }}"

If I ran a debug command to check the value of the var all looks good

- name: Check Val
  debug:
    msg: "{{ item.id }}"
  with_items: "{{ aws_ec2_volums_setting }}"

Output:

TASK [aws_delete_snapshoot : Set Filters2] ****************************************************************************************
ok: [localhost] => (item={u'vol': u'Vol-01', u'id': u'vol-XXXXXX', u'server': u'us-nv-sat-01'}) => {
    "changed": false,
    "item": {
        "id": "vol-vol-XXXXXX",
        "server": "us-nv-sat-01",
        "vol": "Vol-01"
    },
    "msg": "vol-XXXXXX"
}
like image 231
alexis Avatar asked Dec 06 '25 13:12

alexis


1 Answers

It looks to me like you just need to drop the vars[] and it should work fine. Change vars[item.id] to just item.id.

Try:

- name: Set Filters
  set_fact:
    snapshot_list: "{{ ec2_snapshot_facts.snapshots | selectattr('volume_id', 'equalto', item.id ) | list }}"
  with_items: "{{ aws_ec2_volums_setting }}"
like image 141
Tj Kellie Avatar answered Dec 08 '25 21:12

Tj Kellie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!