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

时间:2017-06-22 14:22:57

标签: arrays loops docker ansible

我有一个像RCD_APIS=backend,api-alerting,api-tracking,api-versioning这样的字符串变量,其中包含我的泊坞窗图像的名称。我需要将它拆分成一个数组并循环遍历它,这样我就可以拉出每个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 ...?

2 个答案:

答案 0 :(得分:1)

你走了:

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

答案 1 :(得分:0)

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

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

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