Ansible read yaml file and write content to another file with some additional info

Viewed 232

I have a yaml file file1.yaml like this,

name: teshan
age: 420
country: lka # this line might not be present

In my Ansible playbook, I need to read this, add/ modify the country and write to a file2.yaml. And if file1.yaml does not exist I need to create file2.yaml with just the country. I understand I need to load file1 to a dict and modify it. But how do I do this?

Note: This is a part of a very large playbook that I need to modify. The file names are variables. I have had no knowledge in Ansible before today so please excuse me if this is a very noob question. Any help is appericiated.

2 Answers

For example, given the file

shell> cat file1.yaml
name: teshan
age: 420
country: lka

the task below reads the variables from file1.txt to dictionary dict, combines changes, and creates file2.yaml

    - copy:
        dest: file2.yaml
        content: |-
          {{ dict|combine(changes)|to_nice_yaml }}
      vars:
        dict: "{{ lookup('file', 'file1.yaml')|from_yaml }}"
        changes:
          country: tw
shell> cat file2.yaml
age: 420
country: tw
name: teshan

lot of solutions to do that:

- name: "tips1"
  hosts: localhost
  tasks:
    - name: Check if the file exists
      stat:
        path: file1.yaml
      register: stat_result

    - name: Create the file, if it doesnt exist already
      copy: 
        dest: file2.yaml
        content: |
          country: wahtyouwant
      when: not stat_result.stat.exists

    - name: copy file modified
      copy: 
        dest: file2.yaml
        content: |-
            {{ stuff | combine(newcountry) | to_nice_yaml }}
      vars:
        stuff: "{{ lookup('file', 'file1.yaml') | from_yaml }}"
        newcountry:
          country: whatyouwant
      when: stat_result.stat.exists
Related