The host list ansible, yml grammar, playbook Detailed operating +

In this section:
a .inventory host list
two .yml grammar
three .playbook Detailed operation +

inventory list of hosts

ansible默认的主机清单是/etc/ansible/hosts文件
主机清单可以手动设置,也可以通过Dynamic Inventory动态生成
一般主机名使用FQDN

vi /etc/ansible/hosts
[webserver]      #方括号设置组名
www1.example.org    #定义被监控主机,这边可以是主机名也可以是IP地址,主机名需要修改/etc/hosts文件
www2.example.org:2222     #冒号后定义远程连接端口,默认是ssh的22端口

如果是名称类似的主机,可以使用列表的方式标识各个主机
[webserver]
www[01:50].example.org ansible_ssh_user=root ansible_ssh_pass=123456

[dbbservers]
db-[a:f].example.org

The following are the variables Inventory

(1)主机变量
[webserver]
www1.magedu.com http_port=80 maxRequestsChild=808
www2.magedu.com http_port=8080 maxRequestsChild=909
(2)组变量
[servers:vars]
ntp_server=ntp.example.org
nfs_server=nfs.example.org
(3)组嵌套
[apache]
http1.example.org
http2.example.org

[nginx]
ngx1.example.org
ngx2.example.org

[webservers:children]
apache
nginx

(4)inventory变量参数
参数                          说明
ansible_ssh_host    将要连接的远程主机名.与你想要设定的主机的别名不同的话,可通过此变量设置.
ansible_ssh_port    ssh端口号.如果不是默认的端口号,通过此变量设置.
ansible_ssh_user    默认的 ssh 用户名
ansible_ssh_pass    ssh 密码(这种方式并不安全,我们强烈建议使用 --ask-pass 或 SSH 密钥)
ansible_ssh_private_key_file    ssh 使用的私钥文件.适用于有多个密钥,而你不想使用 SSH 代理的情况.
ansible_ssh_common_args 此设置附加到sftp,scp和ssh的缺省命令行
ansible_sftp_extra_args 此设置附加到默认sftp命令行。
ansible_scp_extra_args  此设置附加到默认scp命令行。
ansible_ssh_extra_args  此设置附加到默认ssh命令行。
ansible_ssh_pipelining  确定是否使用SSH管道。 这可以覆盖ansible.cfg中得设置。
ansible_shell_type  目标系统的shell类型.默认情况下,命令的执行使用 'sh' 语法,可设置为 'csh' 或 'fish'.
ansible_python_interpreter  目标主机的 python 路径.适用于的情况: 系统中有多个 Python, 或者命令路径不是"/usr/bin/python",比如 *BSD, 或者 /usr/bin/python
ansible_*_interpreter   这里的"*"可以是ruby 或perl 或其他语言的解释器,作用和ansible_python_interpreter 类似
ansible_shell_executable    这将设置ansible控制器将在目标机器上使用的shell,覆盖ansible.cfg中的配置,默认为/bin/sh。

yaml grammar

The difference between objects and collections:

对象
  属性1  长:5m
  属性2  宽:2m
  属性3  高:1.5m
集合
  对象1
  对象2
  对象3

YAML: another markup language. Language is used to write the configuration file, it is very simple and powerful.
YAML syntax and other similar language, can also be expressed hash table, such as scalar data structure.
Structure to show through space; configuration items in sequence through - to represent; Map where the keys with: to separate; YAML's extension yaml

The basic syntax rules:

1.大小写敏感
2.使用缩进表示层级关系
3.缩进时不允许使用Tab键,只允许使用空格。
4.缩进的空格数目不重要,只要相同层级的元素左侧对齐即可

YAML支持的数据结构:
1.对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
 例如:name:Example Developer
        键     值
2.数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
 例如:-Apple
       -Orange
3.纯量:单个的、不可再分的值
 例如:number:12.30
       sure:true

yaml example:

name:zhangsan
age:20
name:lisi
age:22
people:
-name:zhangsan
      age:20
      -name:lisi
      age:22

Detailed operation playbook +

Ansible script --- playbook

Template ansible will play multiple organizations running a playbook calls by task.
playbooks itself consists of the following components
(1) Tasks: tasks that call for a module to complete the operation; the equivalent of the transaction, will not perform a successful rollback
(2) Variables: variables, host list, screenplay, which -e command statement variable three scenarios
(3) templates: templates
(4) Handlers: a processor, when a condition is satisfied, the trigger operation performed;
(. 5) the roles: role.

Here is an example of a playbook

- hosts: webserver              //定义的主机组,即应用的主机
  vars:                        //定义变量
    http_port: 80
    max_clients: 200
  user: root
  tasks:                               //执行的任务
  - name: ensure apache is at the latest version #友好提示,自己定义
    yum: pkg=httpd state=latest #检查httpd包是不是最新版本
  - name: write the apache config file
    template: src=/srv/httpd.j2 dest=/etc/httpd.conf
    notify: #调用触发下面具体的操作
    - restart apache
  - name: ensure apache is running
    service: name=httpd state=started
  handlers:                       //处理器
    - name: restart apache #调这个操作
      service: name=httpd state=restarted

执行一个playbook
ansible-playbook [yaml文件名]
例如:ansible-playbook ping.yml
参数:-k(–ask-pass) 用来交互输入ssh密码
      -K(-ask-become-pass) 用来交互输入sudo密码
      -u   指定用户
补充命令:
ansible-playbook nginx.yml --syntax-check    #检查yaml文件的语法是否正确
ansible-playbook nginx.yml --list-task       #检查tasks任务
ansible-playbook nginx.yml --list-hosts      #检查生效的主机
ansible-playbook nginx.yml --start-at-task='Copy Nginx.conf'     #指定从某个task开始运行

lab environment

Master
host 01 192.168.136.168
host 02 192.168.136.185
host 03 192.168.136.253

ansibel deployment environment, join the list of hosts

[webserver]
192.168.136.168
[mysql]
192.168.136.185
[ftpserver]
192.168.136.253
#关闭所有主机防火墙
[root@localhost ~]# systemctl stop firewalld.service 
[root@localhost ~]# setenforce 0
#免交户
ssh-keygen -t rsa #生成密钥,回车,输入密码
#公钥推给对方主机
ssh-copy-id [email protected]
ssh-copy-id [email protected]    //配置密钥对验证
ssh-copy-id [email protected]
root@localhost ~]# ssh-agent bash #ssh代理
[root@localhost ~]# ssh-add #添加密码

hosts and users Introduction

[root@localhost ~]# vim a.yml

- hosts: webserver               #指定主机组,可以是一个或多个组。
  remote_user: root                #指定远程主机执行的用户名

[root@localhost ~]# ansible-playbook a.yml 

PLAY [webserver] ***************************************************************

TASK [Gathering Facts] *********************************************************
ok: [192.168.136.168]

PLAY RECAP *********************************************************************
192.168.136.168            : ok=1    changed=0    unreachable=0    failed=0   

Each task can also define the remote user to perform:

---
- hosts: mysql
  remote_user: root             
  tasks:
    - name: test connect
      ping:
      remote_user: root          #指定远程主机执行tasks的运行用户为mysql
执行playbook时:ansible-playbook ping.yml
LAY [webserver] *******************************************************************

TASK [Gathering Facts] *************************************************************
ok: [192.168.136.168]

TASK [test connect] ****************************************************************
ok: [192.168.136.168]

PLAY RECAP *************************************************************************
192.168.136.168            : ok=2    changed=0    unreachable=0    failed=0   

Specifies the remote host sudo switch users:

---
- hosts: mysql
  remote_user: root            
  become: yes                  #2.6版本以后的参数,之前是sudo,意思为切换用户运行
  become_user: mysql          #指定sudo用户为mysql
执行playbook时:ansible-playbook ping.yml -K

tasks列表和action
1.Play的主体部分是task列表,task列表中的各任务按次序逐个在hosts中指定的主机上执行,即在所有主机上完成第一个任务后再开始第二个任务。
在运行playbook时(从上到下执行),如果一个host执行task失败,整个tasks都会回滚,请修正playbook 中的错误,然后重新执行即可。
Task的目的是使用指定的参数执行模块,而在模块参数中可以使用变量,模块执行时幂等的,这意味着多次执行是安全的,因为其结果一致。
2.每一个task必须有一个名称name,这样在运行playbook时,从其输出的任务执行信息中可以很好的辨别出是属于哪一个task的。如果没有定义name,‘action’的值将会用作输出信息中标记特定的task。
3.定义一个task,常见的格式:”module: options” 例如:yum: name=httpd
4.ansible的自带模块中,command模块和shell模块无需使用key=value格式

小示例:
---
- hosts: webserver
  remote_user: root
  tasks:
   - name: disable selinux
     command: '/sbin/setenforce 0'
   - name: install httpd
     yum: name=httpd  

 #这边还可以关闭防火墙,加上一段:
   - name: disable firewalld
     service: name=firewalld state=stopped

   - name: start httpd
     service: name=httpd state=started
[root@localhost ~]# ansible-playbook a.yml 

PLAY [webserver] *******************************************************************

TASK [Gathering Facts] *************************************************************
ok: [192.168.136.168]

TASK [disable selinux] *************************************************************
changed: [192.168.136.168]

TASK [install httpd] ***************************************************************
changed: [192.168.136.168]

TASK [start httpd] *****************************************************************
changed: [192.168.136.168]

PLAY RECAP *************************************************************************
192.168.136.168            : ok=4    changed=3    unreachable=0    failed=0   

play中只要执行命令的返回值不为0,就会报错,tasks停止

修改如下:加入执行失败,我们可以设置一个参数跳过一个问题,继续下面的操作ignore_errors: True 
---
- hosts: webserver
  remote_user: root
  tasks:
   - name: disable selinux
     command: '/sbin/setenforce 0'
     ignore_errors: True             #忽略错误,强制返回成功
   - name: make sure apache is running
     service: name=httpd state=started

The following is another example and to be read

---
- hosts: webserver
  remote_user: root
  tasks:
   - name: create nginx group
     group: name=nginx system=yes gid=208
   - name: create nginx user
     user: name=nginx uid=208 group=nginx system=yes
- hosts: mysql
  remote_user: root
  tasks:
   - name: copy file to mysql
     copy: src=/etc/inittab dest=/opt/inittab.back

Handlers Introduction

Handlers也是一些task的列表,和一般的task并没有什么区别。
是由通知者进行的notify,如果没有被notify,则Handlers不会执行,假如被notify了,则Handlers被执行
不管有多少个通知者进行了notify,等到play中的所有task执行完成之后,handlers也只会被执行一次

示例
---
- hosts: webserver
  remote_user: root
  tasks:
   - name: install httpd package
     yum: name=httpd state=latest
   - name: install configuration file for httpd
     copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf
     notify:
      -restart httpd
   - name: start httpd service
     service: enabled=true name=httpd state=started
  handlers:
   - name: restart httpd
     service: name=httpd state=restarted

也可以引入变量
    ---
- hosts: webserver
  remote_user: root
  vars:
  - package: httpd
  - service: httpd
  tasks:
   - name: install httpd package
     yum: name={{package}} state=latest
   - name: install configuration file for httpd
     copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf
     notify:
      -restart httpd
   - name: start httpd service
     service: enabled=true name={{service}} state=started
  handlers:
   - name: restart httpd
     service: name={{service}} state=restarted

#写一个创建用户的引入变量的小事列
[root@localhost ~]# vim b.yml 
- hosts: ftpserver
  remote_user: root
  vars:
   - username: lisi
  tasks:
   - name: create user
     user: name={{username}}
[root@localhost ~]# ansible-playbook b.yml --syntax-check

playbook: b.yml
[root@localhost ~]# ansible-playbook b.yml 

PLAY [ftpserver] *******************************************************************

TASK [Gathering Facts] *************************************************************
ok: [192.168.136.253]

TASK [create user] *****************************************************************
ok: [192.168.136.253]

PLAY RECAP *************************************************************************
192.168.136.253            : ok=2    changed=0    unreachable=0    failed=0   
ansible-playbook b.yml -e username=lisi
主机清单也可以加入要使用的用户

playbook使用变量的方法:
1.通过ansible命令传递
例如:编辑如下yaml
vi a.yml
---
- hosts: mysql
  remote_user: root
  vars:
  - user:
  tasks:
  - name: add new user
    user: name={{user}}
然后执行命令: ansible-playbook a.yml -e "user=testvar"
可以执行命令查看:ansible mysql -m command -a 'tail /etc/passwd'

2.直接在yaml中定义变量---如上handlers示例
3.直接引用一些变量
如:引用ansible的固定变量
#content指定文件内容到路径下
vi test.yml
---
- hosts: mysql
  remote_user: root
  tasks:
   - name: copy file
     copy: content="{{ansible_all_ipv4_addresses}}," dest=/opt/vars.txt
执行命令:ansible-playbook test.yml
去253上查看vars.txt文件内容
[root@localhost opt]# cat add.txt 
["192.168.122.1", "192.168.136.253"]

再如:引用主机变量
vi /etc/ansible/hosts
在mysql组的主机后面添加如下
[mysql]
192.168.80.183 testvar="80.183"          #定义testvar变量的值为80.183
vi test.yml      #添加{{testvar}}主机变量
---
- hosts: mysql
  remote_user: root
  tasks:
   - name: copy file
     copy: content="{{ansible_all_ipv4_addresses}},{{testvar}}" dest=/opt/vars.txt
执行命令:ansible-playbook test.yml
去183上查看vars.txt文件内容

-------- -------- test conditions

如果需要根据变量、facts(setup)或此前任务的执行结果来作为某task执行与否的前提时要用到条件测试,在Playbook中条件测试使用when子句。
在task后添加when子句即可使用条件测试:when子句支持jinjia2表达式或语法,例如:
vi when.yml
---
- hosts: mysql
  remote_user: root
  tasks:
    - name: "shutdown CentOS"
      command: /sbin/shutdown -h now #-r重启
      when: ansible_distribution == "CentOS"
PLAY [mysql] ***********************************************************************

TASK [Gathering Facts] *************************************************************
ok: [192.168.136.185]

TASK [shutdown CentOS] *************************************************************
fatal: [192.168.136.185]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Shared connection to 192.168.136.185 closed.\r\n", "unreachable": true}
    to retry, use: --limit @/root/b.retry

PLAY RECAP *************************************************************************
192.168.136.185            : ok=1    changed=0    unreachable=1    failed=0   

Multi-conditional

vi when.yml
---
- hosts: mysql
  remote_user: root
  tasks:
    - name: "shut down CentOS 6 systems"
      command: /sbin/shutdown -r now
      when:
        - ansible_distribution == "CentOS"
        - ansible_distribution_major_version == "6"

Group condition determination (and, and, or)

vi when.yml
---
- hosts: mysql
  remote_user: root
  tasks:
    - name: "shut down CentOS 6 and Debian 7 systems"
      command: /sbin/shutdown -t now
      when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == "6") or
            (ansible_distribution == "Debian" and ansible_distribution_major_version == "7")

Custom variables conditional test

#满足为true就创建文件,满足为False旧删除
vi when.yml
---
- hosts: all
  vars:
    exist: "True"
  tasks:
  - name: creaet file
    command:  touch /tmp/test.txt
    when: exist | match("True") #match:匹配

  - name: delete file
    command:  rm -rf /tmp/test.txt
    when: exist | match("False")    

TASK [Gathering Facts] *************************************************************
ok: [192.168.136.253]
ok: [192.168.136.168]
ok: [192.168.136.185]

TASK [creaet file] *****************************************************************
 [WARNING]: Consider using file module with state=touch rather than running touch

changed: [192.168.136.185]
changed: [192.168.136.253]
changed: [192.168.136.168]

TASK [delete file] *****************************************************************
skipping: [192.168.136.253]
skipping: [192.168.136.168]
skipping: [192.168.136.185]

PLAY RECAP *************************************************************************
192.168.136.168            : ok=2    changed=1    unreachable=0    failed=0   
192.168.136.185            : ok=2    changed=1    unreachable=0    failed=0   
192.168.136.253            : ok=2    changed=1    unreachable=0    failed=0   

---------- ------------- iteration is equivalent to ergodic #

当有需要重复性执行的任务时,可以使用迭代机制。其使用格式为将需要迭代的内容定义为item变量引用,并通过with_items语句指明迭代的元素列表即可。例如:
---
- hosts: webserver
  remote_user: root
  tasks:
    - name: "Install Packages"
      yum: name={{ item }} state=latest #item:去下面的集合遍历
      with_items: #一步一步安装
        - httpd
        - mysql-server
        - php   
也可以自己定义(还可以设置数组,看做一整行,后面根据调某一个属性变量名,就调出来了)
---
- hosts: webserver
  remote_user: root
  tasks:
    - name: "Add users"
      user: name={{ item.name }} state=present groups={{ item.groups }}
      with_items:
        - { name:'test1', groups:'wheel'}
        - { name:'test2', groups:'root'}

#小事列
- hosts: all
  vars:
    exist: "False"
  tasks:
  - name: create users
    user: name={{item}}
    with_items:
     - t01
     - t02
     - t03

ok: [192.168.136.253]
ok: [192.168.136.168]
ok: [192.168.136.185]

TASK [create users] ****************************************************************
changed: [192.168.136.253] => (item=t01)
changed: [192.168.136.168] => (item=t01)
changed: [192.168.136.185] => (item=t01)
changed: [192.168.136.253] => (item=t02)
changed: [192.168.136.168] => (item=t02)
changed: [192.168.136.185] => (item=t02)
changed: [192.168.136.253] => (item=t03)
changed: [192.168.136.168] => (item=t03)
changed: [192.168.136.185] => (item=t03)

PLAY RECAP *************************************************************************
192.168.136.168            : ok=2    changed=1    unreachable=0    failed=0   
192.168.136.185            : ok=2    changed=1    unreachable=0    failed=0   
192.168.136.253            : ok=2    changed=1    unreachable=0    failed=0   
#去主机查看有没有这些用户
t01:x:1001:1001::/home/t01:/bin/bash
t02:x:1002:1002::/home/t02:/bin/bash
t03:x:1003:1003::/home/t03:/bin/bash

Templates module

#把168的httpd配置文件复制过来
[root@localhost ~]# vim /etc/ansible/hosts 
[root@localhost ~]# scp [email protected]:/etc/httpd/conf/httpd.conf ./
httpd.conf                                        100%   11KB   4.0MB/s   00:00  
#修改httpd配置文件
Listen {{http_port}} #变量
ServerName {{server_name}}
MaxClients {{access_num}}

mv httpd.conf httpd.conf.j2

#赋值
[root@localhost ~]# vim /etc/ansible/hosts 
[webserver]
192.168.136.168 http_port=192.168.136.168:80  server_name="www.yun.com:80" access_num=200 #指定端口,域名,访问次数200

[root@localhost ~]# vim apache.yml
- hosts: webserver
  remote_user: root
  vars:
   - package: httpd
   - service: httpd
  tasks:
    - name: check latest
      yum: name-{{package}} state=latest
    - name: configure apache
      template: src=/etc/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf #源在本地的控制端,指定对方的被控端
      notify:
        - restart httpd
    - name: start httpd
      service: name={{server}} enabled=true state=started
  handlers:
    - name: restart httpd
      service: name={{server}} state=restarted

[root@localhost ~]# ansible-playbook apache.yml --syntax-check

playbook: apache.yml
[root@localhost ~]# ansible-playbook apache.yml 

PLAY [webserver] *******************************************************************

TASK [Gathering Facts] *************************************************************
ok: [192.168.136.168]

TASK [check latest] ****************************************************************
ok: [192.168.136.168]

TASK [configure apache] ************************************************************
changed: [192.168.136.168]

TASK [start httpd] *****************************************************************
changed: [192.168.136.168]

RUNNING HANDLER [restart httpd] ****************************************************
changed: [192.168.136.168]

PLAY RECAP *************************************************************************
192.168.136.168            : ok=5    changed=3    unreachable=0    failed=0   
#有了模板就根据这个模板就统一修改其他被控端的所有主机的配置文件

去两台远程主机上查看
grep -i listen /etc/httpd/conf/httpd.conf
grep -i maxClient /etc/httpd/conf/httpd.conf
grep -i servername /etc/httpd/conf/httpd.conf

tags module

在一个playbook中,我们一般会定义很多个task,如果我们只想执行其中的某一个task或多个task时就可以使用tags标签功能了,格式如下:
vi hosts.yml
---
- hosts: webserver
  remote_user: root
  tasks:
    - name: Copy hosts file
      copy: src=/etc/hosts dest=/etc/hosts
      tags:
      - only #打上标记我只执行我标记的操作
    - name: touch file
      file: path=/opt/hosts state=touch
执行命令:ansible-playbook hosts.yml --tags="only"
PLAY [webserver] *******************************************************************

TASK [Gathering Facts] *************************************************************
ok: [192.168.136.168]

TASK [Copy hosts file] *************************************************************
ok: [192.168.136.168]

PLAY RECAP *************************************************************************
192.168.136.168            : ok=2    changed=0    unreachable=0    failed=0   

ansible-playbook hosts.yml

事实上,不光可以为单个或多个task指定同一个tags。playbook还提供了一个特殊的tags为always。作用就是当使用always当tags的task时,无论执行哪一个tags时,定义有always的tags都会执行。
vi hosts.yml
---
- hosts: webserver
  remote_user: root
  tasks:
    - name: Copy hosts file
      copy: src=/etc/hosts dest=/etc/hosts
      tags:
      - only
    - name: touch file
      file: path=/opt/hosts state=touch
      tags:
      - always
执行命令:ansible-playbook hosts.yml --tags="only"
分别去两台被管理服务器上去查看文件创建情况

Guess you like

Origin blog.51cto.com/14469918/2469942