首页 > 解决方案 > 使用 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'"}

标签: dictionaryansible

解决方案


你想要的是使用切换list-unit-filesjson 输出--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 }}'

推荐阅读