繁体   English   中英

如何将字符串拆分为数组并遍历它?

[英]how to split string to array and loop over it?

我有一个像RCD_APIS=backend,api-alerting,api-tracking,api-versioning这样的字符串变量,其中包含我的docker映像的名称。 我需要将其拆分为一个数组并循环遍历,以便可以提取每个docker映像

我已经尝试过with_sequence循环,但是我只得到索引(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 }}

我也尝试了with_item循环,但是它不起作用,所以我尝试调试:

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

我得到类似的东西:

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

所以我该如何遍历该数组(像foreach一样),然后docker pull backend, docker pull api-alerting ...?

干得好:

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

要在debug模块中打印列表,其中x.content是带换行符的字符串,并且您希望在换行符上拆分,请使用:

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

要么

  debug:
    var: "x.content.split('\n')"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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