ansible(二)—— inventory

ansible(二) -- inventory

例子直接从官网上摘抄。地址:http://docs.ansible.com/intro_inventory.html#id10

1、Ad-hoc commands

对于一些快速执行的而又无需写入保存的任务,ansible提供了这种特殊命令行的操作;这里官方地址:http://docs.ansible.com/intro_adhoc.html

官网给的解释很有趣,既然playbook如此强大,为何还要提供这种特殊的命令行呢,所以举例说明,假如你只想圣诞节间关机的情况下,只执行一条命令的效率很显然比写playbook文件的效果要更好

准备工作

在做之前,当然就是实现ssh无秘钥登录,即拷贝公钥到要管理的目标主机上

基本语法:

ansible 
 
  
 
  
    -m 
   
     -a 
    
      -i:指定 inventory 文件,使用当前目录下的 hosts all:针对 hosts 定义的所有主机执行,这里也可以指定组名或模式 -m:指定所用的模块,我们使用 Ansible 内置的 ping 模块来检查能否正常管理远端机器 -u:指定远端机器的用户 -a:参数部分 
     
    
  

模式

了解下命令行中的特殊模式

all 等价于inventory中的所有hosts 
one.example.com \\一台主机
one.example.com:two.example.com \\两台主机
192.168.1.50 \\也可以已IP地址指定
192.168.1.* \\通配符
#组的指定 
webservers
webservers:dbservers

#指定一个组,但是却不在另外一个组中
webservers:!phoenix

#指定交叉,加入webservers同时也必须加入staging中
webservers:&staging

#上面也可以综合起来写
webservers:dbservers:&staging:!phoenix

#传递变量,必须加上参数-e,但是一般不会用
webservers:!{{excluded}}:&{{required}}
#模糊匹配 
*.example.com *.com

#混合写法
one*.com:dbservers

#正则写法
~(web|db).*\.example\.com

2、inventory

inventory 文件用来定义你要管理的主机。其默认位置在 /etc/ansible/hosts ,如果不保存在默认位置,也可通过-i选项指定。

参照官网,这里inventory可以灵活多变的写成多样的形式来满足不同的需求

mail.example.com \\未分组的机器需要在hosts的顶部保留 
[webservers]
foo.example.com
bar.example.com

[dbservers]
one.example.com
two.example.com
three.example.com

[test:children] \\支持嵌套
webservers
dbservers
#支持基于非标准的SSH端口 
badwolf.example.com:5309

#支持跳转
jumper ansible_ssh_port=5555 ansible_ssh_host=192.168.1.50
#支持通配 
[webservers]
www[01:50].example.com \\表示www01-50.example.com的50个目标

[databases]
db-[a:f].example.com \\同理db-a - db-f.example.com的目标
#基于不同的主机不同的连接类型 
[targets]
localhost ansible_connection=local
other1.example.com ansible_connection=ssh ansible_ssh_user=mpdehaan
other2.example.com ansible_connection=ssh ansible_ssh_user=mdehaan

Host变量

#主机变量很容易被稍后的playbook引用 
[atlanta]
host1 http_port=80 maxRequestsPerChild=808
host2 http_port=303 maxRequestsPerChild=909

Group变量

#变量可以直接在组中全部应用 
[atlanta]
host1
host2

[atlanta:vars]
ntp_server=ntp.atlanta.example.com \\直接引用上面的host1和host2
proxy=proxy.atlanta.example.com

#同样支持嵌套
[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
northwest

3、Dynamic Inventory

在不同的系统平台上,ansible也提供了基于文本的形式来描述inventory,这部分还没太看明白,日后看明白,补充上这部分的内容

常用指令在上一篇已经提到,这里就不多做更多演示,而要完成日常任务都是依赖于各个模块提供的功能,我基本上日常中只用到了ansible的这些功能,关于ansible的核心,playbook,也会在后面的文章中去学习,和各位分享学习过程

你可能感兴趣的:(ansible,Inventory)