blog
blog copied to clipboard
Ansible 批量测试机器端口
trafficstars
此示例主要用到 wait_for 模块,文档参见:
http://docs.ansible.com/ansible/latest/wait_for_module.html
目的: 我们需要知道几百台机器的某几个端口是否开启的时候(也可用 nc 来判断)
- 建立 variables 文件
$ mkdir -p inventory/group_vars && touch inventory/group_vars/all.yml
$ cat nventory/group_vars/all.yml
---
ports:
- "2000"
- "3000"
hosts:
- ip: "192.168.0.40"
- ip: "192.168.0.41"
- ip: "192.168.0.42"
- ip: "192.168.0.43"
- ip: "192.168.0.44"
- ip: "192.168.0.45"
- 在建立完变量后,建立 inventory 文件
$ touch inventory/inventory
$ cat inventory/inventory
[local]
127.0.0.1
- 然后建立 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