0

I am trying to define a dictionary FACTS_VAR in which the key must contain the word SUB. Argument_value and the value is true but when I loop over the variable Argument

hosts: all
gather_facts: true

vars:

  Argument:
    - value1
    - value2                      

tasks:

- name: DEFINING A variable
  set_fact:
    FACTS_VAR: {'SUB..item': true}
  loop: "{{Argument}}"

- debug:
    var: FACTS_VAR

I got this result so I don't know what is missing there. I am expecting to get a dictionary like this

FACTS_ENTRY:
   SUB.value1: true
   SUB.value2: true

TASK [debug] *****************************************************************************************************************
ok: [control] => {
    "FACTS_ENTRY": {
        "SUB..item": true
    }
}
ok: [ansible4] => {
    "FACTS_ENTRY": {
        "SUB..item": true
    }
medisamm
  • 197
  • 1
  • 7

2 Answers2

2

Create the keys

facts_entry_keys: "{{ ['sub']|product(argument)|map('join','.')|list }}"

gives

facts_entry_keys:
  - sub.value1
  - sub.value2

Create the dictionary

facts_entry: "{{ dict(facts_entry_keys|product([true])) }}"

gives

facts_entry:
  sub.value1: true
  sub.value2: true

Example of a complete playbook

- hosts: localhost
  vars:
    argument:
      - value1
      - value2
    facts_entry_keys: "{{ ['sub']|product(argument)|map('join','.')|list }}"
    facts_entry: "{{ dict(facts_entry_keys|product([true])) }}"
  tasks:
    - debug:
        var: facts_entry
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • this is what i am looking for. It works like a magic, thank you so much for your efficient solution – medisamm Aug 01 '22 at 20:16
1

From your current description I understand only that you probably like to define variables somehow dynamically.

The following example could give some guidance.

---
- hosts: test
  become: false
  gather_facts: false

  vars:

    ARG:
      - val1
      - val2

  tasks:

  - name: Dynamically define variable
    set_fact:
      FACTS_VAR: "{ 'SUB_{{ item }}': true }"
    loop: "{{ ARG }}"

  - debug:
      var: FACTS_VAR

resulting into an output of

TASK [Dynamically define variable] **
ok: [test.example.com] => (item=val1)
ok: [test.example.com] => (item=val2)

TASK [debug] ************************
ok: [test.example.com] =>
  FACTS_VAR:
    SUB_val2: true

Please take note that according your current description there can be only one value as result.

Further Q&A

U880D
  • 8,601
  • 6
  • 24
  • 40
  • thank you so much for the reply, exactly this is my problem that the `var` `FACTS_VAR` must take all the values given in input because i need after that to transform that `dictionary` into `JSON format` in the next task like this one [create_jason_file](https://stackoverflow.com/questions/63416703/how-to-write-a-json-file-using-ansible) – medisamm Jul 31 '22 at 15:34