how to read a yaml file and update itself ?

40 views
Skip to first unread message

Eric Chang

unread,
Nov 4, 2021, 9:12:49 PM11/4/21
to Ansible Project
let's said I have a yaml file like

centers.yml

centers:
  - center_id: ABC123
    center_password: 123456789
  - center_id: 123ABC
    center_password: ""

now I want to read the centers.yml , and update center_password with pwgen(8) if center_password is null and write back to centers.yml

How should I do the job ?

Dick Visser

unread,
Nov 5, 2021, 3:04:57 AM11/5/21
to ansible...@googlegroups.com
Is this file local or on your remote host?

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/19fcdb4b-f04b-4f36-af5e-27a1977bea06n%40googlegroups.com.
--
Sent from a mobile device - please excuse the brevity, spelling and punctuation.

Eric Chang

unread,
Nov 7, 2021, 7:58:56 PM11/7/21
to Ansible Project
>> Is this file local or on your remote host?

local
dick....@geant.org 在 2021年11月5日 星期五下午3:04:57 [UTC+8] 的信中寫道:

Dick Visser

unread,
Nov 8, 2021, 5:04:56 AM11/8/21
to ansible...@googlegroups.com
This should work, although it could probably be optimised:


---

- hosts: localhost

  gather_facts: no

  connection: local


  vars:

    filename: /tmp/centers.yml


  tasks:

    - set_fact:

        centers_data: |

          {{ centers_data|default([]) | union([


            item if item.center_password != '' else


            {

              'center_id': item.center_id,

              'center_password': lookup('pipe', 'pwgen -sy 48 1')

            }


          ]) }}


      loop: "{{ lookup('file', filename)|from_yaml|json_query('centers[]') }}"


    - copy:

        content: "{{ {'centers': centers_data} | to_nice_yaml }}"

        dest: /tmp/out.yml







--
Dick Visser
Trust & Identity Service Operations Manager
GÉANT

Eric Chang

unread,
Nov 11, 2021, 8:43:08 PM11/11/21
to Ansible Project
WOW , that's incredible !  thanks !

dick....@geant.org 在 2021年11月8日 星期一下午6:04:56 [UTC+8] 的信中寫道:
Reply all
Reply to author
Forward
0 new messages