在Ansible中,我有一个字符串列表,我想用换行符加入以创建一个字符串,当写入文件时,它变成一系列行.但是,当我使用join()过滤器时,它适用于内部列表,字符串中的字符,而不是外部列表中的字符串本身.这是我的示例代码:
# 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 }}"
Run Code Online (Sandbox Code Playgroud)
我想得到如下输出:
One fish
Two fish
Red fish
Blue Fish
Run Code Online (Sandbox Code Playgroud)
我得到的是:
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"
}
Run Code Online (Sandbox Code Playgroud)
如何正确连接字符串列表与换行符?
tec*_*raf 26
解
join 过滤器适用于列表,因此将其应用于您的列表:
- name: Concatenate the public keys
set_fact:
my_joined_list: "{{ my_list | join('\n') }}"
Run Code Online (Sandbox Code Playgroud)
说明
虽然my_list在您的示例中是一个列表,但在您使用时with_items,每次迭代item都是一个字符串.字符串被视为字符列表,因此join将它们分开.
它就像在任何语言中一样:当你有一个循环for i in (one, two, three)并引用循环i内部时,每次迭代只得到一个值,而不是整个集合.
备注
不要使用debug模块,而是copy与content已经\n呈现为换行符.
创建列表的方式非常繁琐.你只需要(引号也没有必要):
- name: Create the list
set_fact:
my_list:
- "One fish"
- "Two fish"
- "Red fish"
- "Blue fish"
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
33457 次 |
| 最近记录: |