如何配置Ansible Playbook:端口开放时终止Karaf安装执行
It sounds like your current Ansible task is waiting for the Karaf port to become accessible—exactly the opposite of what you need. You want to stop the installation immediately if the target port {{ karaf_port }} is already open (meaning a Karaf instance is already running). Here's how to adjust your Playbook logic:
Existing (Incorrect) Logic
First, let's recap your current task (which waits for the port to open, failing only if it doesn't become accessible after 30 seconds):
- name: Wait for my-service to start wait_for: port={{karaf_port}} timeout=30 msg: "Port 8101 is not accessible."
Corrected Logic
We'll use the state: stopped parameter in the wait_for module to check if the port is not in use. If the port is open, this task will fail and terminate the Ansible run with your custom message:
- name: Verify Karaf port is not already in use wait_for: port: "{{ karaf_port }}" state: stopped timeout: 1 msg: "Karaf instance is already running on port {{ karaf_port }}. Installation aborted."
Breakdown of the Corrected Task:
state: stopped: Tellswait_forto check if the port is closed (not accepting connections). If the port is open, this condition fails immediately.timeout: 1: We don't need to wait—we just want an immediate check of the port's current state.msg: Custom error message that will be displayed when the port is found open, clearly explaining why the installation is being terminated.
Alternative: Explicit Fail Step (For More Control)
If you want to separate the port check from the failure trigger (for better readability or additional pre-failure logic), you can split it into two tasks:
- name: Check if Karaf port is open wait_for: port: "{{ karaf_port }}" state: stopped timeout: 1 register: port_check_result ignore_errors: true - name: Abort installation if port is in use fail: msg: "Terminating installation: Karaf is already running on port {{ karaf_port }}" when: port_check_result.failed
This approach registers the result of the port check, ignores any initial failure, then explicitly triggers a failure only if the port was found open.
This adjusted logic will ensure your Playbook stops execution as soon as it detects that the target Karaf port is occupied—exactly what you need for your installation workflow.
内容的提问来源于stack exchange,提问作者ImranRazaKhan

