2

这显示了我正在尝试做的事情

---
- hosts: localhost
  gather_facts: false
  vars:
    str: "abcdefg"
    str_parts: []
  tasks:
    - name: Break string into list of max 3 character parts
      set_fact:
        str_parts: "{{ str_parts + [ str[:3] ] }}"
        str: "{{ str[3:] }}"
      until: str == ""

使用 -vvv 运行它显示循环代码只执行一次。str_parts 获得单个成员“abc”,str 更改为“defg”,日志显示“FAILED - RETRYING: Break string into list of max 3 character parts”消息,直到超时

为什么不循环,呃,循环?

我可以通过使用命令或 shell 模块在断点处插入逗号然后使用 {{ str | 来解决它。split(",") }} 但纯 Ansible 解决方案会更好

编辑:错误set_fact 主题的行为在循环时不会更新事实(重大更改)

4

1 回答 1

2

例如

    - set_fact:
        str_parts: "{{ str|batch(3)|map('join') }}"

  str_parts:
  - abc
  - def
  - g

可以只选择匹配的项目,例如

    - set_fact:
        str_parts: "{{ str|batch(3)|map('join')|select('match', '^.{3}$') }}"

  str_parts:
  - abc
  - def
于 2021-06-03T13:19:46.370 回答