---
- name: 检查当前内核版本
  shell: uname -r
  register: current_kernel
  changed_when: false

- name: 验证是否需要升级内核
  fail:
    msg: "内核已经是 {{ kernel_version }} 版本，无需升级"
  when: kernel_version in current_kernel.stdout

- name: 创建内核RPM文件目录
  file:
    path: /tmp/kernel-rpms
    state: directory
    mode: '0755'
  become: yes

- name: 上传内核RPM文件到目标节点
  copy:
    src: "{{ item }}"
    dest: /tmp/kernel-rpms/
    mode: '0644'
  with_fileglob:
    - "files/kernel-lt-*.rpm"
  become: yes

- name: 卸载冲突的旧内核工具包
  yum:
    name:
      - kernel-tools
      - kernel-tools-libs
      - kernel-headers
    state: absent
  become: yes

- name: 逐个安装内核RPM包
  command: "yum localinstall -y /tmp/kernel-rpms/{{ item }} --nogpgcheck"
  with_items:
    - "kernel-lt-devel-5.4.278-1.el7.elrepo.x86_64.rpm"
    - "kernel-lt-tools-libs-5.4.278-1.el7.elrepo.x86_64.rpm"
    - "kernel-lt-tools-5.4.278-1.el7.elrepo.x86_64.rpm"
    - "kernel-lt-headers-5.4.278-1.el7.elrepo.x86_64.rpm"
    - "kernel-lt-tools-libs-devel-5.4.278-1.el7.elrepo.x86_64.rpm"
    - "kernel-lt-5.4.278-1.el7.elrepo.x86_64.rpm"
  become: yes

- name: 设置新内核为默认启动项
  shell: |
        grub2-set-default 0 && grub2-mkconfig -o /boot/grub2/grub.cfg
  become: yes

- name: 重启系统以应用新内核
  reboot:
    msg: "Reboot to apply new kernel"
    connect_timeout: 60
    reboot_timeout: 300
    pre_reboot_delay: 15
    post_reboot_delay: 30
  become: yes

- name: 等待系统重启后恢复连接
  wait_for_connection:
    connect_timeout: 60
    sleep: 10
    delay: 10
    timeout: 300

- name: 验证新内核版本
  shell: uname -r
  register: new_kernel
  changed_when: false

- name: 显示内核升级结果
  debug:
    msg: "内核已从 {{ current_kernel.stdout }} 升级到 {{ new_kernel.stdout }}"

- name: 清理临时RPM文件
  file:
    path: /tmp/kernel-rpms
    state: absent
  become: yes
