【问题标题】:How to check service exists and is not installed in the server using service_facts module in an Ansible playbook?如何使用 Ansible playbook 中的 service_facts 模块检查服务是否存在和未安装在服务器中?
【发布时间】:2021-10-30 02:07:08
【问题描述】:

我使用service_facts 来检查服务是否正在运行和启用。在某些未安装特定软件包的服务器中。
现在,使用service_facts module,我怎么知道这个特定的包没有安装在那个特定的服务器上?

在 Ansible 剧本中显示以下错误:

localhost | SUCCESS => {
    "ansible_facts": {
        "services": {
            "acpid.service": {
                "name": "acpid.service", 
                "source": "systemd", 
                "state": "running", 
                "status": "enabled"
            }, 
            "agent_installation.service": {
                "name": "agent_installation.service", 
                "source": "systemd", 
                "state": "stopped", 
                "status": "unknown"
            }, "changed": false, 
    "msg": "WARNING: Could not find status for all services. Sometimes this is due to insufficient privileges."
}

【问题讨论】:

  • 我在您的示例输出中看不到任何错误。你到底期待什么?
  • 这是我从该特定服务器收到的消息:"msg": "WARNING: Could not find status for all services. Sometimes this is due to insufficient privileges."
  • 是的,这是一个警告,而不是错误。那么你到底期望什么?你想检查什么?如果您需要仅对 root 可用的服务状态,则需要提升权限。
  • 我需要使用 ansible_facts 获取 falcon 和 nessus 的服务状态。这条消息来了,其中 falcon 和 nessus 没有安装在该服务器上。如何在剧本中处理这个问题。
  • 这意味着您拼错了服务名称(您可能应该使用falcon-sensor 而不是falcon-sensor.service)或者该服务不是由 systemd 管理的,并且可能由还有什么?

标签: python ansible


【解决方案1】:

只有在service_facts 存在且正确注册的情况下,才能使用特定服务。如果您想在不知道是否存在的服务上执行任务,Conditionals 可能适合您。例如

- name: Gathering Service Facts
  service_facts:
  tags: remove,stop,disable

- name: Make sure {{ SERVICE }} is stopped and disabled
  systemd:
    name: {{ SERVICE }}
    state: stopped
    enabled: no
  when: ("{{ SERVICE }}" in services)
  tags: remove,stop,disable

- name: Make sure {{ SERVICE }} is removed
  yum:
    name: {{ SERVICE }}
    state: absent
  tags: remove

你可以这样做

- name: Set facts
  set_fact:
    SERVICE: "postgresql-10.service" for my working test environment
  tags: facts

- name: Gathering service facts
  service_facts:
  tags: facts

- name: Get facts
  debug:
    msg:
      - "{{ ansible_facts.services[SERVICE].status }}"
  tags: facts

【讨论】:

    猜你喜欢
    • 2022-12-19
    • 2015-07-31
    • 1970-01-01
    • 2021-10-19
    • 2011-06-01
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多