inventory文件默认路径:/etc/ansible/hosts,可以使用多个inventory文件。
主机与组
/etc/ansible/hosts 文件的格式:
mail.example.com[webservers]foo.example.combar.example.com[dbservers]one.example.comtwo.example.comthree.example.com
方括号[]中是组名,一台服务器可以同时属于不同的组。
如果某个主机(服务器)的SSH端口不是标准的22端口,可在主机名之后加上端口号,用冒号分隔。如:badwolf.example.com:5309
可以给静态IP地址设置别名:
master ansible_ssh_port=5555 ansible_ssh_host=192.168.1.50
多个相似的主机可使用[]简写, 如:
[webservers]www[01:50].example.com[databases]db-[a:f].example.com
inventory的主机常见设定:
ansible_ssh_host 主机的名字 SSH目的主机名或IPansible_ssh_port 22 SSH目的端口ansible_ssh_user root SSH登录使用的用户名ansible_ssh_pass none SSH认证所使用的密码ansible_connection smart ansible使用何种连接模式连接到主机ansible_ssh_private_key_file none SSH认证所使用的私钥ansible_shell_type sh 命令所使用的shellansible_python_interpreter /usr/bin/python 主机上的python解释器
主机与组的变量
定义主机的变量:
[atlanta]host1 http_port=80 maxRequestsPerChild=808host2 http_port=303 maxRequestsPerChild=909
定义组的变量:
[atlanta]host1host2[atlanta:vars]ntp_server=ntp.atlanta.example.comproxy=proxy.atlanta.example.com
把一个组作为另一个组的成员
通过children可以把一个组作为另一个组的成员,以及分配变量给整个组使用。
这些变量可以给 /usr/bin/ansible-playbook 使用,但不能给 /usr/bin/ansible 使用:
[atlanta]host1host2[raleigh]host2host3[southeast:children]atlantaraleigh[southeast:vars]some_server=foo.southeast.example.comhalon_system_timeout=30self_destruct_countdown=60escape_pods=2[usa:children]southeastnortheastsouthwestnorthwest
在独立文件中定义主机或组的变量
在独立文件中定义主机的变量:/etc/ansible/host_vars/foosball在独立文件中定义组的变量:/etc/ansible/group_vars/webservers
上面的文件需要是YAML格式的。
Tip:
- group_vars/ 和 host_vars/ 目录可放在 inventory 目录下,或是 playbook 目录下. 如果两个目录下都存在,那么 playbook 目录下的配置会覆盖 inventory 目录的配置
- 建议把 inventory 文件 和 变量 放入 git repo 中。
动态inventory
其实,Ansible Inventory 是包含静态 Inventory 和动态 Inventory 两部分的,静态 Inventory 指的是在文件中指定的主机和组,动态 Inventory 指通过外部脚本获取主机列表,并按照 ansible 所要求的格式返回给 ansilbe 命令的。这部分一般会结合 CMDB 资管系统、云计算平台等获取主机信息。由于主机资源一般会动态的进行增减,而这些系统一般会智能更新。我们可以通过这些工具提供的 API 或者接入库查询等方式返回主机列表。
比如为了结合资产管理系统(CMDB),所以要使用到动态获取 inventory 的方法,这样可以省去配置 ansible 服务端的 hosts,所有的客户端 IP、帐号、密码、端口都可以从 CMDB 中获取到。
只要你的脚本输出格式是满足要求的 JSON,这样就可以成为一个动态的资产生成器。
