首页 > 解决方案 > uri 模块中的多个 URL

问题描述

考虑这个ansible代码

- name: Retrieve the wf execution information
  hosts: all
  tasks:
    - name: Get execution info
      uri: 
        url: https://myurl
        user: my_user
        password: my_pass
        method: GET
        return_content: yes
      register: wf_runs
      notify:
        - pager-duty
      changed_when: True

    - name: Print all the runs of the wf
      debug: 
        var: wf_runs.json.relations.link | last

    - name: Assign the variable
      set_fact:
        last_run: "{{ wf_runs.json.relations.link | last }}"

  handlers:
    - name: pager-duty
      pagerduty_alert:
        api_key: my-key
        integration_key: xxxxx
        service_id: sss
        state: triggered
        desc: 
          - "Job started at: {{ last_run | json_query('attributes[1].value')\n }}"
          - "Job ended at: {{ last_run | json_query('attributes[2].value')\n }}"
          - "Job status: {{ last_run | json_query('attribuets[5].value')\n }}"

我想针对 4 个不同的 url 和 4 个不同的环境运行相同的代码,就像这样

https://myurl-env1-wf2
https://myurl-env1-wf3

我怎样才能做到这一点?我曾尝试遍历 url,但它wf_runs.json.relations.lil | last作为未定义的变量失败。提前致谢

标签: ansibleuri

解决方案


问:“我想针对 4 个不同的 url 运行相同的代码”

A: 将任务放入一个文件并添加meta: flush_handlers。例如

$ cat get-info-handle-allert.yml
- name: Get execution info
  uri: 
    url: "{{ item }}"
  ...
- name: Print all the runs of the wf
  ...
- name: Assign the variable
  ...
- meta: flush_handlers

循环include_tasks。例如

  tasks:
    - name: Loop get-info-handle-allert
      include_tasks: get-info-handle-allert.yml
      loop:
        - https://myurl
        - https://myurl-env1-wf2
        - https://myurl-env1-wf3

(未经测试。如果 flush_handlers 有问题,只需将任务替换为处理程序中的任务。)


推荐阅读