【问题标题】:Using Ansible set_fact to create a dictionary from register results systemctl使用 Ansible set_fact 从寄存器结果 systemctl 创建字典
【发布时间】:2020-03-05 15:36:38
【问题描述】:

在 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'"}

【问题讨论】:

    标签: dictionary ansible


    【解决方案1】:

    您想要的是将list-unit-files 切换为json output using --output=json(是的,这是 journalctl 手册页的链接,因为the systemctl one links there

    大致是这样的,虽然我没有测试过:

    - 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 }}'
    

    【讨论】:

    • 对不起,但是在这台机器上返回,{“msg”:“字段 'args' 的值无效 ({u'list_services': u'{{ services3.stdout | from_json }}', u'cacheable': True}),并且无法转换为字典。错误是:执行时无法解码 JSON 对象\n\n:systemctl --output=json list-unit-files --type= service --no-pager -l --no-legend 不返回 json。link
    【解决方案2】:

    使用service_facts。例如

        - service_facts:
        - set_fact:
            dict_services: "{{ dict(ansible_facts.services|
                                    dict2items|
                                    json_query('[].[key, value.status]')) }}"
    

    【讨论】:

      猜你喜欢
      • 2016-06-06
      • 1970-01-01
      • 2021-01-31
      • 2022-10-14
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多