使用Ansible处理分页

使用Ansible处理分页,ansible,Ansible,我有一个来自分页服务器的JSON响应 { "services": [ { "id": "ABC12", "name": "Networks", "description": null, "status": "active", "teams": [ { "id": "XYZ12",

我有一个来自分页服务器的JSON响应

{
    "services": [
        {
            "id": "ABC12",
            "name": "Networks",
            "description": null,
            "status": "active",
            "teams": [
                {
                    "id": "XYZ12",
                    "type": "team_reference",
                    "summary": "Network Systems ",
                }
            ],
            "acknowledgement_timeout": null,
            "auto_resolve_timeout": null,
            "alert_grouping": "intelligent",
            "alert_grouping_timeout": null,
            "integrations": [],
            "response_play": null,
            "type": "service",
            "summary": "All Events",
        }
     ],
     "limit": 25,
     "offset": 0,
     "total": null,
     "more": true
}
限制-我可以设置的最大值为100。

offset-如果指定,则显示该点的结果。

更多-如果为真,则会有更多结果。如果为FALSE,则结束。

有关此分页的详细信息-

我需要匹配
名称
“Networks”,并获取其相应的
id
“ABC12”。问题是我必须对API进行多次分页调用

到目前为止,我已经写了这篇文章

- name: PagerDuty API call - GET Service ID
  uri:
    url: "https://api.pagerduty.com/services?/?limit={{ x }}&offset={{ x+1 }}"
    method: GET
    status_code: 200
    headers:
      Content-Type: "application/json"
      Accept: "application/vnd.pagerduty+json;version=2"
      Authorization: "Token token={{ api_token }}"
 register: json_resp
  • 如何将
    x
    的值设置为
    25
    ,进行API调用并将结果附加到
    json_resp
    直到
    more
    为false

  • 在找到匹配项之前,如何进行多个API调用。如果我找到匹配的,那就别打电话了 还是有更好更干净的方法

    非常感谢您的任何帮助,这对ansible来说是非常新的

    还是有更好更干净的方法

    处理这种情况最干净的方法是编写一个Ansible模块,用于与PagerDutyAPI交互。您的模块将处理分页,然后将完整的结果集返回到您的剧本中

    有一些关于开发Ansible模块的信息


    Ansible已经包含了几个与pagerduty交互的模块;也许模块可以作为一个模型。

    您可以尝试先对url进行卷曲以获取标题。并为您的限制/偏移量设置_fact,并在uri模块中使用。 我是这样做的,但你应该能够根据自己的需要修改它。”“total_pages”的返回像这样的“X-total-pages:2”,因此除了进行拆分之外,可能还有一种更优雅的方式来获取总页数,但这对我来说很有效

    ---
    - name: Get number of pages
      command: |
        curl -I -s {{ api_url }} -H {{ private_token }}
      register: pagination
      failed_when: pagination.rc > 0 or '200 OK' not in pagination.stdout
    
    - set_fact:
        total_pages: "{{ pagination.stdout | regex_search('X-Total-Pages: \\d') }}"
    
    - name: Gather all projects in group
      uri:
        url: "{{ api_url }}"
        headers:
          PRIVATE-TOKEN: "{{ private_token }}"
        body_format: form-urlencoded
        body:
          top_level_only: false
          page: "{{ item }}"
      register: group_projects
      with_sequence: start=1 end={{ total_pages.split()[1] }}
    

    嗨,拉尔克斯。感谢您的回复,我正在实施一个非常小的解决方案。不幸的是,不允许编写模块。在ansible play中有没有办法做到这一点?写模块…是不允许的?这是家庭作业吗?编写模块将是解决这一特定问题的最干净、最有效的方法。当然,您也可以编写Python或shell脚本,并在模块中运行该脚本。