首页 > 解决方案 > 使用循环重用 Ansible 编写的任务

问题描述

我正在编写 Ansible 剧本。我生成了一个随机字符串(例如 4M[0-9].html)并将其添加到列表中。我不确定如何使用循环生成一堆字符串(例如其中的 50 个)并添加到同一个列表url_list中。下面是我已经拥有的代码。任何帮助将不胜感激。

- name: xxx
  hosts: localhost
  connection: local

  tasks:
    - name: create an variables
      set_fact:
        url_list: []

    - name: generate random string
      vars:
        random_str: ''
      set_fact:
        random_str: "{{ random_str }}{{ item }}"
      with_items:
        - '4M'
        - "{{9 | random}}"
        - '.html'

    - name: add str to the list
      set_fact:
        url_list: "{{ url_list + [item] }}"
      with_items:
        - "{{ random_str }}"

    - name: print the random string from the list
      debug:
        msg: "{{ item }}"
      with_items: "{{ url_list }}"

标签: ansible

解决方案


您可以range在循环中使用(替换旧with_sequence循环)来控制迭代循环的次数。

您还需要创建随机字符串的初始步骤。可以在构建url_list变量时完成。

尝试这个:

- name: xxx
  hosts: localhost
  connection: local

  tasks:
    - name: create an variables
      set_fact:
        url_list: []

    - name: add str to the list
      set_fact:
        url_list: "{{ url_list + ['4M' + (9 | random | string) + '.html'] }}"
      loop: "{{ range(0, 50) | list }}"

    - name: print the random string from the list
      debug:
        msg: "{{ item }}"
      loop: "{{ url_list }}"

推荐阅读