还有另一种方法,您可以使用像 awk
这样的 bash 命令将文件处理为文本文件。
如果文件内容如下:
cat /tmp/test.ini
[group1]
host1
host2
[group2]
host3
host4
[first_two_groups:children]
group1
group2
[group3]
host5
host6
[group4]
host7
host8
当文件具有Linux EOL时,您可以使用以下命令:
awk "/first_two_groups\:children/,/^$/" /tmp/test.ini | grep -v children
group1
group2
要查找的子组所在的组名为first_two_groups
,它可以出现在文件的任何位置。只要在组定义后有空行作为awk流的结束锚点,该命令就可以正常工作。我认为大多数人在ansible清单文件中添加空行以提高可读性,我们可以利用这一事实。
如果文件恰好具有Windows EOL,则命令为
awk "/first_two_groups\:children/,/^[\\r]$/" /tmp/test.ini | grep -v children
使用Ansible的示例可能是这样的:
- name: get group children
shell: awk "/first_two_groups\:children/,/^$/" /tmp/test.ini | grep -v children
register: chlldren
- debug: var=children.stdout_lines
以上内容尚未完全测试,但如果出现问题,则可能是在 shell 模块中转义特殊字符时出现的问题。请记住 - 当您在 ansible shell 模块中传递特殊字符(如冒号)时,请使用 jinja 扩展 - 而不是使用
:
,请使用
{{ ':' }}
。
此外,为了保持一致的 bash 行为,建议在任务末尾显式添加可执行文件。
args:
executable: /bin/bash
with_items: "{{ groups['satellites'] }}"
有什么问题? - stacksonstacks