Top

NSD ARCHITECTURE DAY02

  1. 练习1:playbook练习
  2. 案例2:变量练习
  3. 案例3:handlers练习
  4. 案例4:编写playbook

1 练习1:playbook练习

1.1 问题

本案例要求:

1.2 步骤

实现此案例需要按照如下步骤进行。

步骤一:playbook的ping脚本检测

[root@ansible ansible]# vim ping.yml
---
- hosts: all
  remote_user: root
  tasks:
     - ping:
[root@ansible ansible]# ansible-playbook ping.yml  //输出结果

PLAY [all] *******************************************************************

TASK [Gathering Facts] *******************************************************
ok: [web1]
ok: [web2]
ok: [cache]
ok: [db1]
ok: [db2]

TASK [ping] ******************************************************************
ok: [db1]
ok: [web2]
ok: [cache]
ok: [web1]
ok: [db2]

PLAY RECAP *******************************************************************
cache                      : ok=2    changed=0    unreachable=0    failed=0   
db1                        : ok=2    changed=0    unreachable=0    failed=0   
db2                        : ok=2    changed=0    unreachable=0    failed=0   
web1                       : ok=2    changed=0    unreachable=0    failed=0   
web2                       : ok=2    changed=0    unreachable=0    failed=0

注意:如果检测的时候出错,会在当前的目录生成一个新的文件(以.retry结尾),可以去这个文件里面看是哪个主机的错

步骤二:用playbook安装Apache,修改端口,配置ServerName,修改主页,设置开机自启

[root@ansible ansible]# vim http.yml

---
- hosts: cache
  remote_user: root
  tasks:
    - name: install one specific version of Apache
      yum:
        name: httpd		//安装Apache
        state: installed
    - lineinfile:
        path: /etc/httpd/conf/httpd.conf
        regexp: '^Listen '
        line: 'Listen 8080'		//修改端口为8080
    - service:
        name: httpd
        enabled: yes		//开机自启
        state: restarted
    - copy:
        src: /root/index.html		//修改主页,可以自己写个页面
        dest: /var/www/html/index.html
[root@ansible ansible]# ansible-playbook http.yml
[root@ansible ansible]# curl 192.168.1.45:8080
hello world 
[root@ansible ansible]# ssh cache
Last login: Fri Sep  7 09:32:05 2018 from 192.168.1.40
[root@cache ~]# apachectl -t
Syntax OK

2 案例2:变量练习

2.1 问题

本案例要求熟悉playbook进阶:

2.2 步骤

实现此案例需要按照如下步骤进行。

步骤一:使用user模块添加用户,并修改密码

[root@ansible ansible]# vim user.yml
---
- hosts: cache
  remote_user: root
  vars:
    username: xiaoming
  tasks:
    - name: create user "{{username}}"
      user: group=wheel uid=1000 name={{username}}
    - shell: echo 123456 | passwd --stdin xiaoming
    - shell: chage -d 0 {{username}}
[root@ansible ansible]# ansible-playbook user.yml   //执行结果

PLAY [cache] ******************************************************************

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

TASK [create user " xiaoming "] ***********************************************
changed: [cache]

TASK [command] ****************************************************************
changed: [cache]

TASK [command] ****************************************************************
changed: [cache]

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


步骤二:变量过滤器,创建一个用户,设置密码

[root@ansible ansible]# vim user1.yml
---
- hosts: cache
  remote_user: root
  tasks:
   - user:
       name: lisi
       group: root
       password: "{{'123456' | password_hash('sha512')}}"
   - shell: chage -d 0 lisi
[root@ansible ansible]# ansible-playbook user1.yml 

PLAY [cache] ******************************************************************

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

TASK [user] *******************************************************************
changed: [cache] 

TASK [command] ****************************************************************
changed: [cache]

PLAY RECAP ********************************************************************
cache                      : ok=3    changed=2    unreachable=0    failed=0   

步骤三:定义一个变量创建用户

[root@ansible ansible]# vim user2.yml

---
- hosts: cache
  remote_user: root
  vars:
    user: zhangs
  tasks:
    - user:
        name: "{{user}}"
        group: root
        password: "{{'123456' | password_hash('sha512')}}"
    - shell: chage -d 0 "{{user}}"
[root@ansible ansible]# ansible-playbook user2.yml
PLAY [cache] ******************************************************************

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

TASK [user] *******************************************************************
changed: [cache]

TASK [command] ****************************************************************
changed: [cache]

PLAY RECAP ********************************************************************
cache                      : ok=3    changed=2    unreachable=0    failed=0   

3 案例3:handlers练习

3.1 问题

本案例要求:

3.2 步骤

实现此案例需要按照如下步骤进行。

步骤一:error

playbook从上往下顺序执行,若报错,后面的命令不会在执行,若想解决可以使用ignoring_errors:True(使用这个,会有报错信息,告诉你错误忽略,继续执行下面的命令)

[root@ansible ansible]# vim error.yml
---
- hosts: web
  remote_user: root
  tasks:
    - shell: mkdir /tmp/cache
    - name: ReStart service httpd
      service:
        name: httpd
        state: restarted
    - name: run  some command
      shell: /usr/bin/somecommand
      ignore_errors: True
[root@ansible ansible]# ansible-playbook error.yml 

PLAY [web] ***********************************************************************************

TASK [Gathering Facts] ***********************************************************************************
ok: [web2]
ok: [web1]

TASK [command] ***********************************************************************************
 [WARNING]: Consider using file module with state=directory rather than running mkdir

fatal: [web1]: FAILED! => {"changed": true, "cmd": "mkdir /tmp/cache", "delta": "0:00:00.004799", "end": "2019-04-11 14:57:11.582036", "msg": "non-zero return code", "rc": 1, "start": "2019-04-11 14:57:11.577237", "stderr": "mkdir: \u65e0\u6cd5\u521b\u5efa\u76ee\u5f55\"/tmp/cache\": \u6587\u4ef6\u5df2\u5b58\u5728", "stderr_lines": ["mkdir: \u65e0\u6cd5\u521b\u5efa\u76ee\u5f55\"/tmp/cache\": \u6587\u4ef6\u5df2\u5b58\u5728"], "stdout": "", "stdout_lines": []}
changed: [web2]

TASK [ReStart service httpd] *****************************************************************************
fatal: [web2]: FAILED! => {"changed": false, "msg": "Could not find the requested service httpd: host"}
	to retry, use: --limit @/etc/ansible/error.retry

PLAY RECAP ***********************************************************************************
web1                       : ok=1    changed=0    unreachable=0    failed=1   
web2                       : ok=2    changed=1    unreachable=0    failed=1   

[root@ansible ansible]#

步骤二:tags给指定的任务定义一个调用标识

1)tags 样例

[root@ansible ansible]# vim adhttp.yml
---
- hosts: cache
  remote_user: root
  tasks:
    - copy:
        src: /root/httpd.conf
        dest:  /etc/httpd/conf/httpd.conf
        owner: apache
        group: apache
        mode: 0644
      tags: syncconf

2)调用方式

[root@ansible ansible]# ansible-playbook tags.yml  -t syncconf

PLAY [cache] ***********************************************************************************

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

TASK [copy] ***********************************************************************************
changed: [cache]

PLAY RECAP ***********************************************************************************
cache                      : ok=2    changed=1    unreachable=0    failed=0


步骤三: handlers

关注的资源发生变化时采取的操作

1) 使用handlers来配置文件,重新载入配置文件让服务生效

[root@ansible ansible]# vim handers.yml    
---
- hosts: cache
  remote_user: root
  tasks:
    - copy:
        src: /root/httpd.conf
        dest:  /etc/httpd/conf/httpd.conf
        owner: apache
        group: apache
        mode: 0644
      tags: syncconf
      notify:
        - restart httpd
  handlers:
    - name: restart httpd
      service:
          name: httpd
          state: restarted




[root@ansible ansible]# ansible-playbook handers.yml 

PLAY [cache] ***********************************************************************************

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

TASK [copy] ***********************************************************************************
ok: [cache]

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

4 案例4:编写playbook

4.1 问题

本案例要求:

4.2 步骤

实现此案例需要按照如下步骤进行。

步骤一:把系统负载太高的Apache服务停止

1)当系统负载超过0.7时,则关掉httpd

[root@ansible ansible]# vim when.yml
---
- hosts: cache
  remote_user: root
  tasks:
    - shell: uptime | awk '{printf("%.2f\n",$(NF-2))}'
      register: result
    - service:
        name: httpd
        state: stopped
      when: result.stdout|float > 0.7

[root@ansible ansible]# ansible-playbook when.yml 

PLAY [cache] ***********************************************************************************

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

TASK [command] ***********************************************************************************
changed: [cache]

TASK [service] ***********************************************************************************
changed: [cache]

PLAY RECAP ***********************************************************************************
cache                      : ok=3    changed=2    unreachable=0    failed=0   

步骤三:with_items标准循环

1)with_item创建多用户

[root@ansible ansible]# vim adduser.yml
---
- hosts: web2
  remote_user: root
  tasks:
    - name: add users
      user: group=wheel password={{'123456' | password_hash('sha512')}} name={{item}}
      with_items: ["nb", "dd", "plj", "lx"]

[root@ansible ansible]# ansible-playbook adduser.yml 

PLAY [web2] ***********************************************************************************

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

TASK [add users] ***********************************************************************************
changed: [web2] => (item=nb)
changed: [web2] => (item=dd)
changed: [web2] => (item=plj)
changed: [web2] => (item=lx)

PLAY RECAP ***********************************************************************************
web2                       : ok=2    changed=1    unreachable=0    failed=0

2)为不同用户定义不同组

[root@ansible ansible]# vim adduser1.yml
---
- hosts: web2
  remote_user: root
  tasks:
    - name: add users
      user: group={{item.group}} password={{'123456' | password_hash('sha512')}} name={{item.name}}
      with_items:
        - {name: 'nb',  group: 'root'}
        - {name: 'dd',  group: 'root'}
        - {name: 'plj', group: 'wheel'}
        - {name: 'lx',  group: 'wheel'} 

[root@ansible ansible]# ansible-playbook adduser1.yml 
PLAY [web2] ***********************************************************************************

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

TASK [add users] ***********************************************************************************
changed: [web2] => (item={u'group': u'root', u'name': u'nb'})
changed: [web2] => (item={u'group': u'root', u'name': u'dd'})
changed: [web2] => (item={u'group': u'wheel', u'name': u'plj'})
changed: [web2] => (item={u'group': u'wheel', u'name': u'lx'})

PLAY RECAP ***********************************************************************************
web2                       : ok=2    changed=1    unreachable=0    failed=0  

3)include and roles

在编写playbook的时候随着项目越来越大,playbook越来越复杂。可以把一些play、task 或 handler放到其他文件中,通过包含进来是一个不错的选择

roles像是加强版的include,它可以引入一个项目的文件和目录

一般所需的目录层级有

vars:变量层

tasks:任务层

handlers:触发条件

files:文件

template:模板

default:默认,优先级最低

...
tasks:
   - include: tasks/setup.yml
   - include: tasks/users.yml user=plj 
//users.yml 中可以通过{{ user }}来使用这些变量
handlers:
  - include: handlers/handlers.yml

步骤五:debug检测


[root@ansible ansible]# ansible-playbook  --syntax-check  http.yml  //检测语法

playbook: http.yml
[root@ansible ansible]# ansible-playbook  -C  http.yml   //测试运行

[root@ansible ansible]# ansible-playbook   http.yml  --list-tasks  
//显示要执行的工作

playbook: http.yml

  play #1 (cache): cache	TAGS: []
    tasks:
      install one specific version of Apache	TAGS: []
      lineinfile	TAGS: []
      replace	TAGS: []
      service	TAGS: []
      copy	TAGS: []


[root@ansible ansible]# vim debug.yml
---
- hosts: cache
  remote_user: root
  tasks:
    - shell: uptime |awk '{printf("%f\n",$(NF-2))}'
      register: result
    - service: 
         name: httpd 
         state: stopped
      when: result.stdout|float > 0.7
    - name: Show debug info
      debug: var=result

[root@ansible ansible]# ansible-playbook debug.yml 		//运行

PLAY [cache] ***********************************************************************************

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

TASK [command] ***********************************************************************************
changed: [cache]

TASK [command] ***********************************************************************************
skipping: [cache]

TASK [Show debug info] ***********************************************************************************
ok: [cache] => {
    "result": {
        "changed": true, 
        "cmd": "uptime |awk '{printf(\"%f\\n\",$(NF-2))}'", 
        "delta": "0:00:00.005905", 
        "end": "2018-09-07 12:57:51.371013", 
        "failed": false, 
        "rc": 0, 
        "start": "2018-09-07 12:57:51.365108", 
        "stderr": "", 
        "stderr_lines": [], 
        "stdout": "0.000000", 
        "stdout_lines": [
            "0.000000"
        ]
    }
}

PLAY RECAP ***********************************************************************************
cache                      : ok=3    changed=1    unreachable=0    failed=0