如何在Ansible中加入字符串列表? [英] How to join a list of strings in Ansible?
问题描述
在Ansible中,我有一个要与换行符结合的字符串列表,以创建一个字符串,当写入文件时,它将变成一系列行.但是,当我使用join()过滤器时,它适用于内部列表(字符串中的字符),而不适用于外部列表(字符串本身).这是我的示例代码:
In Ansible, I have a list of strings that I want to join with newline characters to create a string, that when written to a file, becomes a series of lines. However, when I use the join() filter, it works on the inner list, the characters in the strings, and not on the outer list, the strings themselves. Here's my sample code:
# Usage: ansible-playbook tst3.yaml --limit <GRP>
---
- hosts: all
remote_user: root
tasks:
- name: Create the list
set_fact:
my_item: "{{ item }}"
with_items:
- "One fish"
- "Two fish"
- "Red fish"
- "Blue fish"
register: my_item_result
- name: Extract items and turn into a list
set_fact:
my_list: "{{ my_item_result.results | map(attribute='ansible_facts.my_item') | list }}"
- name: Examine the list
debug:
msg: "{{ my_list }}"
- name: Concatenate the public keys
set_fact:
my_joined_list: "{{ item | join('\n') }}"
with_items:
- "{{ my_list }}"
- name: Examine the joined string
debug:
msg: "{{ my_joined_list }}"
我想获得如下输出:
One fish
Two fish
Red fish
Blue Fish
我得到的是:
TASK: [Examine the joined string] *********************************************
ok: [hana-np-11.cisco.com] => {
"msg": "B\nl\nu\ne\n \nf\ni\ns\nh"
}
ok: [hana-np-12.cisco.com] => {
"msg": "B\nl\nu\ne\n \nf\ni\ns\nh"
}
ok: [hana-np-13.cisco.com] => {
"msg": "B\nl\nu\ne\n \nf\ni\ns\nh"
}
ok: [hana-np-14.cisco.com] => {
"msg": "B\nl\nu\ne\n \nf\ni\ns\nh"
}
ok: [hana-np-15.cisco.com] => {
"msg": "B\nl\nu\ne\n \nf\ni\ns\nh"
}
如何正确地将字符串列表与换行符连接起来?
How do I properly concatenate a list of strings with the newline character?
推荐答案
解决方案
join
过滤器适用于列表,因此将其应用于列表:
join
filter works on lists, so apply it to your list:
- name: Concatenate the public keys
set_fact:
my_joined_list: "{{ my_list | join('\n') }}"
说明
虽然示例中的my_list
是列表,但是当您使用with_items
时,在每次迭代中item
都是字符串.字符串被视为字符列表,因此join
会将它们拆分.
While my_list
in your example is a list, when you use with_items
, in each iterationitem
is a string. Strings are treated as lists of characters, thus join
splits them.
就像任何一种语言一样:当您有一个循环for i in (one, two, three)
并在循环内引用i
时,每次迭代只会得到一个值,而不是整个集合.
It’s like in any language: when you have a loop for i in (one, two, three)
and refer to i
inside the loop, you get only one value for each iteration, not the whole set.
备注
-
不要使用
debug
模块,但是要使用copy
和content
将\n
呈现为换行符.
Don’t use
debug
module, butcopy
withcontent
to have\n
rendered as newline.
创建列表的方式非常繁琐.您所需要做的就是(也不需要引号):
The way you create a list is pretty cumbersome. All you need is (quotation marks are also not necessary):
- name: Create the list
set_fact:
my_list:
- "One fish"
- "Two fish"
- "Red fish"
- "Blue fish"
这篇关于如何在Ansible中加入字符串列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!