Ansible - 4 - 清单定义


Ansible 清单(Inventory)

Ansible 主机清单(Inventory)

Ansible通过Inventory(可管理的主机集合)对远端服务器或者主机进行统一操作和管理,默认将主机列在一个文本文件中,这个文件称为Inventory文件。

  • 默认的路径和文件为:/etc/ansible/hosts
  • 可以通过ANSIBLE_HOSTS环境变量、ansible.cfg文件中inventory参数来指定,或者运行ansible和ansible-playbook时使用-i参数临时指定
  • 可以有多个 inventory 文件,也可以通过 Dynamic Inventory 动态生成
  • inventory文件为 INI文件格式,中括号中的字符为组名。可以将同一个主机同时归并到多个不同的组中
  • 组名建议使用"_"来连接字符,例如“aaa_bbb_ccc”

Ansible Inventory文件

192.168.56.1    # 未分组
test.example.com  
127.0.0.1 ansible_connection=local  # 直接访问本地主机,而不是通过SSH

[Test]  # 已分组名称
192.168.56.1
192.168.56.2
192.168.56.[3:4]  # 通过列表方式通配地址
192.168.56.[5:6]  # 多个通配地址
anliven-[a:d].example.com  # 通配主机域名

[Test:vars]  # 定义组变量
ansible_ssh_user="anliven"
ansible_ssh_pass="anliven"
ansible_ssh_port="22"

[Test2]  # 在分组中指定变量
192.168.56.[1:2] ansible_ssh_user=anliven ansible_ssh_pass=Anliven
192.168.56.[3:4] ansible_ssh_user=anliven ansible_ssh_pass=Anliven
192.168.56.[3:4]

[Test3]  # 在分组中切换root用户 
192.168.56.[1:2] ansible_ssh_port="22" ansible_ssh_user="anliven" ansible_ssh_pass="anliven"  ansible_become_pass="Anliven" 

[Temp]
192.168.56.1:2222  # 指定端口
192.168.56.2 http_port=8080 var1=test1 var2=test2   # 定义主机时为其添加主机变量以便于在playbook中使用

[Temp:vars]
ansible_ssh_user="anliven"
ansible_ssh_pass="anliven"

[TestGroup:children]  # 嵌套组,TestGroup为名称,其他为固定格式 
Test1
Test2
Test3

[TestGroup:vars]  # 嵌套组的变量只能在ansible-playbook中使用
var1="test1"
var2="123"

[all:vars]  # 类似全局变量,对inventory文件中所有节点都有效
ansible_ssh_port="22"

Ansible Inventory内置参数

Ansible Inventory文件中可使用的行为参数

可以在ansible.cfg中的[defaults]部分更改一些Inventory行为参数的默认值

Ansible Dynamic Inventory

  • 动态Inventory也就是Ansible所有的Inventory文件里面的主机列表和变量信息都支持从外部拉取,例如CMDB等。
  • 避免主机列表不准确和频繁大量的手动更新的问题
  • 也可以通过设置ansible.cfg文件中的inventory参数为一个可执行脚本,将CMDB等其他系统的主机信息同步至Ansible中。
  • 对动态Inventory脚本的参数和输出必须遵循格式规则

Ansible Inventory分割

通过Inventory分割满足如下需要

  • 按不同业务/系统分割成的多个Inventory文件
  • 同时使用常规Inventory文件和动态Inventory脚本

实现方式

  • 配置ansible.cfg文件的hostfile参数,指定放置inventory文件目录作为Inventory,Ansible将合并目录里所有文件为一个完整的Inventory
  • 也可以在命令行中使用-i命令来指定特定的Inventory文件
[defaults]

hostfile = /etc/ansible/inventory  # 指定目录作为Inventory

全文跳转链接

Ansible系列全文地址https://www.cnblogs.com/anliven/p/16859401.html


posted @ 2022-11-04 22:23  Anliven  阅读(162)  评论(0编辑  收藏  举报