chetan
chetan

Reputation: 111

Multiple different commands in loop

I am trying to convert a yml file into json. I need to pick the list of yml files from file1.txt and convert all those files to json.

Below is the code that I am using

- hosts: localhost
  tasks:
    - name: convert yml to json
      shell: cat /home/testadmin/{{ item }}.yml
      register: result
    - copy:
        dest: ./{{ item }}.json
        content: "{{ result.stdout | from_yaml | to_nice_json }}"
      with_lines: cat file1.txt

The code should pick up the filename from file1.txt and then convert the file 1 by 1. I would like to know how to put all these commands to convert yml to json in a loop.

The actual result should replace all the .yml files in file1.txt and convered into the json format with the same name

Upvotes: 0

Views: 305

Answers (1)

clockworknet
clockworknet

Reputation: 3046

A loop only works on the task that it is attached to. To wrap multiple tasks in a loop, you need to split them out to another file, use an include statement to load them, and then attach the loop to that include statement.

In your case tho, none of that is required. I think this should do what you are looking for, presuming that file1.txt contains a list of file names, one per line & without file extension:

- host: localhost
  connection: local
  tasks:
    - name: Convert each file listed in file1.txt
      copy:
        dest: "./{{ item | trim }}.json"
        content: "{{ lookup('file', item + '.yml') | from_yaml | to_nice_json }}"
      with_lines: cat ./file1.txt
  • connection: local stops Ansible opening a SSH connection to the localhost
  • {{ item | trim }} takes each item from the list and trims any leading or trailing whitespace
  • lookup('file', item + '.yml') reads a file. item is the default variable name used in loops to contain the contents of each element of the loop
  • with_lines only works locally, so if you need to run this remotely, you will need to modify this

Upvotes: 1

Related Questions