首页 文章

ansible包括数组切片

提问于
浏览
0

在Ansible 2.2中,我想循环遍历从S3读取的大量文件 .

这是我的 role/tasks/main.yml

- name: Simulate variable read from S3
    set_fact:
      list_of_files_to_import: [
        "a.tar.gz",
        "b.tar.gz",
        "c.tar.gz",
        "d.tar.gz",
        "e.tar.gz",
        "f.tar.gz",
        "g.tar.gz",
        "h.tar.gz",
        ...
        "zz.tar.gz"
      ]

  - name: Process each file from S3
    include: submodule.yml
    with_items: list_of_files_to_import

这是 role/tasks/submodule.yml

---
  - name: Restore TABLE {{ item }}
    debug: var={{ item }}

这会崩溃,因为文件太多了 .

我发现我可以切片并一次发送部分:

- name: Process each file from S3
    include: submodule.yml
    with_items: "{{ list_of_files_to_import[0:5] }}"

  - name: Process each file from S3
    include: submodule.yml
    with_items: "{{ list_of_files_to_import[5:10] }}"

  - name: Process each file from S3
    include: submodule.yml
    with_items: "{{ list_of_files_to_import[10:15] }}"

  - name: Process each file from S3
    include: submodule.yml
    with_items: "{{ list_of_files_to_import[15:20] }}"

我想尝试类似的东西,而不是硬编码所有这些小块

- name: Process each file from S3
    include: submodule.yml
    with_items: "{{ list_of_files_to_import[{{start}}:{{end}}] }}"

但我们cannot get variable-defined variable names

如何在Ansible 2.2中处理大量项目?

1 回答

  • 0

    我最终用shell脚本解决它,用一些 --extra-vars 重复调用playbook来指定要处理的文件 .

    这只能起作用,因为S3中的文件列表具有类似的文件名 . 基本上它循环遍历文件名并一次处理每个文件名 .

    #!/usr/bin/env bash
    
    # return 0(true) if the year/month combination is valid
    valid() {
       yr=$1
       mn=$2
       # do not run on months after this month
       if [ "$yr" -eq "2017" -a "$mn" -gt "$(date +%m)" ]
       then
         return 1
       fi
    
       return 0
    }
    
    # For every year from 2002 to this year
    for year in `seq 2002 $(date +%Y)`
    do
       # for every zero-padded month, 01-12
       for month in `seq -f "%02g" 01 12`
       do
          # for each type of item in inventory
          for object in widgets doodads
          do
              if valid $year $month;
              then
                 ansible-playbook playbook_name.yml --extra-vars "object=$object year=$year month=$month"
              else
                 echo skipping invalid combo $object $year $month
              fi
          done
       done
    done
    

相关问题