perl
perl

Reputation: 65

Rewriting the yaml variable (ansible)

I have a variable:

"result":[
            {
            "item": "192.168.0.1",
            "stdout_lines": [
                "a",
                "b",
                "c",
                "d",
                "e",
              ]
             },
            {
            "item": "192.168.0.2",
            "stdout_lines": [
                "aa",
                "bb",
                "cc",
               ]
            }
         ]

I want to get the following variable:

"result":[
            {
            "item": [
                "192.168.0.1",
                "192.168.0.1",
                "192.168.0.1",
                "192.168.0.1",
                "192.168.0.1",
               ]
            "stdout_lines": [
                "a",
                "b",
                "c",
                "d",
                "e",
              ]
             },
            {
            "item": [
                "192.168.0.2",
                "192.168.0.2",
                "192.168.0.2",
               ]
            "stdout_lines": [
                "aa",
                "bb",
                "cc",
               ]
            }
         ]

That is, I need the value of "item" to be repeated as many times as the values in "stdout_lines". The values of "stdout_lines" always change, "stdout_lines" can have a different number of values.

How can I do this?

Upvotes: 0

Views: 230

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68254

For example

    - set_fact:
        _tmp: "{{ _tmp|d([]) + [item|combine({'item': _items.split()})] }}"
      loop: "{{ result }}"
      vars:
        _count: "{{ item.stdout_lines|length }}"
        _item: "{{ item.item }} "
        _items: "{{ _item * _count|int }}"
    - set_fact:
        result: "{{ _tmp }}"

gives the expected result

result:
  - item:
    - 192.168.0.1
    - 192.168.0.1
    - 192.168.0.1
    - 192.168.0.1
    - 192.168.0.1
    stdout_lines:
    - a
    - b
    - c
    - d
    - e
  - item:
    - 192.168.0.2
    - 192.168.0.2
    - 192.168.0.2
    stdout_lines:
    - aa
    - bb
    - cc

Upvotes: 2

Related Questions