ansible-playbook(变量2)及简单检查语法命令

此文包含模块
  • error
  • tags
  • handlers
  • when
  • register
  • debug
  • with_items
  • include and roles
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

模块 error

  • ansible-playbook对错误的处理
    –默认情况判断$? .如果值不为0就停止执行
    –但某些情况我们需要忽略错误继续执行
    –例如 创建缓存目录,然后重启apache
---
- hosts: web1
  tasks: 
    - shell: mkdir /tmp/cache
    - name: reload httpd
      service:
        name: httpd
        state: restarted
  • 错误处理方法
    –ignore_errors:对错误的处理方式
    –Ture 表示忽略错误继续执行
    – False 表示遇到错误就停止执行
    – 默认 False
    – 处理方式:
       - name: run some command
         shell: /usr/bin/somecommand
         ignore_error: True

模块 tags

  • tags :给指定的任务定义一个调用标识
  • 使用格式:
    – name: NAME
    – module: arguments
    –tags:TAG_ID
  • playbook调用方式
    – -t TAGS, --tags= TAGS
  • 修改 httpd 配置的yml
    tasks:
      - copy:
          src: httpd.conf
          dest: /etc/httpd/conf/httpd.conf
      - template:
          src: index.html
          dest: /var/www/html/index.html
          owner: apache
          group: apache
          mode: 0644
    
    • 设置 tags 标记
    - name: modify index.html
        copy:
          src: index.html
          dest: /var/www/html/index.html
          owner: apache
          group: apache
          mode: 0644
        tags: update_index
    
  • 调用标记
    ansible-playbook conf.yml -t update_index

模块 handlers

  • 当关注的资源发生变化时采取的操作
  • notify这个action可用于在每个play的最后被触发,这样可以避免有多次改变发生时每次都执行指定的操作,取而代之仅在所有的变化发生完成后一次性执行指定操作
  • 在 notify中列出的操作称为handler ,即notify调用handler中定义的操作
  • 前面安装了Apache,修改httpd的配置文件,重新载入配置文件让服务生效
  • 使用handlers来实现
   handlers:
     - name: reload httpd
       service: 
         name: httpd
         state: restarted
  • 结合之前的例子,使用handlers
     tasks:
       - name: modify httpd.conf
         copy:
           src: httpd.conf
           dest: /etc/httpd/conf/httpd.conf
         tags: update_conf
         notify: reload httpd
      handlers:
        - name: reload httpd
          service:
            name: httpd
            state: restarted

!!!注意事项:

– notify 调用的是handler段的name定义的串,必须一致,否则达不到触发的效果
– 多个task触发同一个notify的时候,同一个服务只会触发一次
– notify可以触发多个条件,在生产环境中往往涉及到某一个配置文件的改变要重启若干服务的场景,handler用到这里非常适合
– 结合vars可以写出非常普通的服务管理脚本

error/tags/handlers模块的练习

  • 安装Apache软件 配置文件
  • 重新载入配置文件让服务生效
  • 使用handlers来实现
步骤一:error

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

[root@manger 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 

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

[root@manger 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
[root@manger ansible]# ansible-playbook tags.yml  -t syncconf
[root@manger 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@manger ansible]# ansible-playbook handers.yml 
模块 when
  • 有些适合需要在满足特定的条件后再触发某一项操作,或在特定的条件下终止某个行为,这个适合需要进行条件判断,when正是解决这个问题的最佳选择,远程中的系统变量facts作为when的条件,可以通过setup模块查看
    – when 的样例:
tashs:
  - name: somecommand
    command: somecommand
    when: expr
  • 一个使用when的例子
---
- name: Install VIM
  hosts: all
  tasks:
    - name: Install VIM via yum
      yum: name=vim-enhanced state=installed
      when: ansible_os_family == "RedHat"
	- name: Install VIM via apt
	  apt: name=vim  state=installed
	  when: ansible_os_family == "Debian" 
模块 register
  • register
    – 有时候我们还需要更复杂的例子,如判断前一个命令的执行结果去处理后面的操作,这时候就需要register模块来保存前一个命令的返回状态,在后面进行调用
    - command: test command
      register: result
    - command: run command
      when: result
    
  • 变量注册进阶
    – 针对运行命令结果的返回值做判定
    – 当系统负载超过一定值的适合做特殊处理
--- 
- hosts: web
  remote_user: root
  tasks:
    - shell: uptime | awk '{
    
    printf("%.2f",$(NF-2))}'
      register: result
    - service:
        name: httpd
        state: stopped
      when: result.stdout | float >0.7  	

调试

模块 debug
  • debug 模块可以在运行时,输出更为详细的信息,帮助我们排错
---
- hosts: web  
  remote_user: root
  tasks: 
    - shell: uptime | awk '{
    
    printf("%.2f",$(NF-2))}'
      register: result
    - service:
        name: httpd
        state: stopped
      when: result.stdout| float >0.7
    - debug: var=result
with_items
  • with_items是playbook标准循环,可以用于迭代一个列表或字典,通过{ {item}} 获取每次迭代的值
    – 例如创建多个用户
---
- hosts: web1
  remote_user: root
  tasks:
    - name: add users
      user: group=wheel password={
    
    {
    
    '123456' |password_hash('sha512')}}  name={
    
    {
    
    item}}
      with_items:["a1","a2","a3","a4"]
  • with_items进阶
    – 为不同用户定义不同组
---
- hosts: web2
  remote_user:root
  tasks:
    - name: add users
      user:group={
    
    {
    
    item.group}} password={
    
    {
    
    '123456 '| password_hash('sha512')}} name={
    
    {
    
    item.name}}
      with_items:
        - {
    
    name: 'a1',group: 'root'}
        - {
    
    name: 'a2',group: 'root'}
        - {
    
    name: 'a3',group: 'wheel'}
        - {
    
    name: 'a4',group: 'wheel'}
模块 include and roles
  • 在编写playbook的时候随着项目越来越大,playbook越来越复杂,修改也很麻烦.这时可以把一些play、task或handler放到其他文件中,通过include指令包含进来是一个不错的选择
   tasks:
      - include: tasks/setup.yaml
      - include: tasks/user.yml user=a1 # users.yml 中可以通过{
    
    { user }} 来使用这个变量
     
    handlers:
       - include: handler/handlers.yml
  • roles 像加强版的include,它可以引入一个项目的文件和目录

  • 一般所需的目录层级有
    – vars: 变量层
    –tasks: 任务层
    –handlers: 触发条件
    –files: 文件
    – template: 模板
    – default: 默认,优先级最低

  • 假如有一个play包含了一个叫"x" 的role,则

---
- hosts: host_group
  roles:
    - x

– x/tasks/main.yml
– x/vars/main.yml
– x/handlers/main.yml
– x/… …/main.yml
– 都会自动添加进这个play

排错方法(调试)

  • 检测语法
]# ansible-playbook --syntax-check playbook.yaml
  • 测试运行
]#ansible-playbook -C playbook.yaml

–显示受到影响的主机 --list-hosts
–显示工作的task --list-tasks
–显示将要运行的tag --list-tags

练习: 把系统负载太高的Apache服务停止

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

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

  [root@manager 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@manager ansible]# ansible-playbook when.yml 
  • 步骤二:with_items标准循环

1)with_item创建多用户

[root@manager 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: ["a1", "a2", "a3", "a4"]
[root@manager ansible]# ansible-playbook adduser.yml 

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

[root@manager 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: 'a1',  group: 'root'}
        - {
    
    name: 'a2',  group: 'root'}
        - {
    
    name: 'a3', group: 'wheel'}
        - {
    
    name: 'a4',  group: 'wheel'} 
[root@manager ansible]# ansible-playbook adduser1.yml 

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@manager ansible]# ansible-playbook  --syntax-check  http.yml  //检测语法
root@manager ansible]# ansible-playbook   http.yml  --list-tasks  
//显示要执行的工作
[root@manager 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@manager ansible]# ansible-playbook debug.yml         //运行

猜你喜欢

转载自blog.csdn.net/weixin_45942735/article/details/104298786