使用ansible来收集和修改事实,并将修改后的json POST到http API



在使用Ansible修补基于yum的Linux主机之前,我想收集有关当前安装的包的事实,并将详细信息写入http API。

第一个任务是收集事实并将其存储在一个变量中:

tasks:
- name: Gather installed packages
yum:
list: installed
register: installed_packages

其输出如下所示:

[
{
"arch": "noarch", 
"envra": "0:yum-3.4.3-168.el7.centos.noarch", 
"epoch": "0", 
"name": "yum", 
"release": "168.el7.centos", 
"repo": "installed", 
"version": "3.4.3", 
"yumstate": "installed"
}, 
{
"arch": "x86_64", 
"envra": "0:zlib-1.2.7-19.el7_9.x86_64", 
"epoch": "0", 
"name": "zlib", 
"release": "19.el7_9", 
"repo": "installed", 
"version": "1.2.7", 
"yumstate": "installed"
}
]

我的API需要额外的字段;server_hostname,server_ip_addressreview_id我需要将它们添加到json数组的每个元素中。我试过使用combine,我能想到的最好的是:

- name: Create empty list
set_fact:
list_two: []
- name: Add additional details to installed_packages fact
set_fact:
list_two: "{{ list_two + [item | combine ({ 'server_hostname': 'server-name','server_ip_address': '1.2.3.4','review_id': 'guid' })] }}"
with_items: "{{ installed_packages.results }}"

这在我的一个开发服务器上非常慢,并且在另一个开发服务器上挂起(并且永远不会完成)。我如何将这些字段添加到installed_packages事实,使其看起来像下面,并使用uri模块执行POST。

[
{
"arch": "noarch", 
"envra": "0:yum-3.4.3-168.el7.centos.noarch", 
"epoch": "0", 
"name": "yum", 
"release": "168.el7.centos", 
"repo": "installed", 
"version": "3.4.3", 
"yumstate": "installed",
"server_hostname": "server-name",
"server_ip_address": "1.2.3.4",
"review_id": "guid"
}, 
{
"arch": "x86_64", 
"envra": "0:zlib-1.2.7-19.el7_9.x86_64", 
"epoch": "0", 
"name": "zlib", 
"release": "19.el7_9", 
"repo": "installed", 
"version": "1.2.7", 
"yumstate": "installed",
"server_hostname": "server-name",
"server_ip_address": "1.2.3.4",
"review_id": "guid"
}
]

很难确切地说明为什么当前使用循环的尝试确实失败了,但是这里有一种不使用循环的替代方法:

- debug:
msg: "{{ installed_packages.results | map('combine', _host_info) }}"
vars:
_host_info:
server_hostname: server-name
server_ip_address: 1.2.3.4
review_id: guid 

您可以直接在uri任务中进行定制,例如:

- ansible.builtin.uri:
url: https://httpbin.org/post
method: POST
body_format: json
body:
packages: "{{ installed_packages.results | map('combine', _host_info) }}"
vars:
_host_info:
server_hostname: server-name
server_ip_address: 1.2.3.4
review_id: guid

最新更新