使用循环重用Ansible编写的任务

时间:2019-11-20 00:21:22

标签: 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 }}"

1 个答案:

答案 0 :(得分:1)

您可以在循环中使用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 }}"