一 引言

  前段时间自己实现了ansible对接操作系统升级脚本,现将整个项目记录如下,如果项目中存在问题或优化的点,请帮忙指正。本项目运行在RedHat Linux系统。

在我们生产环境中,操作系统的升级由系统升级、服务器重启以及vmtools安装三部分组成。本次项目的目标有两点:

  (1) ansible对接操作系统升级脚本实现自动批量升级服务器系统。

  (2) 系统升级、服务器重启和vmtools安装三部分即可以统一运行又可各部分独立运行。

  存在的难点:在实现中,如何实现服务器重启部分和其余两个部分的衔接。这里需要考虑以下几点:

  (1) 如何判断服务器是否需要重启?

  (2) 如何判断服务器是否重启成功?

  (3) 如何避免服务器重启过程中ansible会话的断开?

  具体的实现过程以及难点解决方法将在后续的项目介绍中展示。

 

二 项目介绍

 

图1 项目中playbook的运行流程

  在项目中我们创建一个单独的ansible角色,角色名为update_os。整个ansible角色分为检测任务、主机升级任务、重启任务、vmtools安装任务。各任务的功能如下:

  • 检测任务: 判断主机是否在线。
  • 主机升级任务: 升级操作系统、记录升级日志、判断升级是否成功。
  • 重启任务: 判断主机是否升级成功、重启服务器、判读主机重启是否成功。
  • vmtools安装任务: 安装vmtools、记录安装日志、判断是否安装成功。

  各个playbook的内容:

  site.yml文件是updata_os角色的入口,使用roles导入update_so角色。

---
- name: update os
  gather_facts: no
  hosts: test
  roles:
      - update_os

  update_os角色的tasks目录中的文件有main.yml、ping.yml、 update.yml、reboot.yml、install_vmtools.yml五个playbook文件。

main.yml文件的内容如下:

---
- name: check if host is online
  include: ping.yml
  tags: always

- name: Start system upgrade
  block:
    - name: decide to proceed
      setup:
      tags: always
    
    - name: include update playbook
      include_tasks:
          file: update.yml
          apply:
             tags: update_os
      tags: always
 
    - name: include reboot playbook
      include_tasks:
         file: reboot.yml
         apply:
            tags: reboot_singal
      tags: always
    - name: include vmtools playbook
      include_tasks: 
          file: install_vmtools.yml
          apply:
             tags:  vmtools
      tags: always
  when:  > 
    ( ping.failed is defined and ping.failed == false ) or  
    ( ping2.failed is defined and ping2.failed == false )

   main.yml文件中实现对其余四个playbook文件的调用。在main.yml文件中先导入ping.yml文件来检测在线的主机,之后只对在线的主机执行block块(Start system upgrade)中的内容。main.yml文件中之后依次导入update.yml, reboot.yml和install_vmtools.yml三个playbook。main.yml文件中也使用了ansible的tags功能,这样可以实现主机升级、重启、安装vmtools三个任务既可以单个执行又可以统一执行,适用于多种场景的使用。例如:

]# ansible-playbook  site.yml   # 统一执行
]# ansible-playbook  site.yml  --tags update_os  #只执行标签update_os即主机升级任务

ping.yml文件内容如下:

---
- name: test if linux is alive
  block:
  - name: 1st ping linux
    ping:
    register: ping
    failed_when: false
    ignore_unreachable: yes
    ignore_errors: yes
 
  - name: 2nd ping linux
    ping:
    register: ping2
    failed_when: false
    ignore_unreachable: yes
    ignore_errors: yes
    when: >
        (ping.failed is defined and ping.failed == true) or
        (ping.unreachable is defined and ping.unreacheable == true)
  when: (ansible_connection is defined) and ((ansible_connection == 'ssh') or (ansible_connection == ''))

  ping.yml文件的编写机制为: 第一次对受控主机执行ansible的ping模块,并使用register记录结果。 对于第一次ping失败时的主机,playbook将执行第二次ping。第二次ping的原因是为了避免网络抖动等因素导致第一次ping失败。只有第一次或第二次ping成功的受控主机才进行之后的任务。

 

三  参考文献

 

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/ops-cases/p/16927510.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!