Ansible list to dict and incremente value for each element

Viewed 133

I have a list list_info = ["config1", "config2"] and I would like to transform to a dict which incremente value by one for each item and starting for a number like 100. To have a dict like that :

list_info is a variable define before with set_fact

- name: Print
  vars:
    start: 100
  set_fact:
    dict_info: "{{ dict(list_info|zip(_serial)) }}"
  vars:
    _len: "{{ list_info|length }}"
    _serial: "{{ range(start, start + _len|int) }}"

The task includes an option with an undefined variable. The error was: 'start' is undefined\n\nThe error appears to be in

1 Answers

you have two vars section on the same task, this is the error.

---
- hosts: localhost
  gather_facts: false

  vars:
    list_info:
      - config1
      - config2
      - config3
      - config11
      - config21
      - config31

  tasks:
    - name: Print
      set_fact:
        dict_info: "{{ dict(list_info| zip(_serial)) }}"
      vars:
        start: 100
        _len: "{{ list_info|length }}"
        _serial: "{{ range(start, start + _len|int) | list }}"

    - name: DEBUG
      debug:
        msg: "{{ dict_info }}"

and the output:

TASK [Print] *************************************************************************
ok: [localhost]

TASK [DEBUG] *************************************************************************
ok: [localhost] => {
    "msg": {
        "config1": 100,
        "config11": 103,
        "config2": 101,
        "config21": 104,
        "config3": 102,
        "config31": 105
    }
}

PLAY RECAP ***************************************************************************
Related