'how to change a element from a list or use "if else" within a loop to assign element
I am querying a table and am only interested in the "name" column. The table is returned as a list of dictionaries, so I pull the "name" from each entry and add it to a list. The thing is that if the name has a certain value, for instance "N/A" I don't want the new list I am populating to pull in the value "N/A" but another value instead, for instance "skip". Here is an example of what I am doing which doesn't work, and the list stays the same:
- name: Extract "name" column from table and append it to new_list
set_fact:
new_list: "{{ new_list + [item.name] }}"
loop: "{{queried_table.record}}"
- name: Iterate through new_list and change "N/A" elements to "skip"
set_fact:
current_name: "skip"
when: current_name == "N/A"
loop: "{{new_list}}"
loop_control:
loop_var: current_name
What I want to do, but in pseudocode:
- name: Extract "name" column from table and append it to new_list
set_fact:
new_list: "{{ if(item.name == "N/A"){
append the word "skip" to new_list instead of "N/A"
}else{append item.name onto new_list}
}}"
loop: "{{queried_table.record}}"
Solution 1:[1]
Q: "Pull 'name' from each entry ... replace 'N/A' with 'skip'."
A: For example, given the table below for testing
queried_table:
record:
- {name: r1, rec: data}
- {name: r2, rec: data}
- {name: N/A, rec: none}
map the attribute name and regex_replace the items
new_list: "{{ queried_table.record|
map(attribute='name')|
map('regex_replace', 'N/A', 'skip')|
list }}"
gives
new_list: [r1, r2, skip]
Put the declaration of new_list into the vars as appropriate.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
