本文实例讲述了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>参数的使用方法,详细规则及含义见下表:
更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 陈慧娴.1996-雪映美白96演唱会2CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 王子异《1996 Part.2》[FLAC/分轨][50.66MB]
- 贵族音乐《古典名曲与轻音乐钢琴 打开宝宝睡眠开关》[320K/MP3][155.91MB]
- 贵族音乐《古典名曲与轻音乐钢琴 打开宝宝睡眠开关》[FLAC/分轨][251.78MB]
- 黄韵玲2001-巴结音乐[全员集合][WAV+CUE]
- 郑绪岚2015-流金岁月·精选[首版][WAV+CUE]
- 周冰倩1995《沧桑情歌》JVC日本录制[WAV+CUE]
- 辛禄乐队.2024-热烈的少年【星辰】【FLAC分轨】
- 成龙.1996-龙的心【滚石】【WAV+CUE】
- 童安格.1991-一世情缘【宝丽金】【WAV+CUE】
- 韩红2010-擦肩而过[央金玛][WAV+CUE]
- RiccardoTesi-UnballoLiscio,Vol.II(2024)[24-48]FLAC
- 金池VS刘罡2009《双声情》[WAV+CUE]
- 冯奥迪《卄》[320K/MP3][67.08MB]
- 冯奥迪《卄》[FLAC/分轨][172.46MB]