penglongli / blog

18 stars 1 forks source link

Ansible 批量测试机器端口 #46

Open penglongli opened 6 years ago

penglongli commented 6 years ago

此示例主要用到 wait_for 模块,文档参见: http://docs.ansible.com/ansible/latest/wait_for_module.html

目的: 我们需要知道几百台机器的某几个端口是否开启的时候(也可用 nc 来判断)

  1. 建立 variables 文件
    
    $ mkdir -p inventory/group_vars && touch inventory/group_vars/all.yml
    $ cat nventory/group_vars/all.yml
    ---
    ports:
    - "2000"
    - "3000"

hosts:

  1. 在建立完变量后,建立 inventory 文件

    $ touch inventory/inventory
    $ cat inventory/inventory
    [local]
    127.0.0.1
  2. 然后建立 playbook 文件

    $ touch playbook.yml
    $ cat playbook.yml
    ---
    - hosts: local
    connection: local
    
    tasks:
    - name: Check port
      wait_for:
        host: "{{ item.0.ip }}"
        port: "{{ item.1 }}"
        state: started
        delay: 0
        timeout: 2
      ignore_errors: yes
      with_nested:
        - "{{ hosts }}"
        - "{{ ports }}"

然后执行:

$ ansible-playbook -i inventory/inventory playbook.yml

源码见: https://github.com/penglongli/ansible-sample/tree/master/sample-4