ansible playbook脚本自动判断系统类型并升级rpm包

469 阅读2分钟

本文已参与 ⌈新人创作礼⌋ 活动,一起开启掘金创作之路
ansible playbook脚本自动判断系统类型并升级rpm包

使用说明: 将相关系统的rpm包通过tar -zcvf 创建成tar包,而且tar包中不要带文件夹(只包含rpm包才可以)。

准备工作: 主机列表文件内容:

[root@ansible_host redhat]# cat redhat.txt 
[redhat]
192.168.254.11 ansible_ssh_user=user1 ansible_ssh_pass=password ansible_sudo_pass=password 
192.168.254.125 ansible_ssh_user=user1 ansible_ssh_pass=password ansible_sudo_pass=password

步骤一、在目标主机上创建rpm包存放目录(在ansible管理主机上创建create_dir.yml,并粘贴如下yaml代码;脚本用途:在目标主机上的/tmp目录中创建update0715目标,为后续解压tar包做准备): create_dir.yml

---
- hosts: redhat
  gather_facts: False
  tasks:
   - name: Create a directory if it does not exist
     file:
      path: /tmp/update0715
      state: directory
      mode: '0755'

命令执行:

ansible-playbook create_dir.yml -i redhat.txt

步骤二、判断目标主机的系统版本,并上传rpm包(通过ansible自动收集主机信息当中的变量ansible_distribution和ansible_distribution_major_version获取操作系统类型和版本,并自动匹配后上传tar包到/tmp目录)

cat playbook1_upload.yml
---
- hosts: redhat
  gather_facts: True
  tasks:
   - name: copy redhat7 packages
     copy: 
         src: /tmp/redhat7.tar
         dest: /tmp/redhat7.tar
         mode: '0755'
     when: ansible_distribution == "RedHat" and ansible_distribution_major_version == "7"
   - name: copy redhat6 packages
     copy: 
         src: /tmp/redhat6.tar
         dest: /tmp/redhat6.tar
         mode: '0755'
     when: ansible_distribution == "RedHat" and ansible_distribution_major_version == "6"

步骤三、在目标主机上解压tar包

cat playbook2_tar.yml
---
- hosts: redhat
  gather_facts: yes
  tasks:
   - name: Extract
     unarchive:
       src: /tmp/redhat{{ansible_distribution_major_version}}.tar
       dest: /tmp/update0715
       remote_src: yes

步骤四、执行升级命令(rpm命令当中的F参数的意义:rpm命令会对比指定升级的rpm包的低版本在系统中是否存在;如果存在低版本,则进行升级;如果不存在低版本,则忽略此包;而rpm命令当中的参数U则是升级所有指定的包,不判断系统当中曾经是否存在低版本):

ansible -i redhat all -m shell -a 'cd /tmp/update0715;sudo rpm -Fvh *.rpm' -b

通过rpm命令验证rpm包是否升级成功:

`ansible -i redhat.txt redhat -m shell -a 'rpm -qa ***'`