首页 > 解决方案 > 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 }}

我怎样才能做到这一点?

标签: ansible

解决方案


使脚本的输出成为有效的 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

推荐阅读