Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split string to array and loop over it?

I have a string variable like this RCD_APIS=backend,api-alerting,api-tracking,api-versioning that contains the name of my docker images. I need to split it into an array and loop over it so I can pull each docker image

I have tried the with_sequence loop but i get just the index (1,2,3,..)

- name: pull images from registry
  docker_image:
    name: "hostname:5000/{{ RCD_APIS.split(',') }}"
    pull: true
    state: present
    tag: "{{RCD_VERSION_CURRENT}}"
  with_sequence: count={{ RCD_APIS|count }}

I also tried with_item loop but it doesn't work so i tried to debug :

 vars:
    - container: "{{ RCD_APIS }}"
 tasks:
    - name: pull images from registry debug
      debug: var={{item|basename}}
      with_items: container.split(',')

i get something like:

(item=container.split(',')) => {
         "container.split(',')": [
         "backend", 
         "api-alerting", 
         "api-tracking", 
         "api-versioning", 
         "connecteur-gdfa", 
         "api-batch", 
         "ihm"
     ], 
     "item": "container.split(',')"
}

so how can i loop over that array (like a foreach) and do the docker pull backend, docker pull api-alerting... ?

like image 901
zeO_340 Avatar asked Jun 11 '26 22:06

zeO_340


2 Answers

Here you go:

- name: pull images from registry
  docker_image:
    name: hostname:5000/{{ item }}
    pull: true
    state: present
    tag: "{{RCD_VERSION_CURRENT}}"
  with_items: "{{ RCD_APIS.split(',') }}"
like image 194
Konstantin Suvorov Avatar answered Jun 13 '26 15:06

Konstantin Suvorov


To print a list in the debug module, where x.content is a string with newlines, and you want to split on newlines, use:

  debug:
    msg: "{{ x.content.split('\n') }}"

or

  debug:
    var: "x.content.split('\n')"
like image 34
activedecay Avatar answered Jun 13 '26 14:06

activedecay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!