Ansible详解(二)

一、YAML简介
二、Ansible组件
三、主机清单Invetory
四、PlayBook介绍
    
一、YAML简介
http://www.yaml.org
YAML:可以使用简单清单,散列表,标题等数据结构。
YAML的语法和其他高阶语言类似,并且可以简单表达清单、散列表、标量等数据结构。其结构(Structure)通过空格来展示,序列(Sequence)里的项用"-"来代表,Map里的键值对用":"分隔。下面是一个示例。
    yet another markup language //仍是一种标记语言
name: John kona //key为name,value为John,kona
age: 41
gender: Male
spouse: //kv可以嵌套,kev:value(key:value)
    name: Jane Smith  
    age: 37
    gender: Female //k/v可以嵌套
children:
    -   name: Jimmy Smith //-:列表,后面的都是列表元素    
        age: 17        //name和age,gender都是children的键key
        gender: Male
    -   name: Jenny Smith
        age 13
        gender: Female
    
YAML文件扩展名通常为.yaml,如example.yaml。

1)list
列表的所有元素均使用“-”打头,例如:
# A list of tasty fruits
- Apple
- Orange
- Strawberry
- Mango

2)dictionary
字典通过key与value进行标识 //多个key-value联合起来就叫做字典
例如:
---
# An employee record
name: Example Developer
job: Developer
skill: Elite

也可以将key:value放置于{}中进行表示,例如:
---
# An employee record
{name: Example Developer, job: Developer, skill: Elite}

二、Ansible组件
Inventory
Modules
Ad Hoc Commands
Playbooks组件:
    Tasks任务
    Variables变量,ansible有自带的变量,也可以自定义
    Templates模板,包含了模板语法的文本文件;
    Handlers处理器,特定条件下才会被触发的任务    
    Roles角色
    
三、主机清单Invetory
1.主机与组:/etc/ansible/hosts
Inventory
ansible的默认的inventory file为/etc/ansible/hosts。
inventory file可以有多个,且也可以通过Dynamic Inventory来动态生成。

inventory文件格式
inventory文件遵循INI文件风格,中括号中的字符为组名。可以将同一个主机同时归并到多个不同的组中;此外,当如若目标主机使用了非默认的SSH端口,还可以在主机名称之后使用冒号加端口号来标明。
ntp.wolf.com

[webservers]
www1.wolf.com:2222
www2.wolf.com

[dbservers]
db1.wolf.com
db2.wolf.com
db3.wolf.com

如果主机名称遵循相似的命名模式,还可以使用列表的方式标识各主机,例如:

[webservers]
www[01:50].example.com

[databases]
db-[a:f].example.com

2.主机变量
可以在inventory中定义主机时为其添加主机变量以便于在playbook中使用。例如:
[webservers]
www1.wolf.com http_port=80 maxRequestsPerChild=808
www2.wolf.com http_port=8080 maxRequestsPerChild=909

3.组变量
组变量是指赋予给指定组内所有主机上的在playbook中可用的变量。例如:
[webservers]
www1.wolf.com
www2.wolf.com

[webservers:vars]
ntp_server=ntp.wolf.com
nfs_server=nfs.wolf.com

4.组嵌套
inventory中,组还可以包含其它的组,并且也可以向组中的主机指定变量。不过,这些变量只能在ansible-playbook中使用,而ansible不支持。例如:

[apache]
httpd1.wolf.com
httpd2.wolf.com

[nginx]
ngx1.wolf.com
ngx2.wolf.com

[webservers:children]
apache
nginx

[webservers:vars]
ntp_server=ntp.wolf.com

5.inventory参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
ansible基于 ssh 连接inventory中指定的远程主机时,还可以通过参数指定其交互方式;这些参数如下所示:
ansible_ssh_host  // 将要连接的远程主机名.与你想要设定的主机的别名不同的话,可通过此变量设置.
ansible_ssh_port   //ssh 端口号.如果不是默认的端口号,通过此变量设置.
ansible_ssh_user   // 默认的  ssh  用户名
ansible_ssh_pass   //ssh  密码(这种方式并不安全,我们强烈建议使用 --ask-pass 或 SSH 密钥)
ansible_sudo_pass   //sudo  密码(这种方式并不安全,我们强烈建议使用 --ask- sudo -pass)
ansible_sudo_exe (new  in  version 1.8)   //  sudo  命令路径(适用于1.8及以上版本)
ansible_connection   //  与主机的连接类型.比如: local ssh  或者 paramiko. Ansible 1.2 以前默认使用 paramiko.1.2 以后默认使用  'smart' , 'smart'  方式会根据是否支持 ControlPersist, 来判断 'ssh'  方式是否可行.
ansible_ssh_private_key_file  //ssh  使用的私钥文件.适用于有多个密钥,而你不想使用 SSH 代理的情况.
ansible_shell_type  // 目标系统的shell类型.默认情况下,命令的执行使用  'sh'  语法,可设置为  'csh'  或  'fish' .
ansible_python_interpreter 
     目标主机的 python 路径.适用于的情况: 系统中有多个 Python, 或者命令路径不是 "/usr/bin/python" ,比如  \*BSD, 或者  /usr/bin/python
     不是 2.X 版本的 Python.我们不使用  "/usr/bin/env"  机制,因为这要求远程用户的路径设置正确,且要求  "python"  可执行程序名不可为 python以外的名字(实际有可能名为python26).
     与 ansible_python_interpreter 的工作方式相同,可设定如 ruby 或 perl 的路径....
[webservers]   // 组名用[ ] 
foo.example.com
bar.example.com
[dbservers]
badwolf.example.com:5309   // 端口号不是默认22
jumper ansible_ssh_port=5555 ansible_ssh_host=192.168.1.50   //jumper 是主机名,ansible_ssh_port和ansible_ssh_port是主机变量,适用于单个主机
other1.example.com     ansible_connection= ssh         ansible_ssh_user=mpdehaan  // 指定用户名
localhost              ansible_connection= local
[atlanta]
host1 http_port=80 maxRequestsPerChild=808   // 主机变量
host2 http_port=303 maxRequestsPerChild=909
一个系统可以属于不同的组,比如一台服务器可以同时属于 webserver组 和 dbserver组.这时属于两个组的变量都可以为这台主机所用,至于变量的优先级关系将于以后讨论.

==============================================================================
四、PlayBook介绍
Playbook的基础组件:
    Hosts:运行指定任务的目标主机 //多个冒号分割
    remote_user:在远程主机上执行任务的用户
        sudo_user: //指定切换的身份
    tasks:任务列表
        模块,模块参数:自上而下运行
        格式:
            action:module arguments
            motuled:arguments //新版本的
            
        注意:shell和command模块后面直接跟命令,而非key=value类的参数列表
    1.某任务的状态在运行后为changed时,可通过notify通知给handlers;
    2.任务可以通过"tags"打标签,而后在ansible-playbook命令上使用-t指定    
        
1.第一个playbook
[root@localhost ~]# cat a.yaml //格式严格对齐
[root@localhost ~]# cat a.yaml
- hosts: testweb
  remote_user: root
  tasks:
  - name: crete a user3
    user: name=user3 system=true uid=306
-  hosts: testweb2
  remote_user: root
  tasks:
  - name: crete a user4
    user: name=user4 system=true uid=307
[root@localhost ~]#
//注运行顺序:先运行user3,在运行user4 task
//空格,不是tab对齐。
    
ansible-playbook
    -v verbose
    -s sudo 
    --list-hosts //只输出匹配到的主机,而不返回任何命令
    --check //不做修改,仅测试在远程主机上将会改变什么,干跑一遍
            
ansible-playbook --check a.yaml //格式必须对齐
    //提示OK=3,有一个是远程主机的facts变量
    ansible-doc -s setup
    ansible 192.168.4.106 -m setup //收集远程主机的变量信息

2.tasks示例    
- hosts: websrvs
  remote_user: root
  tasks:
  - name: install httpd package
    yum: name=httpd state=present
  - name: install configure file
    copy: src=files/httpd.conf dest=/etc/httpd/conf/
  - name: start service httpd
    service: name=httpd state=started
  - name: execute ss command
    shell: ss -tnl |grep 80
ansible all -m yum -a "name=httpd state=absent" //卸载目标主机的httpd
ansible websrvs -m shell -a "ss -tnl |grep 80" 
    //ansible 可以与运行多遍,不管目标主机是否已经执行该操作    
    
3.handler:
    任务,在特定条件下触发
    接受到其他任务的通知时被触发
    
    某任务的状态为changed时,可通过notify通知相应的handlers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- hosts: websrvs
   remote_user: root
   tasks:
   - name:  install  httpd package
     yum: name=httpd state=present
   - name:  install  configure  file
     copy: src=files /httpd .conf dest= /etc/httpd/conf/
     notify: restart httpd         // 只有在notify发生改变的时候,重复执行才会触发handler,
   - name: start service httpd
     service: name=httpd state=started
   handlers:  
   - name: restart httpd
     service: name=httpd state=restarted
// 只有在配置文件发生改变的时候,handlers才会被触发    
     handlers:--> changed  // 发生了改变,实验只是修改了httpd.conf文件
     handlers:-->ok  // 文件没有发生改变

    注:会重复执行这些操作{即使已经操作过了},install ,install和start //重复操作,可以打标签,指定只运行哪些操作
        例如:发现目标httpd已经安装了,不再重新安装而已
4.tag
    ansible-playboot -t instconf --check a.yaml //-t可以指定多个标签

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[root@localhost ~] # cat b.yaml 
- hosts: websrvs
   remote_user: root
   tasks:
   - name:  install  httpd package
     yum: name=httpd state=present
     tags: package
   - name:  install  configure  file
     copy: src=files /httpd .conf dest= /etc/httpd/conf/
     tags: package         // 两个tags可以同名,将会被同时执行上
     notify: restart httpd
   - name: start service httpd
     service: name=httpd state=started
     tags: start
   handlers:
   - name: restart httpd
     service: name=httpd state=restarted

    
ansible-playbook --tag package b.yaml     
    
5.变量: variables:
变量来源:

来源一.inventory file中定义的变量
来源二.playbook中定义的变量
来源三.include文件和角色中定义的变量
来源四.系统facts变量,可以通过 ansible hostname -m setup来获取。当然你也可以通过安装拓展包来获取更多的系统变量信息。例如拓展facter和ohai。
来源五.local facts
    

    1.facts:由setup模块提供,可直接调用
        ansible-doc -s setup
        关闭facts:
            - host: all 
              gather_facts: no
        ansible <hostname> -m setup -a "filter=ansible_local"    
        在template和playbook中访问该数据:{{ ansible_local.preferences.general.asdf }} /{{ ansible_eth0.ipv4.address }}
    在ansible中缓存facts使用redis //yum install redis &&start 
        [defaults]
        gathering = smart
        fact_caching = redis
        fact_caching_connection = /path/to/cachedir
        fact_caching_timeout = 86400
        # seconds    
    2.ansible-playbook命令行中的自定义变量
        -e ARGS,--extra-vars=VARS
    3.通过roles传递变量
    4.Host Inventory //可以向不同主机传递不同的变量
        a.向不同的主机传递不同的变量
        b.向组中的主机传递相同的变量
            [testvaer] //建立一个新的组,然后添加
            http_port=8080
            192.168.4.100
            192.168.4.112   //这样这两个主机使用的变量都一样了
            注:组可以嵌套    
ansible-playbook -e pkname=memcached --check c.yaml 

1
2
3
4
5
6
[root@localhost ~] # cat c.yaml 
- hosts: websrvs
   remote_user: root
   tasks:
   - name:  install  {{ pkname }}
     yum: name={{ pkname }} state=present

=========================================
每个主机使用不同的变量,被赋予不同的主机名
ansible-playbook --check c.yaml     

1
2
3
4
5
6
[root@localhost ~] # cat c.yaml 
- hosts: websrvs
   remote_user: root
   tasks:
   - name:  install  {{ hname }}
     hostname : name={{ hname }}

    
[root@localhost ~]# cat /etc/ansible/hosts
# This is the default ansible 'hosts' file.
[websrvs]
192.168.4.110 hname=www1
192.168.4.106 hname=www2

参考:http://www.ansible.com.cn/docs/intro_inventory.html#inventoryformat
注:template和role后再后续介绍












本文转自MT_IT51CTO博客,原文链接:http://blog.51cto.com/hmtk520/2058175,如需转载请自行联系原作者

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值