Files
ansible-playbook/nezha_reinstall.yml
T

99 lines
2.7 KiB
YAML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
- name: 重装 Nezha Agent(卸载旧版本并安装新版本)
hosts: all
become: yes
vars:
# Nezha 服务端地址(host:port
nz_server: "dash.miner.vvvo.net:443"
# 是否启用 TLS
nz_tls: true
# 客户端密钥(必填,建议通过 -e 或 vars 文件传入,勿硬编码到仓库)
nz_client_secret: ""
# 安装脚本 URL
install_script_url: "https://raw.githubusercontent.com/wangdefaa/nezha-agent/refs/heads/main/script/install.sh"
# 服务与路径配置
service_name: "nezha-agent.service"
service_file: "/etc/systemd/system/nezha-agent.service"
install_dir: "/opt/nezha"
script_path: "/tmp/nezha-agent.sh"
tasks:
# ---------- 参数校验 ----------
- name: 验证必填参数
ansible.builtin.assert:
that:
- nz_client_secret | length > 0
fail_msg: "参数 nz_client_secret 不能为空"
success_msg: "参数验证通过"
# ---------- 卸载旧版本 ----------
- name: 检查服务单元文件是否存在
ansible.builtin.stat:
path: "{{ service_file }}"
register: service_file_stat
- name: 停止并禁用 Nezha Agent 服务
ansible.builtin.systemd:
name: "{{ service_name }}"
state: stopped
enabled: no
when: service_file_stat.stat.exists
- name: 删除服务单元文件
ansible.builtin.file:
path: "{{ service_file }}"
state: absent
register: unit_removed
- name: 重新加载 systemd 配置
ansible.builtin.systemd:
daemon_reload: yes
when: unit_removed.changed
- name: 删除安装目录
ansible.builtin.file:
path: "{{ install_dir }}"
state: absent
# ---------- 安装新版本 ----------
- name: 下载安装脚本
ansible.builtin.get_url:
url: "{{ install_script_url }}"
dest: "{{ script_path }}"
mode: '0755'
force: yes
- name: 执行安装脚本
ansible.builtin.shell: "bash {{ script_path }}"
args:
executable: /bin/bash
environment:
NZ_SERVER: "{{ nz_server }}"
NZ_TLS: "{{ nz_tls | lower }}"
NZ_CLIENT_SECRET: "{{ nz_client_secret }}"
register: install_output
- name: 显示安装结果
ansible.builtin.debug:
var: install_output.stdout_lines
- name: 清理临时脚本
ansible.builtin.file:
path: "{{ script_path }}"
state: absent
# ---------- 验证 ----------
- name: 验证 Nezha Agent 服务状态
ansible.builtin.systemd:
name: "{{ service_name }}"
register: service_status
- name: 显示服务状态
ansible.builtin.debug:
msg: "Nezha Agent 服务状态: {{ service_status.status.ActiveState }}"