使用ansible打开端口时安装代理

时间:2019-11-13 09:33:00

标签: ansible port

在安装ansible之前,我需要检查端口是否打开。我写了下面的剧本。

- name: Check all port numbers are opened
  wait_for:
    port: "{{ item }}"
    state: started    
  with_items:
    - "{{ agent_port }}"
    - "{{ service_port }}"

需要做什么:
1.如果打开了端口,则继续下一步。
2.打印一条消息,提示无法安装

2 个答案:

答案 0 :(得分:0)

如果未在 timeout

中启动任何端口,则

wait_for 将失败

- name: Check all port numbers are opened
  wait_for:
    port: "{{ item }}"
    state: started
    timeout: 5
    msg: "{{ item }} is not started. Installation cannot happen."
  with_items:
    - "{{ agent_port }}"
    - "{{ service_port }}"

- debug:
    msg: "Continue to next step ..."

例如下面的播放(开放的端口22和25)

- hosts: localhost
  tasks:
    - wait_for:
        port: "{{ item }}"
        state: started
        timeout: 3
        msg: "{{ item }} is not started. Installation cannot happen."
      loop:
        - 22
        - 25
      # - 6566

    - debug:
        msg: Continue

给予

ok: [localhost] => (item=22)
ok: [localhost] => (item=25)

ok: [localhost] => {
    "msg": "Continue"

,但在关闭端口6566时将失败

ok: [localhost] => (item=22)
ok: [localhost] => (item=25)
failed: [localhost] (item=6566) => {"ansible_loop_var": "item", "changed": false, "elapsed": 3, "item": 6566, "msg": "6566 is not started. Installation cannot happen."}

答案 1 :(得分:0)

这未经测试,但是可以使您了解如何将pre_tasks与任务一起使用。.pre_tasks是Ansible在执行任何任务之前执行的任务

- name: Check all port numbers are opened
  pre_tasks:
    - name: Ensure {{ item }} port is opened
      wait_for:
        port: {{ item }}
        state: started
      with_items:
         - "{{ agent_port }}"
         - "{{ service_port }}"

  tasks:
     - name: actual installation tasks will come here.
       ----
       ----
       ----