首页 > 解决方案 > 如何使用listen_ports_facts模块,ansible

问题描述

使用ansible我想检查tomcat在哪个端口运行,当然我认为有不同的方法可以做到,但是我找到了这个ansible模块

https://docs.ansible.com/ansible/latest/modules/listen_ports_facts_module.html

我想用它,但是根据例子,我不知道如何使用它。

我的意思是如果我设置

gather_facts: true

并运行任务

  - name: List TCP ports
    debug:
      msg: "{{ ansible_facts.tcp_listen }}"

我得到了错误

TASK [discover-servers : List TCP ports] *******************************************************************************************************************************
task path: /home/A78252689/sap_bo/roles/discover-servers/tasks/tomcat_servers.yml:4
fatal: [2a00:da9:2:21ca:111:0:426:2]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'tcp_listen'\n\nThe error appears to be in '/home/A78252689/sap_bo/roles/discover-servers/tasks/tomcat_servers.yml': line 4, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: List TCP ports\n    ^ here\n"}

如果我在示例中完全按照它的方式设置任务,我在第一个任务中出现错误收集关于侦听端口的事实

TASK [discover-servers : include_tasks] ********************************************************************************************************************************
task path: /home/A78252689/sap_bo/roles/discover-servers/tasks/main.yml:4
fatal: [2a00:da9:2:21ca:111:0:426:2]: FAILED! => {"reason": "no action detected in task. This often indicates a misspelled module name, or incorrect module path.\n\nThe error appears to be in '/home/A78252689/sap_bo/roles/discover-servers/tasks/tomcat_servers.yml': line 4, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: Gather facts on listening ports\n    ^ here\n"}

那么,您知道如何使用模块 listen_ports_facts 吗?提前感谢您的支持

标签: ansible

解决方案


您的gather_facts剧本运行阶段使用该setup模块。它不运行listen_ports_facts,因此如果您不明确运行该模块,您将无法获得这些事实。

从文档中,listen_ports_module创建了以下事实:

  • tcp_listen
  • udp_listen

使用 Ansible 2.9.2,以下工作正常:

---
- gather_facts: false
  hosts: localhost

  tasks:
    - listen_ports_facts:

    - debug:
        msg: "{{ tcp_listen }}"

    - debug:
        msg: "{{ udp_listen }}"

如果您尝试运行该listen_ports_facts模块并且收到错误“在任务中未检测到任何操作”,则可能是您正在运行没有该listen_ports_facts模块的旧版 Ansible。它首先出现在 2.9 版本中。


推荐阅读