dictionary - 使用 Ansible set_fact 从寄存器结果 systemctl 创建字典
问题描述
在 Ansible 中,我使用 register 将任务的结果保存在变量 services 中。它有这样的结构:
"stdout_lines": [
"arp-ethers.service \u001b[1;31mdisabled\u001b[0m",
"auditd.service \u001b[1;32menabled \u001b[0m",
"autovt@.service \u001b[1;31mdisabled\u001b[0m",
"blk-availability.service \u001b[1;31mdisabled\u001b[0m"]
我想收到这个:
{
"arp-ethers.service": "disabled",
"auditd.service": "enabled",
"autovt@.service": "disabled",
"blk-availability.service":"disabled"
}
我想使用后续的 set_fact 任务来生成一个带有字典的新变量,但是到目前为止我没有运气。
- name: Collect all services for SYSTEMD
raw: systemctl list-unit-files --type=service --no-pager -l --no-legend`
register: services
changed_when: false
- debug:
var: services
- debug:
msg: "{{ item.split()[0]|to_json }} : {{ item.split()[1]|to_json }}"
with_items:
- "{{ services.stdout_lines }}"
- name: Populate fact list_services for SYSTEMD
set_fact:
cacheable: yes
list_services: "{{ list_services|default({}) | combine ( {item.split()[0]|to_json: item.split()[1]|to_json} ) }}"
with_items: "{{ services.stdout_lines }}"
这个回报:
FAILED! => {"msg": "|combine expects dictionaries, got u'arp-ethers.service \\x1b[1;31mdisabled\\x1b[0m\\r\\nauditd.service \\x1b[1;32menabled \\x1b[0m\\r\\nautovt@.service \\x1b[1;31mdisabled\\x1b[0m\\r\\nblk-availability.service \\x1b[1;31mdisabled\\x1b[0m\\r\\n'"}
解决方案
你想要的是使用切换list-unit-files
到json 输出--output=json
(是的,这是 journalctl 手册页的链接,因为那个systemctl
链接在那里)
大致是这样的,虽然我没有测试过:
- name: Collect all services for SYSTEMD
raw: systemctl --output=json list-unit-files --type=service
register: services_json
changed_when: false
- set_fact:
services: '{{ services_json.stdout | from_json }}'
推荐阅读
- matplotlib - 如何在多个图中隐藏轴
- android - 如何为所有新项目配置项目级别的 build.gradle?
- apigee - Apigee:无法通过 Management Server 进行身份验证
- python - 使用 opencensus-python 时从 Application Insights 中删除 customDimensions 项
- javascript - 根据数组长度更改字符串
- java - 如何将请求正文中的数据作为 json 发送到 resttemplate.exchange
- matlab - 函数 pdist 和 knnsearch
- python - 列出新列表项时,“字段列表”中的未知列“site_id”
- sockets - 确定哪个 IP 地址收到了数据包
- azure-ad-b2c - 通过自我声明的电子邮件查找用户,如果用户存在,则重定向到用户的社交登录提供商