1

我正在尝试将现有的 ansible playbook(用于以并行方式提取多个网页 URL 的网页内容)转换为可重用的角色。我需要角色在循环中接受变量,并为我当前的剧本能够执行的单个任务中的所有项目生成输出。但是当前角色只能产生循环中最后一项的输出

我尝试在角色内外注册网页内容,但没有用。并且使用与角色相同的_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

预期输出:

响应结果:

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/"
    }
}
4

1 回答 1

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.

希望能帮助到你

于 2019-06-06T22:46:45.853 回答