-2

necesito agregar un string en una lista, con un valor dependiendo del valor de un atributo de la lista


I need to add a string in a list, with a value depending on the value of an attribute in the list

#ambprueba.yml

LIST_BASES: 
  - { BASE: 'ambprueba_sc',TWO_TASK: 'sc' }
  - { BASE: 'ambprueba_si',TWO_TASK: 'si' }        
  - { BASE: 'ambprueba_slucs',TWO_TASK: '001' }
  - { BASE: 'ambprueba_sluod',TWO_TASK: '105' }

--------------------------

#Ambiente=ambprueba (in this case)

  - name: "Include vars in {{ Ambiente }}.yml"
    include_vars:
      file: "{{ Ambiente }}.yml"
      name: INFO_AMBIENTE

  - name: "adding string value tipo to list"
    set_fact:
      LIST_BASES: "{{ ITEM.BASE + ITEM.TWO_TASK + [{'TIPO':{% if ITEM.TWO_TASK=='sc' or ITEM.TWO_TASK=='si' %}ITEM.TWO_TASK{% else% }slu }] }}" 
    with_items: "{{ INFO_AMBIENTE.LIST_BASES}}"

#expected result

LIST_BASES: 
  - { BASE: 'ambprueba_sc'    ,TWO_TASK: 'sc'  ,TIPO: 'sc' }
  - { BASE: 'ambprueba_si'    ,TWO_TASK: 'si'  ,TIPO: 'si'}        
  - { BASE: 'ambprueba_slucs' ,TWO_TASK: '001' ,TIPO: 'slu'}
  - { BASE: 'ambprueba_sluod' ,TWO_TASK: '105' ,TIPO: 'slu'}

#error:
fatal: [xxx.xxx.xxx.xxx]: FAILED! => {"msg": "template error while templating string: unexpected '%'. String: {{ ITEM.BASE + ITEM.TWO_TASK + [{'TIPO':{% if ITEM.TWO_TASK=='sc' or ITEM.TWO_TASK=='si' %}ITEM.TWO_TASK{% else% }slu }] }}"}

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
upszot
  • 1
  • 1

1 Answers1

0

Try this:

  - set_fact:
      LIST_BASES: []

  - name: "adding string value tipo to list"
    set_fact:
      LIST_BASES: "{{ LIST_BASES + [item | combine({'TIPO': item.TWO_TASK if item.TWO_TASK=='sc' or item.TWO_TASK=='si' else 'slu'})] }}"
    with_items: "{{ INFO_AMBIENTE.LIST_BASES }}"

The first set_fact task initialises the variable as a list. The second set_fact task appends a new list entry, which is the original dict combined with a new dict for the 'TIPO' key. The value for 'TIPO' is conditionally set based on your requirements.

Matt P
  • 2,452
  • 1
  • 12
  • 15