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

使用说明:
相关系统的tar包需提前准备,而且tar包中不要带文件夹(只包含rpm包才可以)。

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

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

步骤一、在目标主机上创建rpm包存放目录:
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包
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

步骤四、执行升级命令:

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

rpm验证:

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

你可能感兴趣的:(linux系统,linux)