您的位置:首页 > 其它

inventory file 与hosts patterns (ansible 机器清单 与 主机匹配模式)

2020-02-05 00:46 120 查看

Ansible配置:

ansible有两个核心配置文件: ansible.cfg 配置文件和Inventory配置文件

  • Ansible.cfg配置文件
  • Inventory机器列表配置

这里介绍Inventory配置文件

Inventory file:

Inventory file 机器清单,ansible用于管理机器节点的配置文件,类似系统的/etc/hosts文件。

默认的配置文件为:

/etc/ansible/hosts
(新版本默认的Inventory文件好像是 /home/ansible/ansible_hosts)。

Inventory文件遵循ini文件风格,[]标记分组,方便对机器列表的管理。

#inventory file例子,可在这里添加主机名hostname或者ip地址
#未分组的主机,添加在最前面
122.19.45.201
hostname1
122.19.45.[1:10]    #[1:10]表示所有1~10之间的数字,表示一组ip地址45.1、45.2、...

#分组管理的主机,以便对不同主机进行不同的管理,同一主机可同时属于不同组
[test0]     #组名
122.28.13.100
122.19.61.68:5030    #如果主机ssh端口不是22,可在地址后加:指定

[targets1]
localhost     ansible_connection=local
122.28.13.10  ansible_connection=ssh  ansible_ssh_user=user  #指定连接类型和连接用户名

[targets2]    #可配置主机变量
host1       http_port=80
host2       http_port=80 var2=xxx var3=xxx

[targets2:var]  #添加关键字var,配置组变量,对属于该组的所有主机都适用
var4=xxx
var5=xxx

[targets3:children]  #添加关键字children,把组作为其他组的子成员
targets1
targets2

ansible ad-hoc 命令的用法为:

ansible  <host_pattern> [options]

这里先讨论
host_pattern
部分的用法。 [options]部分用简单的
-m ping
来检测网络的连通性

Inventory文件的使用例子:

定义好Inventory文件后,通过:

  1. 命令行
    ansible <host-pattern> [options]
  2. playbook
    - hosts: <host-pattern>

<host-pattern>
部分指定对哪些机器或分组执行任务。

以ansible命令行命令为例:

#使用默认的inventory文件
ansible 121.28.13.100 -m ping # 检测13.100是否存活(必须在inventory文件中)
ansible all -m ping           # 检测所有主机是否存活
ansible targets1 -m ping      # 检测组targets1的主机是否存活

#使用指定的inventory文件
ansible all -i my_hosts_list -m ping # -i参数指定inventory文件

ansible不能操作 没有在Inventory中定义过的主机**

主机列表的正则匹配

ansible支持主机列表的正则匹配

  • 全量:
    all/*
  • 逻辑或:
    :

  • 逻辑非:
  • 逻辑与:
  • 切片:
    []
  • 正则匹配: 以
    ~
    开头
ansible all -m ping  #所有默认inventory文件中的机器
ansible "*" -m ping  #同上
ansible 121.28.13.* -m  ping #所有122.28.13.X机器

ansible  web1:web2  -m  ping  #所有属于组web1或属于web2的机器
ansible  web1:!web2  -m  ping #属于组web1,但不属于web2的机器
ansible  web1&web2  -m  ping  #属于组web1又属于web2的机器

ansible webserver[0]  -m  ping    #属于组webserver的第1台机器
ansible webserver[0:5]  -m  ping  #属于组webserver的第1到4台机器

ansible "~(beta|web)\.example\.(com|org)"  -m ping

转载于:https://www.cnblogs.com/iois/p/6403761.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
dengjiao4659 发布了0 篇原创文章 · 获赞 1 · 访问量 363 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: