1

I have written an shell script that outputs an list of applications and the ports on which these applications listen (I can ajust this output to anything I want)

{ application: 'foo', port: '10' }
{ application: 'bar', port: '20' }

First the shell script is executed in ansible and the output is in an variable: outputscript.

Now I want to use this in an ansible loop something like this:

- 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 }}

How can I do this?

1
  • 1) I don't see a script call anywhere nor a result registed in your above example. So we have no idea how you are doing this exactly 2) your example script output is not formatted correctly as code and, as is, does not respect any know serialization standard (json, yaml, xml...) so how are you planning to parse this exactly ? Are you outputting one result per line ? Or a full result list at once that should be parsed as a whole ? Please edit your question and clarify. You should also show your current attempts to achieve your goal and describe the exact problem your are facing. Commented Nov 25, 2020 at 15:51

1 Answer 1

1

Make the output of the script a valid YAML. For example

shell> cat my_script.sh
#!/bin/bash
echo '{application: foo, port: 10}'
echo '{application: bar, port: 20}'

Then, the plabook below

- 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 }}"

gives

shell> cat ~/foo/file.txt 
Listen 10

shell> cat ~/bar/file.txt 
Listen 20
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.