三、主机清单

发布时间 2023-12-13 17:34:07作者: 相信童话

三、主机清单

​ 在使用Ansible来批量管理主机的时候,通常我们需要先定义要管理哪些主机或者主机组而这个用于管理主机与主机组的文件就叫做Inventory,也叫主机清单。该文件默认位于/etc/ansible/hosts。当然我们也可以通过修改ansible配置文件的Inventory配置项来修改默认inventory的位置。

3.1 定义主机和组

  • 主机:可以使用域名、主机名、ip地址方式来表示
  • 组:使用[groupname]表示,中括号内的标识为组名
  1. 普通方式定义

    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
  1. 定义主机范围

    当需要添加的主机数量特别多,且具有连续特征,可以按范围进行定义:如

    [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
  1. 定义嵌套组

    组的嵌套,需要在组名后边加上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 选择主机与组

  1. 匹配所有主机

    ansible all --list-hosts
    
  2. 匹配指定的主机或组

    # 匹配webserver组
    ansible webserver --list-hosts
    
    # 匹配node1主机
    ansible node1 --list-hosts
    
    # 匹配不属于任何组的主机
    ansible ungrouped --list-hosts
    
  3. 通配符匹配

    ansible node* --list-hosts
    ansible 192.168.1.* --list-hosts
    ansible db*.example.com --list-hosts
    
  4. 组合条件匹配

  • ,:条件连接符,连接多个规则

  • &:前面的条件还必须满足当前条件才能被选择

  • !:此规则匹配到的主机或组,将不被选择

    # 匹配多个主机多个组
    ansible node*,webserver,server[a:c] --list-hosts
    
    # 匹配主机db1,web01并且还在db组中
    ansible 'db1,web01,&db' --list-hosts
    
    # 匹配webserver组中的所有主机,将server5排除
    ansible 'webserver,!server5' --list-hosts
    

由于有特殊字符,所以需要将表达式用单引号引起来。

  1. 正则表达式匹配

    正则表达式匹配需要用单引号引起来,且需要在正则表达式前面加~符号。

    [redhat@master ansible]$ ansible '~^(db|ser).*2' --list-hosts
      hosts (2):
        server2
        db2