Python自动化运维之Ansible定义主机与组规则

一 点睛

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

六 分离主机与组特定数据

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

七 匹配目标

目标 (Patterns)匹配,格式为:ansible<pattern_goes_here>-m<module_name>-a<arguments>。

举例说明:重启webservers组的所有Apache服务。

ansible webservers -m service -a "name=httpd state=restarted"

<pattern_goes_here>参数的使用方法,详细规则及含义见下表:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值