Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible - append a string var itself in a loop

Tags:

ansible

I have a problem with append a string var itself in a loop.

like

var: 
  a: ""

var:
  package:
     - {{ iterations: 0 , newvar : b }}
     - {{ iterations: 1 , newvar : c }}
     - {{ iterations: 2 , newvar : d }}
     - {{ iterations: 3 , newvar : e }}
- set_fact:
    a: a + {{newvar}} 
  loop: {{ package }}

And I expected the answer should be a = bcde

But I also have the code if-else inside the set_fact. ( it make the code more complicated ) The code as below:


 var:
   portq: ""

 var:
   package: 
     - {{ iterations: 0 }}
     - {{ iterations: 1 }}
     - {{ iterations: 2 }}
     - {{ iterations: 3 }}


- set_fact:

      portq: "{% if q_port_result.results[item.iterations].cde != 'unknown' %}{{ portq + q_port_result.results[item.iterations].cde}}{% else %}{% endif %}"

      loop: "{{ package }}"

My problem is how to add append the "portq" with the new variable.

It always prompts the error "The error was: 'portq' is undefined\n\n"

Many thanks!

like image 968
Jacky Avatar asked Oct 18 '25 01:10

Jacky


1 Answers

- name: test
  hosts: localhost
  become: false
  vars:
    package:
      - iterations: 0
        newvar: b
      - iterations: 1
        newvar: c
      - iterations: 2
        newvar: d
      - iterations: 3
        newvar: e
  tasks:
    - set_fact:
        a: "{{ a | default('') + item.newvar }}"
      loop: "{{ package }}"
    - debug: var=a
like image 200
Jiri B Avatar answered Oct 21 '25 21:10

Jiri B