ansible中的主机清单

发布时间:2026/7/12 1:41:50
ansible中的主机清单 概述Ansible 通过主机清单定义需要管理的远程服务器记录主机 IP / 域名、分组、变量、连接参数等信息ansible默认读取/etc/ansible/hosts文件并非/etc/hostsansible中可以将主机清单存放在指定的目录执行时用ansible -i 指定ansible主机清单有两种主流格式INI 格式传统简洁、YAML 格式这里主要讲解INI格式回到顶部主机清单格式基础单主机主机清单rootmaster:~# cat /etc/ansible/hosts10.37.99.63测试命令rootmaster:~# ansible 10.37.99.63 -m ping10.37.99.63 | SUCCESS {“ansible_facts”: {“discovered_interpreter_python”: “/usr/local/bin/python3.13”},“changed”: false,“ping”: “pong”}分组管理核心功能简单分组主机清单rootmaster:~# cat /etc/ansible/hosts[web]10.37.99.6310.37.120.9[db]10.37.99.63[es]10.37.120.9测试rootmaster:~# ansible web -m ping10.37.120.9 | SUCCESS {“ansible_facts”: {“discovered_interpreter_python”: “/usr/local/bin/python3.13”},“changed”: false,“ping”: “pong”}10.37.99.63 | SUCCESS {“ansible_facts”: {“discovered_interpreter_python”: “/usr/local/bin/python3.13”},“changed”: false,“ping”: “pong”}rootmaster:~# ansible db -m ping10.37.99.63 | SUCCESS {“ansible_facts”: {“discovered_interpreter_python”: “/usr/local/bin/python3.13”},“changed”: false,“ping”: “pong”}指定分组名称会连接不同的远程控制机器分组合并将db和es合并为一个新组rootmaster:~# cat /etc/ansible/hosts[web]10.37.99.6310.37.120.9[db]10.37.99.63[es]10.37.120.9这里必须使用:children当作后缀[data:children]dbes测试rootmaster:~# ansible data -m ping10.37.120.9 | SUCCESS {“ansible_facts”: {“discovered_interpreter_python”: “/usr/local/bin/python3.13”},“changed”: false,“ping”: “pong”}10.37.99.63 | SUCCESS {“ansible_facts”: {“discovered_interpreter_python”: “/usr/local/bin/python3.13”},“changed”: false,“ping”: “pong”}批量主机简写连续 IP / 数字主机快速书写[web]表示192.168.1.20 ~ 192.168.1.25共六台机器192.168.1.[20:25]server01 ~ server08server[01:08].test.com自行测试使用内置变量连接主机案例没有配置密钥使用密码连接远程主机[web]10.0.0.7 ansible_userroot ansible_password1 ansible_port22需要使用sshpaasapt install -y sshpass给组配置变量[web]192.168.1.10192.168.1.11[web:vars]ansible_userrootansible_port22envprod常用内置变量ansible_userSSH 登录用户ansible_passwordSSH 登录密码ansible_portSSH 登录端口ansible_ssh_private_key_fileSSH 登录的私钥路径ansible_become是否开启sudo授权ansible_become_user提权到哪个用户默认root