02: playbook基础 、 playbook进阶

xiaoxiao2025-05-17  42

Top

NSD ARCHITECTURE DAY02

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

1 练习1:playbook练习

1.1 问题

本案例要求:

安装Apache并修改监听端口为8080修改ServerName配置,执行apachectl -t命令不报错设置默认主页hello world启动服务并设开机自启

1.2 步骤

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

步骤一:playbook的ping脚本检测

  [root@ansible ansible]# vim ping.yml---- hosts: allremote_user: roottasks:- 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=0db1 : ok=2 changed=0 unreachable=0 failed=0db2 : ok=2 changed=0 unreachable=0 failed=0web1 : ok=2 changed=0 unreachable=0 failed=0web2 : ok=2 changed=0 unreachable=0 failed=0

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

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

  [root@ansible ansible]# vim http.yml ---- hosts: cacheremote_user: roottasks:- name: install one specific version of Apacheyum:name: httpd        //安装Apachestate: installed- lineinfile:path: /etc/httpd/conf/httpd.confregexp: '^Listen 'line: 'Listen 8080'        //修改端口为8080- replace:path: /etc/httpd/conf/httpd.confregexp: '^#(ServerName).*'        //配置ServerNamereplace: '\1 localhost'- service:name: httpdenabled: yes        //开机自启state: restarted- copy:src: /root/index.html        //修改主页,可以自己写个页面dest: /var/www/html/index.html [root@ansible ansible]# curl 192.168.1.56:8080hello world[root@ansible ansible]# ssh cacheLast login: Fri Sep 7 09:32:05 2018 from 192.168.1.51[root@cache ~]# apachectl -tSyntax OK

2 案例2:变量练习

2.1 问题

本案例要求熟悉playbook进阶:

练习使用user模块添加用户练习使用变量简化task,让play通用性更强练习使用过滤器

2.2 步骤

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

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

  [root@ansible ansible]# vim user.yml---- hosts: cacheremote_user: rootvars:username: xiaomingtasks:- 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: cacheremote_user: roottasks:- user:name: lisigroup: rootpassword: "{{'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: cacheremote_user: rootvars:user: zhangstasks:- user:name: "{{user}}"group: rootpassword: "{{'123456' | password_hash('sha512')}}"- shell: chage -d 0 "{{user}}"[root@ansible ansible]# ansible-playbook user2.ymlPLAY [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 问题

本案例要求:

安装Apache软件配置文件,重新载入配置文件让服务生效使用handlers来实现

3.2 步骤

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

步骤一:error

playbook从上往下顺序执行,若报错,后面的命令不会在执行,若想解决有两种方法:

1)当返回值为假时,显示true: - shell: setenforce 0 || true

  [root@ansible ansible]# vim user5.yml---- hosts: cacheremote_user: rootvars:user: bbtasks:- shell: setenforce 0 || true- user:name: "{{user}}"group: rootpassword: "{{'123456' | password_hash('sha512')}}"- shell: chage -d 0 "{{user}}" [root@ansible ansible]# ansible-playbook user5.yml PLAY [cache] ****************************************************************** TASK [Gathering Facts] ********************************************************ok: [cache] TASK [command] ****************************************************************changed: [cache] TASK [user] *******************************************************************changed: [cache] TASK [command] ****************************************************************changed: [cache] PLAY RECAP ********************************************************************cache : ok=4 changed=3 unreachable=0 failed=0

2、忽略:ignoring_errors: True(推荐使用这个,会有报错信息,告诉你错误忽略,继续执行下面的命令)

  [root@ansible ansible]# vim user6.yml---- hosts: cacheremote_user: rootvars:user: bbtasks:- shell: setenforce 0ignore_errors: True- user:name: "{{user}}"group: rootpassword: "{{'123456' | password_hash('sha512')}}"- shell: chage -d 0 "{{user}}" [root@ansible ansible]# ansible-playbook user6.yml PLAY [cache] ****************************************************************** TASK [Gathering Facts] ********************************************************ok: [cache] TASK [command] ****************************************************************fatal: [cache]: FAILED! => {"changed": true, "cmd": "setenforce 0", "delta": "0:00:00.004198", "end": "2018-09-07 11:08:14.936959", "msg": "non-zero return code", "rc": 1, "start": "2018-09-07 11:08:14.932761", "stderr": "setenforce: SELinux is disabled", "stderr_lines": ["setenforce: SELinux is disabled"], "stdout": "", "stdout_lines": []}...ignoring TASK [user] *******************************************************************changed: [cache] TASK [command] ****************************************************************changed: [cache] PLAY RECAP ********************************************************************cache : ok=4 changed=3 unreachable=0 failed=0

步骤二: handlers

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

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

  [root@ansible ansible]# vim adhttp.yml---- hosts: cacheremote_user: roottasks:- copy:src: /root/httpd.confdest: /etc/httpd/conf/httpd.confowner: rootgroup: rootmode: 0644notify:- restart httpdhandlers:- name: restart httpdservice: name=httpd state=restarted [root@ansible ansible]# ansible-playbook adhttp.yml PLAY [cache] ****************************************************************** TASK [Gathering Facts] ********************************************************ok: [cache] TASK [copy] *******************************************************************ok: [cache] PLAY RECAP ********************************************************************cache : ok=2 changed=0 unreachable=0 failed=0 [root@ansible ansible]# ssh cache apachectl -tSyntax OK[root@ansible ansible]# curl 192.168.1.56:8080hello world

2)使用脚本调用变量更改服务

  [root@ansible ansible]# vim adhttp2.yml---- hosts: cacheremote_user: rootvars:server: httpdtasks:- copy:src: /root/httpd.confdest: /etc/httpd/conf/httpd.confowner: rootgroup: rootmode: 0644notify:- restart "{{server}}"handlers:- name: restart "{{server}}"service: name=httpd state=restarted[root@ansible ansible]# ansible-playbook adhttp2.yml PLAY [cache] ************************************************************************************************************ TASK [Gathering Facts] **************************************************************************************************ok: [cache] TASK [copy] *************************************************************************************************************ok: [cache] PLAY RECAP **************************************************************************************************************cache : ok=2 changed=0 unreachable=0 failed=0 [root@ansible ansible]#

4 案例4:编写playbook

4.1 问题

本案例要求:

把所有监听端口是8080的Apache服务全部停止

4.2 步骤

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

步骤一:把监听端口是8080的Apache服务全部停止

  [root@ansible ansible]# vim ad.yml---- hosts: cacheremote_user: roottasks:- shell: netstat -atunlp | awk '{print $4}'| awk '-F:' '{print $2}'register: result- service:name: httpdstate: stopped[root@ansible ansible]# ansible-playbook ad.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

步骤二:when条件判断

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

  [root@ansible ansible]# vim when.yml---- hosts: cacheremote_user: roottasks:- shell: uptime | awk '{printf("%.2f",$(NF-2))}'register: result- service:name: httpdstate: stoppedwhen: 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)为不同用户定义不同组

  [root@ansible ansible]# vim add.yml ---- hosts: web2remote_user: roottasks:- user:name: "{{item.name}}"group: "{{item.group}}"password: "{{'123456'|password_hash('sha512')}}"with_items:- {name: "aa", group: "users"}- {name: "bb", group: "mail" }- {name: "cc", group: "wheel"}- {name: "dd", group: "root" }[root@ansible ansible]# ansible-playbook add.yml PLAY [web2] ************************************************************************************************************* TASK [Gathering Facts] **************************************************************************************************ok: [web2] TASK [user] *************************************************************************************************************changed: [web2] => (item={u'group': u'users', u'name': u'aa'})changed: [web2] => (item={u'group': u'mail', u'name': u'bb'})changed: [web2] => (item={u'group': u'wheel', u'name': u'cc'})changed: [web2] => (item={u'group': u'root', u'name': u'dd'}) PLAY RECAP **************************************************************************************************************web2 : ok=2 changed=1 unreachable=0 failed=0

2)嵌套循环,循环添加多用户

  [root@ansible ansible]# vim add1.yml---- hosts: web2remote_user: rootvars:un: [a, b, c]id: [1, 2, 3]tasks:- name: add usersshell: echo {{item}}with_nested:- "{{un}}"- "{{id}}" [root@ansible ansible]# ansible-playbook add1.yml PLAY [web2] ************************************************************************************************************* TASK [Gathering Facts] **************************************************************************************************ok: [web2] TASK [add users] ********************************************************************************************************changed: [web2] => (item=[u'a', 1])changed: [web2] => (item=[u'a', 2])changed: [web2] => (item=[u'a', 3])changed: [web2] => (item=[u'b', 1])changed: [web2] => (item=[u'b', 2])changed: [web2] => (item=[u'b', 3])changed: [web2] => (item=[u'c', 1])changed: [web2] => (item=[u'c', 2])changed: [web2] => (item=[u'c', 3]) PLAY RECAP **************************************************************************************************************web2 : ok=2 changed=1 unreachable=0 failed=0

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

1)tags 样例

  [root@ansible ansible]# vim adhttp.yml---- hosts: cacheremote_user: roottasks:- copy:src: /root/httpd.confdest: /etc/httpd/conf/httpd.confowner: rootgroup: rootmode: 0644tags: config_httpdnotify:- restart httpdhandlers:- name: restart httpdservice: name=httpd state=restarted

2)调用方式

  [root@ansible ansible]# ansible-playbook adhttp.yml --tags=config_httpd PLAY [cache] ***************************************************************** TASK [Gathering Facts] *******************************************************ok: [cache] TASK [copy] ******************************************************************ok: [cache] PLAY RECAP *******************************************************************cache : ok=2 changed=0 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: cacheremote_user: roottasks:- shell: uptime |awk '{printf("%f\n",$(NF-2))}'register: result- shell: touch /tmp/isrebootwhen: result.stdout|float > 0.5- name: Show debug infodebug: 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
转载请注明原文地址: https://www.6miu.com/read-5030248.html

最新回复(0)