Trying to create a dictionary, and am seeing extra blank {} within the returned dataset. Tried to rework the issue a few ways see below .

 - name: thing
  set_fact:
    makeDict: "
       {% set BuildArr = [] -%}
        {%- for number in range(1, 5) -%}
          { {% set ignored = BuildArr.extend([{
                        'Number1': number|string,
                        'Number2': number|string,
                        'Number3': number
                        }]) -%}}
        {%- endfor %}
        {{ BuildArr }}"
- name: try_again
  debug:
    var: UserGroupArray

Output:

TASK [try_again] ***********************************************************************************************************************ok: [localhost] => {
"UserGroupArray": " { }{ }{ }{ } [{'Number2': u'1', 'Number3': 1, 'Number1': u'1'}, {'Number2': u'2', 'Number3': 2, 'Number1': u'2'}, {'Number2': u'3', 'Number3': 3, 'Number1': u'3'}, {'Number2': u'4', 'Number3': 4, 'Number1': u'4'}]"

}

2 Answers

1
larsks On

and am seeing extra blank {} within the returned dataset

Because you've put one there. The first { and the final } in this block are not Jinja template markers, they are a literal { and }:

      { {% set ignored = BuildArr.extend([{
                    'Number1': number|string,
                    'Number2': number|string,
                    'Number3': number
                    }]) -%}}

I think you want:

      {% set ignored = BuildArr.extend([{
                    'Number1': number|string,
                    'Number2': number|string,
                    'Number3': number
                    }]) -%}
1
Vladimir Botka On

combine might be used instead of extend. For example the play below

- name: Create my_dict
  set_fact:
    my_dict: "{{ my_dict|default({})|combine({('No' + item): item}) }}"
  with_sequence: start=1 end=4
- debug:
    var: my_dict

gives:

"my_dict": {
    "No1": "1", 
    "No2": "2", 
    "No3": "3", 
    "No4": "4"
}