ansible - 使用循环重用 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 }}"
解决方案
您可以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 }}"
推荐阅读
- python - 当行可以属于多个组时,对 pandas Series 或 DataFrame 的行进行分组
- java - 使用 JBoss 部署 REST 服务时的问题
- c# - 公开强类型列表?
- laravel - 如何使用 socket.io 从客户端发送数据到 laravel
- jquery - 如何通过单击使用 jquery 的复选框从列表中过滤这些项目包含特定文本的项目?
- typescript - vscode 找不到 typeRoots 类型定义
- swift - 标签栏项目改变颜色
- r - 无法在 R 中安装闪亮的包
- c# - Web API (.Net Core 2) 和数据库(通过代码优先实体框架创建)到 Google Cloud
- coq - 在 Coq 中用圆对称求解证明