Home > other >  Dynamically generating complex data in Ansible
Dynamically generating complex data in Ansible

Time:06-18

I'm facing the following problem set in writing an Ansible playbook:

A list is given to me:

rooms:
  - room_name: bedroom-1
    chairs: 1
  - room_name: bedroom-2
    chairs: 0
  - room_name: bathroom
    chairs: 0
  - room_name: kitchen
    chairs: 4

And I need to transform that into a list of dictionaries with these two keys per item:

  1. chair_name: <room_name>-chair-<chair_number>
  2. room_name: <room_name>

With the example above that would give me:

chair_names:
  - chair_name: bedroom-1-chair-1
    room_name: bedroom-1
  - chair_name: kitchen-chair-1
    room_name: kitchen
  - chair_name: kitchen-chair-2
    room_name: kitchen
  - chair_name: kitchen-chair-3
    room_name: kitchen
  - chair_name: kitchen-chair-4
    room_name: kitchen

I've been struggling to accomplish this using Ansible. Is there a way to do it?

CodePudding user response:

Use Jinja to create the structure

    chair_names_str: |-
      {% for room in rooms %}
      {% for i in range(room.chairs) %}
      - chair_name: {{ room.room_name }}-chair-{{ i }}
        room_name: {{ room.room_name }}
      {% endfor %}
      {% endfor %}
    chair_names: "{{ chair_names_str|from_yaml }}"

gives

  chair_names:
    - {chair_name: bedroom-1-chair-0, room_name: bedroom-1}
    - {chair_name: kitchen-chair-0, room_name: kitchen}
    - {chair_name: kitchen-chair-1, room_name: kitchen}
    - {chair_name: kitchen-chair-2, room_name: kitchen}
    - {chair_name: kitchen-chair-3, room_name: kitchen}
  • Related