问题
I need to have all the userid in a single variable, all separated by \n. Code is as below.
- name: Retrieve the user id and instance
shell: ls -l {{item}} | grep -v total| awk '{print $3}'
register: find_result_userid
with_items:
- /tmp/log/logs/log1
- /tmp/log/logs/log2
- /tmp/log/logs/log3
- name: Combine all userid
set_fact:
server_names: "{{ find_result_userid.results | map(attribute='stdout_lines')|list }}"
The output is as below.
ok: [localhost] => {
"ansible_facts": {
"server_names": [
[
"root",
"root",
"root"
],
[
"root",
"root",
"root"
],
[
"root",
"root",
"root"
]
]
},
"changed": false
}
I need something like below: i.e all ids separated by a line in a single variable.
"server_names": [
[
"root",
"root",
"root",
"root",
"root",
"root",
"root",
"root",
"root"
]
Kindly advise.
回答1:
flatten the lists
- set_fact:
server_names: "{{ server_names|flatten }}"
回答2:
If the number of items you are iterating with is static, I would guess, that you can use the + operator to append the your results
- name: Combine all userid
set_fact:
server_names: "{{ find_result_userid.results[0].stdout_lines + find_result_userid.results[1].stdout_lines + find_result_userid.results[2].stdout_lines}}"
Otherwise if it is not static, I think Vladimir Botkas answer is better.
回答3:
Combining with what Vladmir Botka suggested, to get result in a single task.
- name: Combine all userid
set_fact:
server_names: "{{ find_result_userid.results | map(attribute='stdout_lines')|list | flatten }}"
来源:https://stackoverflow.com/questions/56886502/formatting-set-fact-variable