Once you load your csv into a variable using the corresponding read_csv
module, you can filter and select values inside the list with the usual filtering tools (selectattr
, map
, ...)
For the demo, I placed your above file in files/example.csv
. Then the following playbook.yml
:
---
- name: Parse csv and filtering demo
hosts: localhost
gather_facts: false
tasks:
- name: read in our csv file in a list
read_csv:
path: files/example.csv
delimiter: ;
register: hosts_info
- name: Show the entire info we parsed (if running with `-v`)
debug:
var: hosts_info.list
verbosity: 1
- name: Show ip depending on fqdn and type
vars:
ip: >-
{{
hosts_info.list
| selectattr('fqdn', '==', item.fqdn)
| selectattr('Typ', '==', item.type)
| map(attribute='IPAddress')
| list
| first
}}
debug:
msg: "The ip of {{ item.fqdn }} for type {{ item.type }} is {{ ip }}"
loop:
- fqdn: aaa.domain.tld
type: db
- fqdn: aaa.domain.tld
type: log
gives (run with -v
to see the intermediate debug)
$ ansible-playbook playbook.yml
PLAY [Parse csv and filtering demo] ****************************************************************************************************************************************************************************************************
TASK [read in our csv file in a list] **************************************************************************************************************************************************************************************************
ok: [localhost]
TASK [Show the entire info we parsed (if running with `-v`)] ***************************************************************************************************************************************************************************
skipping: [localhost]
TASK [Show ip depending on fqdn and type] **********************************************************************************************************************************************************************************************
ok: [localhost] => (item={'fqdn': 'aaa.domain.tld', 'type': 'db'}) => {
"msg": "The ip of aaa.domain.tld for type db is 10.1.1.1"
}
ok: [localhost] => (item={'fqdn': 'aaa.domain.tld', 'type': 'log'}) => {
"msg": "The ip of aaa.domain.tld for type log is 10.2.2.2"
}
PLAY RECAP *****************************************************************************************************************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0