Python自动化运维之Ansible定义主机与组规则操作详解 本文实例讲述了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-m-a。 举例说明:重启webservers组的所有Apache服务。 ansible webservers -m service -a "name=httpd state=restarted" 参数的使用方法,详细规则及含义见下表: 更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》 希望本文所述对大家Python程序设计有所帮助。