---
- name: 在 master 和 ash3c 节点安装 Consul
  hosts: master,ash3c
  become: yes
  vars:
    consul_version: "1.21.5"
    consul_arch: "arm64"  # 因为这两个节点都是 aarch64
    
  tasks:
    - name: 检查节点架构
      command: uname -m
      register: node_arch
      changed_when: false
      
    - name: 显示节点架构
      debug:
        msg: "节点 {{ inventory_hostname }} 架构: {{ node_arch.stdout }}"
        
    - name: 检查是否已安装 consul
      command: which consul
      register: consul_check
      failed_when: false
      changed_when: false
      
    - name: 显示当前 consul 状态
      debug:
        msg: "Consul 状态: {{ 'already installed' if consul_check.rc == 0 else 'not installed' }}"
        
    - name: 删除错误的 consul 二进制文件（如果存在）
      file:
        path: /usr/local/bin/consul
        state: absent
      when: consul_check.rc == 0
      
    - name: 更新 APT 缓存
      apt:
        update_cache: yes
      ignore_errors: yes
      
    - name: 安装 consul 通过 APT
      apt:
        name: consul={{ consul_version }}-1
        state: present
        
    - name: 验证 consul 安装
      command: consul version
      register: consul_version_check
      changed_when: false
      
    - name: 显示安装的 consul 版本
      debug:
        msg: "安装的 Consul 版本: {{ consul_version_check.stdout_lines[0] }}"
        
    - name: 确保 consul 用户存在
      user:
        name: consul
        system: yes
        shell: /bin/false
        home: /opt/consul
        create_home: no
        
    - name: 创建 consul 数据目录
      file:
        path: /opt/consul
        state: directory
        owner: consul
        group: consul
        mode: '0755'