ansible - Ansible +外部shell脚本如何循环输出
问题描述
我编写了一个 shell 脚本,它输出应用程序列表和这些应用程序侦听的端口(我可以将此输出调整为我想要的任何内容)
{ application: 'foo', port: '10' }
{ application: 'bar', port: '20' }
首先,shell 脚本在 ansible 中执行,输出在一个变量中:outputscript。
现在我想在 ansible 循环中使用它,如下所示:
- name: Execute script
shell: "/home/test/test.sh"
register: output_script
- name: change file
line_in_file:
path: /home/{{ item.application }}/file.txt
regex: '^LISTEN '
insertafter: '^#LISTEN '
line: Listen {{ item.port }}
with_items:
- {{ output_script.stdout_lines }}
我怎样才能做到这一点?
解决方案
使脚本的输出成为有效的 YAML。例如
shell> cat my_script.sh
#!/bin/bash
echo '{application: foo, port: 10}'
echo '{application: bar, port: 20}'
然后,下面的plabook
- hosts: localhost
tasks:
- command: "{{ ansible_env.PWD }}/my_script.sh"
register: outputscript
- file:
state: directory
path: "{{ ansible_env.HOME }}/{{ item.application }}"
loop: "{{ outputscript.stdout_lines|map('from_yaml')|list }}"
- lineinfile:
path: "{{ ansible_env.HOME }}/{{ item.application }}/file.txt"
create: true
line: "Listen {{ item.port }}"
loop: "{{ outputscript.stdout_lines|map('from_yaml')|list }}"
给
shell> cat ~/foo/file.txt
Listen 10
shell> cat ~/bar/file.txt
Listen 20
推荐阅读
- google-chrome - 如何使用命令行对接bottem devtools
- spring - 为什么没有更多地使用 Vert.x?
- python-3.x - 如何正确地将共享列表传递给进程或线程?
- ios - 在地图 Swift 上选择注释时坐标为零
- omnet++ - 关于开关的 Omnet++ 模拟
- r - bookdown 到 html_document2 中的数字列表
- php - 图片路径未上传到数据库php codeigniter
- android - android 的 AES 加密问题 - 使用 react-native-crypto-js 包进行开发与发布构建
- google-sheets - 登录后的 ImportXML 功能
- c# - 从 StandardOutput.ReadToEnd 获取整个输出时遇到问题