我需要发送一个URL查询并返回JSON结果,然后读取IP、用户名、密码并将其用作主机。
问题的第一步是,当我发送一个URL查询时,有多个页面,我会将所有这些页面上的服务器信息保存为主机,然后将这些页面上的信息保存为主机,访问这些服务器并更新它们。
URL - http://apilink/virtual-machines
页面结果JSON
"meta": {
"pagination": {
"count": 16,
"current_page": 1,
"links": {
"next": "http://apilink/virtual-machines?page=2"
},
"per_page": 16,
"total": 169,
"total_pages": 11
}
}我将继续使用next URL进行查询,并且必须将结果作为主机在所有返回的页面上写入。
"json": {
"data": [
{
"actual_mhz": 0,
"connectionParameters": {
"data": [
{
"description": "Secure Shell",
"ip_addr": "192.168.1.1",
"port": 22,
"protocol": "SSH"
}
]
},
"hostname": "hostnameserver1",
"name": "server1",
"os": null,
"password": "xXxXxXxXX",
"status": "running",
"username": "root",
[
},从这样返回的结果中,我将使用IP、用户名、密码作为主机,使用下一个任务访问这些主机,并运行系统更新命令。
发布于 2020-12-14 21:53:44
在这种情况下,我将执行第一个API调用,只是为了获取meta.pagination.total_pages,然后基于这个值,我将使用一些loop和range,which is the replacement of the with_sequence。
然后,您需要知道的是,当您注册命令的结果时,您已经可以从变量访问前面项的结果了。
只有一点需要理解,这就是Ansible以一种非常奇特的方式创造结果的事实:
results键,然后从所有结果中填充。类似于:
- hosts: localhost
gather_facts: no
tasks:
- uri:
url: https://example.org/virtual-machines
register: number_of_pages
- uri:
url: >-
{{
api_call.json.meta.pagination.links.next
if api_call is defined else 'https://example.org/virtual-machines'
}}
loop: "{{ range(number_of_pages.json.meta.pagination.total_pages) }}"
register: api_call
- debug:
msg: "{{ api_call }}"https://stackoverflow.com/questions/65270618
复制相似问题