首页 > 解决方案 > 如果端口打开,Ansible Playbook 应该停止执行

问题描述

我正在 VM 上安装 karaf,在我的安装过程中,我想验证 karaf 实例是否已经在运行,如果端口打开,它会停止安装过程并退出 ansible 执行。目前它正在做其他方式

- name: Wait for my-service to start
      wait_for: port={{karaf_port}} timeout=30
       msg: "Port 8101 is not accessible."

标签: ansibleansible-2.x

解决方案


您可以使用此任务来检查应用程序是否已在运行。如果运行,它将中止剧本。

  - name: Check if service is running by querying the application port
    wait_for: 
      port: 22
      timeout: 10
      state: stopped
      msg: "Port 22 is accessible, application is already installed and running"
    register: service_status

基本上,您正在使用带有 的模块state: stopped,并且 ansible 期望端口以某种方式停止侦听timeout几秒钟。如果端口保持 10 秒(由于没有人停止已安装的应用程序,它将保持保持状态),ansible 将退出并出错。

将端口更改为 23,您将看到 playbook 将继续下一步:

  tasks:
  - name: Check if service is running by querying the application port
    wait_for: 
      port: 23
      timeout: 10
      state: stopped
      msg: "Port 23 is accessible, application is already installed and running"
    register: service_status

  - name: print
    debug:
      var: service_status

您不需要该register子句,只是为我的测试添加的。

希望能帮助到你


推荐阅读