inventory文件默认路径:/etc/ansible/hosts,可以使用多个inventory文件。

主机与组

/etc/ansible/hosts 文件的格式:

  1. mail.example.com
  2. [webservers]
  3. foo.example.com
  4. bar.example.com
  5. [dbservers]
  6. one.example.com
  7. two.example.com
  8. three.example.com

方括号[]中是组名,一台服务器可以同时属于不同的组。

如果某个主机(服务器)的SSH端口不是标准的22端口,可在主机名之后加上端口号,用冒号分隔。如:
badwolf.example.com:5309

可以给静态IP地址设置别名:

  1. master ansible_ssh_port=5555 ansible_ssh_host=192.168.1.50

多个相似的主机可使用[]简写, 如:

  1. [webservers]
  2. www[01:50].example.com
  3. [databases]
  4. db-[a:f].example.com

inventory的主机常见设定:

  1. ansible_ssh_host 主机的名字 SSH目的主机名或IP
  2. ansible_ssh_port 22 SSH目的端口
  3. ansible_ssh_user root SSH登录使用的用户名
  4. ansible_ssh_pass none SSH认证所使用的密码
  5. ansible_connection smart ansible使用何种连接模式连接到主机
  6. ansible_ssh_private_key_file none SSH认证所使用的私钥
  7. ansible_shell_type sh 命令所使用的shell
  8. ansible_python_interpreter /usr/bin/python 主机上的python解释器


主机与组的变量

定义主机的变量:

  1. [atlanta]
  2. host1 http_port=80 maxRequestsPerChild=808
  3. host2 http_port=303 maxRequestsPerChild=909

定义组的变量:

  1. [atlanta]
  2. host1
  3. host2
  4. [atlanta:vars]
  5. ntp_server=ntp.atlanta.example.com
  6. proxy=proxy.atlanta.example.com


把一个组作为另一个组的成员

通过children可以把一个组作为另一个组的成员,以及分配变量给整个组使用。
这些变量可以给 /usr/bin/ansible-playbook 使用,但不能给 /usr/bin/ansible 使用:

  1. [atlanta]
  2. host1
  3. host2
  4. [raleigh]
  5. host2
  6. host3
  7. [southeast:children]
  8. atlanta
  9. raleigh
  10. [southeast:vars]
  11. some_server=foo.southeast.example.com
  12. halon_system_timeout=30
  13. self_destruct_countdown=60
  14. escape_pods=2
  15. [usa:children]
  16. southeast
  17. northeast
  18. southwest
  19. northwest


在独立文件中定义主机或组的变量

在独立文件中定义主机的变量:/etc/ansible/host_vars/foosball在独立文件中定义组的变量:/etc/ansible/group_vars/webservers
上面的文件需要是YAML格式的。

Tip:

  • group_vars/ 和 host_vars/ 目录可放在 inventory 目录下,或是 playbook 目录下. 如果两个目录下都存在,那么 playbook 目录下的配置会覆盖 inventory 目录的配置
  • 建议把 inventory 文件 和 变量 放入 git repo 中。

动态inventory

动态 Inventory

其实,Ansible Inventory 是包含静态 Inventory动态 Inventory 两部分的,静态 Inventory 指的是在文件中指定的主机和组,动态 Inventory 指通过外部脚本获取主机列表,并按照 ansible 所要求的格式返回给 ansilbe 命令的。这部分一般会结合 CMDB 资管系统、云计算平台等获取主机信息。由于主机资源一般会动态的进行增减,而这些系统一般会智能更新。我们可以通过这些工具提供的 API 或者接入库查询等方式返回主机列表。

比如为了结合资产管理系统(CMDB),所以要使用到动态获取 inventory 的方法,这样可以省去配置 ansible 服务端的 hosts,所有的客户端 IP、帐号、密码、端口都可以从 CMDB 中获取到。

只要你的脚本输出格式是满足要求的 JSON,这样就可以成为一个动态的资产生成器。