我正在尝试将现有的ansible剧本(用于以并行方式提取多个网页URL的网页内容)转换为可重用角色。我需要角色来循环接受变量,并在我当前的剧本能够完成的单个任务中生成所有项目的输出。但是当前角色只能产生循环中最后一项的输出
我尝试在角色内部和外部注册网页内容,但没有用。另外,将循环响应结果with_items的作用与产生非200值的结果相同
仅供参考,我通过在角色中包含循环而获得了预期的输出,但它无法实现为GET调用保留角色的目的,因为我不需要每次都进行GET调用的循环。因此,我希望在testplaybook.yml中扮演这个角色。
测试角色:main.yml
uri:
url: "{{ URL_Variable }}"
method: GET
status_code: 200
return_content: yes
register: response
ignore_errors: true
testplaybook.yml:
- hosts: localhost
gather_facts: true
tasks:
- name: Include roles
include_role:
name: Test-Role
vars:
URL_Variable: "http://{{ item }}:{{ hostvars[groups['group1'][0]]['port'] }}/{{ hostvars[groups['group1'][0]]['app'] }}/"
with_items: "{{ groups['group1'] }}"
- name: "Display content"
debug:
var: response.results
预期输出:
response.results:
ok: [127.0.0.1] => (item=[0, 'item1']) => {
"ansible_loop_var": "item",
"item": [
0,
"item1"
],
"response": {
"accept_ranges": "bytes",
"changed": false,
"connection": "close",
"content": "content1",
"content_length": "719",
"content_type": "text/html",
"cookies": {},
"failed": false,
"msg": "OK (719 bytes)",
"redirected": false,
"server": "42",
"status": 200,
"url": "http://item1:port/app/"
}
}
ok: [127.0.0.1] => (item=[1, 'item2']) => {
"ansible_loop_var": "item",
"item": [
1,
"item2"
],
"response": {
"accept_ranges": "bytes",
"changed": false,
"connection": "close",
"content": "content2",
"content_length": "719",
"content_type": "text/html",
"cookies": {},
"failed": false,
"msg": "OK (719 bytes)",
"redirected": false,
"server": "42",
"status": 200,
"url": "http://item2:port/app/"
}
}
答案 0 :(得分:0)
尝试此Test-Role: main.yml
文件:
- uri:
url: "{{ URL_Variable }}"
method: GET
status_code: 200
return_content: yes
register: response
ignore_errors: true
- name: Add response to responses array
set_fact:
responses_results: "{{ responses_results | default([]) + [{'URL': URL_Variable, 'response': response.content}] }}"
这可以与include_tasks
一起使用,我假设它也可以与include_role
一起使用,假设变量responses_results
在相同的角色中应该在所有角色中都保持不变。如果不起作用,请尝试使用include_tasks
将代码切换为单个角色。
希望有帮助