三、主机清单
三、主机清单
在使用Ansible来批量管理主机的时候,通常我们需要先定义要管理哪些主机或者主机组而这个用于管理主机与主机组的文件就叫做Inventory,也叫主机清单。该文件默认位于/etc/ansible/hosts。当然我们也可以通过修改ansible配置文件的Inventory配置项来修改默认inventory的位置。
3.1 定义主机和组
- 主机:可以使用域名、主机名、ip地址方式来表示
- 组:使用[groupname]表示,中括号内的标识为组名
-
普通方式定义
web01 web02 [webservers] node1 node2 node3 192.168.1.100 [db] db1.example.com db2.example.com 192.168.1.101
在上面的例子中,定义了一个webservers组,组中有node1、node2、node3和192.168.1.100四台主机;还定义了一个db组,组中有db1.example.com、db2.example.com、192.168.1.101三台主机;web01、web02不属于任何组。
可以使用ansible all --list-hosts来查看主机
[redhat@master ansible]$ ansible all --list-hosts hosts (9): web01 web02 node1 node2 node3 192.168.1.100 db1.example.com db2.example.com 192.168.1.101
-
定义主机范围
当需要添加的主机数量特别多,且具有连续特征,可以按范围进行定义:如
[webservers] web[01:50] [db] db[1:50].example.com [cache] 192.168.1.[100:120] [backup] backup-[a:z].example.com
-
web[01:50]:表示web01-web50共50台主机
-
db[1:50].example.com:表示db1.example.com到db50.example.com共50台主机
-
192.168.1.[100:120]:表示192.168.1.100到192.168.1.120共20台主机
-
backup-[a:z].example.com:表示backup-a.example.com到backup-z.example.com共26台主机
[redhat@master ansible]$ ansible cache --list-hosts hosts (21): 192.168.1.100 192.168.1.101 192.168.1.102 192.168.1.103 192.168.1.104 192.168.1.105 192.168.1.106 192.168.1.107 192.168.1.108 192.168.1.109 192.168.1.110 192.168.1.111 192.168.1.112 192.168.1.113 192.168.1.114 192.168.1.115 192.168.1.116 192.168.1.117 192.168.1.118 192.168.1.119 192.168.1.120
-
定义嵌套组
组的嵌套,需要在组名后边加上children关键字。
[redhat@master ansible]$ cat hosts [webserver] web01 web02 [db] db1 db2 [servers:children] webserver db [servers] node1 [redhat@master ansible]$ ansible servers --list-hosts hosts (4): node1 web01 web02 db1 db2
3.2 选择主机与组
-
匹配所有主机
ansible all --list-hosts
-
匹配指定的主机或组
# 匹配webserver组 ansible webserver --list-hosts # 匹配node1主机 ansible node1 --list-hosts # 匹配不属于任何组的主机 ansible ungrouped --list-hosts
-
通配符匹配
ansible node* --list-hosts ansible 192.168.1.* --list-hosts ansible db*.example.com --list-hosts
-
组合条件匹配
-
,
:条件连接符,连接多个规则 -
&
:前面的条件还必须满足当前条件才能被选择 -
!
:此规则匹配到的主机或组,将不被选择# 匹配多个主机多个组 ansible node*,webserver,server[a:c] --list-hosts # 匹配主机db1,web01并且还在db组中 ansible 'db1,web01,&db' --list-hosts # 匹配webserver组中的所有主机,将server5排除 ansible 'webserver,!server5' --list-hosts
由于有特殊字符,所以需要将表达式用单引号引起来。
-
正则表达式匹配
正则表达式匹配需要用单引号引起来,且需要在正则表达式前面加
~
符号。[redhat@master ansible]$ ansible '~^(db|ser).*2' --list-hosts hosts (2): server2 db2
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)