如何在 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 }}"
我想得到如下所示的输出:
I want to get output that looks like:
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屋!