定义主机与组规则

Ansible 通过定义好的主机与组规则(Inventory)对匹配的目标主机进行远程操作,配置规则文件默认是 /etc/ansible/hosts。

定义主机与组

所有定义的主机与组规则都在 /etc/Ansible/hosts 文件中,为 ini 文件格式,主机可以用域名、IP、别名进行标识,其中 webservers、dbservers 为组名,紧跟着的主机为其成员。格式如下:

mail.example.com
192.168.1.21:2135
[webservers]
foo.example.com
bar.example.com
192.168.1.22
[dbservers]
one.example.com
two.example.com
three.example.com
192.168.1.23

其中,192.168.1.21:2135 的意思是定义一个 SSH 服务端口为 2135 的主机,当然我们也可以使用别名来描述一台主机,如:

jumper ansible_ssh_port=22 ansible_ssh_host=192.168.1.50

jumper 为定义的一个别名,ansible_ssh_port 为主机 SSH 服务端口,ansible_ssh_host 为目标主机,更多保留主机变量如下:

  • ansible_ssh_host,连接目标主机的地址。

  • ansible_ssh_port,连接目标主机 SSH 端口,端口 22 无需指定。

  • ansible_ssh_user,连接目标主机默认用户。

  • ansible_ssh_pass,连接目标主机默认用户密码。

  • ansible_connection,目标主机连接类型,可以是 local、ssh 或 paramiko。

  • ansible_ssh_private_key_file 连接目标主机的 ssh 私钥。

  • ansible_*_interpreter,指定采用非 Python 的其他脚本语言,如 Ruby、Perl 或其他类似 ansible_python_interpreter 解释器。

组成员主机名称支持正则描述,示例如下:

[webservers]
www[01:50].example.com
[databases]
db-[a:f].example.com

定义主机变量

主机可以指定变量,以便后面供 Playbooks 配置使用,比如定义主机 hosts1 及 hosts2 上 Apache 参数 http_port 及 maxRequestsPerChild,目的是让两台主机产生 Apache 配置文件 httpd.conf 差异化,定义格式如下:

[atlanta]
host1 http_port=80 maxRequestsPerChild=808
host2 http_port=303 maxRequestsPerChild=909

定义组变量

组变量的作用域是覆盖组所有成员,通过定义一个新块,块名由组名+“:vars” 组成,定义格式如下:

[atlanta]
host1
host2
[atlanta:vars]
ntp_server=ntp.atlanta.example.com
proxy=proxy.atlanta.example.com

同时 Ansible 支持组嵌套组,通过定义一个新块,块名由组名+“:children” 组成,格式如下:

[atlanta]
host1
host2
[raleigh]
host2
host3
[southeast:children]
atlanta
raleigh
[southeast:vars]
some_server=foo.southeast.example.com
halon_system_timeout=30
self_destruct_countdown=60
escape_pods=2
[usa:children]
southeast
northeast
southwest
southeast

嵌套组只能使用在 /usr/bin/ansible-playbook 中,在 /usr/bin/ansible 中不起作用。

分离主机与组特定数据

为了更好规范定义的主机与组变量,Ansible 支持将 /etc/ansible/hosts 定义的主机名与组变量单独剥离出来存放到指定的文件中,将采用 YAML 格式存放,存放位置规定:“/etc/ansible/group_vars/+组名” 和 “/etc/ansible/host_vars/+主机名” 分别存放指定组名或主机名定义的变量,例如:

/etc/ansible/group_vars/dbservers
/etc/ansible/group_vars/webservers
/etc/ansible/host_vars/foosball

定义的 dbservers 变量格式为:

---
ntp_server: acme.example.org
database_server: storage.example.org

在 Ansible 1.2 及以后版本中,group_vars/ 和 host_vars/ 目录可以保存在 playbook 目录或 inventory 目录,如同时存在,inventory 目录的优先级高于 playbook 目录的。