简体   繁体   中英

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 ... ?

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(',') }}"

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')"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM