1 feat: 重构基础设施架构并完善Consul集群配置

2
     3	主要变更:
     4	- 重构Terraform/OpenTofu目录结构,统一迁移至infrastructure/opentofu
     5	- 添加"7天创造世界"文档,记录基础设施建设演进逻辑
     6	- 更新Consul集群配置管理经验,添加实际案例和解决方案
     7	- 修正README中的Sticky Note,反映Consul集群健康状态
     8	- 添加Ansible部署配置和inventory文件
     9	- 完善项目文档结构,添加各组件配置指南
    10
    11	技术架构演进:
    12	- 第1天: Tailscale网络连接基础 
    13	- 第2天: Ansible分布式控制 
    14	- 第3天: Nomad服务感知与任务调度 
    15	- 第4天: Consul配置集中管理 
    16	- 第5天: OpenTofu状态一致性 
    17	- 第6天: Vault密钥管理 
    18	- 第7天: Waypoint应用部署 
This commit is contained in:
2025-09-30 03:46:33 +00:00
parent c0064b2cad
commit e8bfc76038
119 changed files with 1772 additions and 631 deletions

View File

@@ -0,0 +1,202 @@
---
- name: Add Warden Server as Nomad Client to Cluster
hosts: warden
become: yes
gather_facts: yes
vars:
nomad_plugin_dir: "/opt/nomad/plugins"
nomad_datacenter: "dc1"
nomad_region: "global"
nomad_servers:
- "100.117.106.136:4647"
- "100.116.80.94:4647"
- "100.97.62.111:4647"
- "100.116.112.45:4647"
- "100.84.197.26:4647"
tasks:
- name: 显示当前处理的节点
debug:
msg: "🔧 将 warden 服务器添加为 Nomad 客户端: {{ inventory_hostname }}"
- name: 检查 Nomad 是否已安装
shell: which nomad || echo "not_found"
register: nomad_check
changed_when: false
- name: 下载并安装 Nomad
block:
- name: 下载 Nomad 1.10.5
get_url:
url: "https://releases.hashicorp.com/nomad/1.10.5/nomad_1.10.5_linux_amd64.zip"
dest: "/tmp/nomad.zip"
mode: '0644'
- name: 解压并安装 Nomad
unarchive:
src: "/tmp/nomad.zip"
dest: "/usr/local/bin/"
remote_src: yes
owner: root
group: root
mode: '0755'
- name: 清理临时文件
file:
path: "/tmp/nomad.zip"
state: absent
when: nomad_check.stdout == "not_found"
- name: 验证 Nomad 安装
shell: nomad version
register: nomad_version_output
- name: 创建 Nomad 配置目录
file:
path: /etc/nomad.d
state: directory
owner: root
group: root
mode: '0755'
- name: 创建 Nomad 数据目录
file:
path: /opt/nomad/data
state: directory
owner: nomad
group: nomad
mode: '0755'
ignore_errors: yes
- name: 创建 Nomad 插件目录
file:
path: "{{ nomad_plugin_dir }}"
state: directory
owner: nomad
group: nomad
mode: '0755'
ignore_errors: yes
- name: 获取服务器 IP 地址
shell: |
ip route get 1.1.1.1 | grep -oP 'src \K\S+'
register: server_ip_result
changed_when: false
- name: 设置服务器 IP 变量
set_fact:
server_ip: "{{ server_ip_result.stdout }}"
- name: 停止 Nomad 服务(如果正在运行)
systemd:
name: nomad
state: stopped
ignore_errors: yes
- name: 创建 Nomad 客户端配置文件
copy:
content: |
# Nomad Client Configuration for warden
datacenter = "{{ nomad_datacenter }}"
data_dir = "/opt/nomad/data"
log_level = "INFO"
bind_addr = "{{ server_ip }}"
server {
enabled = false
}
client {
enabled = true
servers = [
{% for server in nomad_servers %}"{{ server }}"{% if not loop.last %}, {% endif %}{% endfor %}
]
}
plugin_dir = "{{ nomad_plugin_dir }}"
plugin "podman" {
config {
socket_path = "unix:///run/podman/podman.sock"
volumes {
enabled = true
}
}
}
consul {
address = "127.0.0.1:8500"
}
dest: /etc/nomad.d/nomad.hcl
owner: root
group: root
mode: '0644'
- name: 验证 Nomad 配置
shell: nomad config validate /etc/nomad.d/nomad.hcl
register: nomad_validate
failed_when: nomad_validate.rc != 0
- name: 创建 Nomad systemd 服务文件
copy:
content: |
[Unit]
Description=Nomad
Documentation=https://www.nomadproject.io/docs/
Wants=network-online.target
After=network-online.target
[Service]
Type=notify
User=root
Group=root
ExecStart=/usr/local/bin/nomad agent -config=/etc/nomad.d
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
KillSignal=SIGINT
TimeoutStopSec=5
LimitNOFILE=65536
LimitNPROC=32768
Restart=on-failure
RestartSec=2
[Install]
WantedBy=multi-user.target
dest: /etc/systemd/system/nomad.service
mode: '0644'
- name: 重新加载 systemd 配置
systemd:
daemon_reload: yes
- name: 启动并启用 Nomad 服务
systemd:
name: nomad
state: started
enabled: yes
- name: 等待 Nomad 服务启动
wait_for:
port: 4646
host: "{{ server_ip }}"
delay: 5
timeout: 60
- name: 检查 Nomad 客户端状态
shell: nomad node status -self
register: nomad_node_status
retries: 5
delay: 5
until: nomad_node_status.rc == 0
ignore_errors: yes
- name: 显示 Nomad 客户端配置结果
debug:
msg: |
✅ warden 服务器已成功配置为 Nomad 客户端
📦 Nomad 版本: {{ nomad_version_output.stdout.split('\n')[0] }}
🌐 服务器 IP: {{ server_ip }}
🏗️ 数据中心: {{ nomad_datacenter }}
📊 客户端状态: {{ 'SUCCESS' if nomad_node_status.rc == 0 else 'PENDING' }}
🚀 warden 现在是 Nomad 集群的一部分

View File

@@ -0,0 +1,72 @@
---
- name: 配置Nomad客户端节点
hosts: nomad_nodes:!semaphore
become: yes
vars:
nomad_config_dir: /etc/nomad.d
tasks:
- name: 创建Nomad配置目录
file:
path: "{{ nomad_config_dir }}"
state: directory
owner: root
group: root
mode: '0755'
- name: 复制Nomad客户端配置
copy:
content: |
datacenter = "dc1"
data_dir = "/opt/nomad/data"
log_level = "INFO"
bind_addr = "0.0.0.0"
server {
enabled = false
}
client {
enabled = true
servers = ["100.116.158.95:4647"]
host_volume "fnsync" {
path = "/mnt/fnsync"
read_only = false
}
}
addresses {
http = "{{ ansible_host }}"
rpc = "{{ ansible_host }}"
serf = "{{ ansible_host }}"
}
advertise {
http = "{{ ansible_host }}:4646"
rpc = "{{ ansible_host }}:4647"
serf = "{{ ansible_host }}:4648"
}
consul {
address = "100.116.158.95:8500"
}
dest: "{{ nomad_config_dir }}/nomad.hcl"
owner: root
group: root
mode: '0644'
- name: 启动Nomad服务
systemd:
name: nomad
state: restarted
enabled: yes
daemon_reload: yes
- name: 检查Nomad服务状态
command: systemctl status nomad
register: nomad_status
changed_when: false
- name: 显示Nomad服务状态
debug:
var: nomad_status.stdout_lines

View File

@@ -0,0 +1,57 @@
---
- name: Configure Podman driver for all Nomad client nodes
hosts: target_nodes
become: yes
tasks:
- name: Stop Nomad service
systemd:
name: nomad
state: stopped
- name: Install Podman if not present
package:
name: podman
state: present
ignore_errors: yes
- name: Enable Podman socket
systemd:
name: podman.socket
enabled: yes
state: started
ignore_errors: yes
- name: Update Nomad configuration to use Podman
lineinfile:
path: /etc/nomad.d/nomad.hcl
regexp: '^plugin "docker"'
line: 'plugin "podman" {'
state: present
- name: Add Podman plugin configuration
blockinfile:
path: /etc/nomad.d/nomad.hcl
marker: "# {mark} PODMAN PLUGIN CONFIG"
block: |
plugin "podman" {
config {
socket_path = "unix:///run/podman/podman.sock"
volumes {
enabled = true
}
}
}
insertafter: 'client {'
- name: Start Nomad service
systemd:
name: nomad
state: started
- name: Wait for Nomad to be ready
wait_for:
port: 4646
host: localhost
delay: 5
timeout: 30

View File

@@ -0,0 +1,22 @@
---
- name: Configure NOPASSWD sudo for nomad user
hosts: nomad_clients
become: yes
tasks:
- name: Ensure sudoers.d directory exists
file:
path: /etc/sudoers.d
state: directory
owner: root
group: root
mode: '0750'
- name: Allow nomad user passwordless sudo for required commands
copy:
dest: /etc/sudoers.d/nomad
content: |
nomad ALL=(ALL) NOPASSWD: /usr/bin/apt, /usr/bin/systemctl, /bin/mkdir, /bin/chown, /bin/chmod, /bin/mv, /bin/sed, /usr/bin/tee, /usr/sbin/usermod, /usr/bin/unzip, /usr/bin/wget
owner: root
group: root
mode: '0440'
validate: 'visudo -cf %s'

View File

@@ -0,0 +1,226 @@
---
- name: 配置 Nomad 集群使用 Tailscale 网络通讯
hosts: nomad_cluster
become: yes
gather_facts: no
vars:
nomad_config_dir: "/etc/nomad.d"
nomad_config_file: "{{ nomad_config_dir }}/nomad.hcl"
tasks:
- name: 获取当前节点的 Tailscale IP
shell: tailscale ip | head -1
register: current_tailscale_ip
changed_when: false
ignore_errors: yes
- name: 计算用于 Nomad 的地址(优先 Tailscale回退到 inventory 或 ansible_host
set_fact:
node_addr: "{{ (current_tailscale_ip.stdout | default('')) is match('^100\\.') | ternary((current_tailscale_ip.stdout | trim), (hostvars[inventory_hostname].tailscale_ip | default(ansible_host))) }}"
- name: 确保 Nomad 配置目录存在
file:
path: "{{ nomad_config_dir }}"
state: directory
owner: root
group: root
mode: '0755'
- name: 生成 Nomad 服务器配置(使用 Tailscale
copy:
dest: "{{ nomad_config_file }}"
owner: root
group: root
mode: '0644'
content: |
datacenter = "{{ nomad_datacenter | default('dc1') }}"
data_dir = "/opt/nomad/data"
log_level = "INFO"
bind_addr = "{{ node_addr }}"
addresses {
http = "{{ node_addr }}"
rpc = "{{ node_addr }}"
serf = "{{ node_addr }}"
}
ports {
http = 4646
rpc = 4647
serf = 4648
}
server {
enabled = true
bootstrap_expect = {{ nomad_bootstrap_expect | default(4) }}
retry_join = [
"100.116.158.95", # semaphore
"100.103.147.94", # ash2e
"100.81.26.3", # ash1d
"100.90.159.68" # ch2
]
encrypt = "{{ nomad_encrypt_key }}"
}
client {
enabled = false
}
plugin "podman" {
config {
socket_path = "unix:///run/podman/podman.sock"
volumes {
enabled = true
}
}
}
consul {
address = "{{ node_addr }}:8500"
}
when: nomad_role == "server"
notify: restart nomad
- name: 生成 Nomad 客户端配置(使用 Tailscale
copy:
dest: "{{ nomad_config_file }}"
owner: root
group: root
mode: '0644'
content: |
datacenter = "{{ nomad_datacenter | default('dc1') }}"
data_dir = "/opt/nomad/data"
log_level = "INFO"
bind_addr = "{{ node_addr }}"
addresses {
http = "{{ node_addr }}"
rpc = "{{ node_addr }}"
serf = "{{ node_addr }}"
}
ports {
http = 4646
rpc = 4647
serf = 4648
}
server {
enabled = false
}
client {
enabled = true
network_interface = "tailscale0"
cpu_total_compute = 0
servers = [
"100.116.158.95:4647", # semaphore
"100.103.147.94:4647", # ash2e
"100.81.26.3:4647", # ash1d
"100.90.159.68:4647" # ch2
]
}
plugin "podman" {
config {
socket_path = "unix:///run/podman/podman.sock"
volumes {
enabled = true
}
}
}
consul {
address = "{{ node_addr }}:8500"
}
when: nomad_role == "client"
notify: restart nomad
- name: 检查 Nomad 二进制文件位置
shell: which nomad || find /usr -name nomad 2>/dev/null | head -1
register: nomad_binary_path
failed_when: nomad_binary_path.stdout == ""
- name: 创建/更新 Nomad systemd 服务文件
copy:
dest: "/etc/systemd/system/nomad.service"
owner: root
group: root
mode: '0644'
content: |
[Unit]
Description=Nomad
Documentation=https://www.nomadproject.io/
Requires=network-online.target
After=network-online.target
[Service]
Type=notify
User=root
Group=root
ExecStart={{ nomad_binary_path.stdout }} agent -config=/etc/nomad.d/nomad.hcl
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
notify: restart nomad
- name: 确保 Nomad 数据目录存在
file:
path: "/opt/nomad/data"
state: directory
owner: root
group: root
mode: '0755'
- name: 重新加载 systemd daemon
systemd:
daemon_reload: yes
- name: 启用并启动 Nomad 服务
systemd:
name: nomad
enabled: yes
state: started
- name: 等待 Nomad 服务启动
wait_for:
port: 4646
host: "{{ node_addr }}"
delay: 5
timeout: 30
ignore_errors: yes
- name: 检查 Nomad 服务状态
shell: systemctl status nomad --no-pager -l
register: nomad_status
ignore_errors: yes
- name: 显示配置结果
debug:
msg: |
✅ 节点 {{ inventory_hostname }} 配置完成
🌐 使用地址: {{ node_addr }}
🎯 角色: {{ nomad_role }}
🔧 Nomad 二进制: {{ nomad_binary_path.stdout }}
📊 服务状态: {{ 'active' if nomad_status.rc == 0 else 'failed' }}
{% if nomad_status.rc != 0 %}
❌ 错误信息:
{{ nomad_status.stdout }}
{{ nomad_status.stderr }}
{% endif %}
handlers:
- name: restart nomad
systemd:
name: nomad
state: restarted
daemon_reload: yes

View File

@@ -0,0 +1,115 @@
---
- name: Configure Podman for Nomad Integration
hosts: all
become: yes
gather_facts: yes
tasks:
- name: 显示当前处理的节点
debug:
msg: "🔧 正在为 Nomad 配置 Podman: {{ inventory_hostname }}"
- name: 确保 Podman 已安装
package:
name: podman
state: present
- name: 启用并启动 Podman socket 服务
systemd:
name: podman.socket
enabled: yes
state: started
- name: 创建 Podman 系统配置目录
file:
path: /etc/containers
state: directory
mode: '0755'
- name: 配置 Podman 使用系统 socket
copy:
content: |
[engine]
# 使用系统级 socket 而不是用户级 socket
active_service = "system"
[engine.service_destinations]
[engine.service_destinations.system]
uri = "unix:///run/podman/podman.sock"
dest: /etc/containers/containers.conf
mode: '0644'
- name: 检查是否存在 nomad 用户
getent:
database: passwd
key: nomad
register: nomad_user_check
ignore_errors: yes
- name: 为 nomad 用户创建配置目录
file:
path: "/home/nomad/.config/containers"
state: directory
owner: nomad
group: nomad
mode: '0755'
when: nomad_user_check is succeeded
- name: 为 nomad 用户配置 Podman
copy:
content: |
[engine]
active_service = "system"
[engine.service_destinations]
[engine.service_destinations.system]
uri = "unix:///run/podman/podman.sock"
dest: /home/nomad/.config/containers/containers.conf
owner: nomad
group: nomad
mode: '0644'
when: nomad_user_check is succeeded
- name: 将 nomad 用户添加到 podman 组
user:
name: nomad
groups: podman
append: yes
when: nomad_user_check is succeeded
ignore_errors: yes
- name: 创建 podman 组(如果不存在)
group:
name: podman
state: present
ignore_errors: yes
- name: 设置 podman socket 目录权限
file:
path: /run/podman
state: directory
mode: '0755'
group: podman
ignore_errors: yes
- name: 验证 Podman socket 权限
file:
path: /run/podman/podman.sock
mode: '066'
when: nomad_user_check is succeeded
ignore_errors: yes
- name: 验证 Podman 安装
shell: podman --version
register: podman_version
- name: 测试 Podman 功能
shell: podman info
register: podman_info
ignore_errors: yes
- name: 显示配置结果
debug:
msg: |
✅ 节点 {{ inventory_hostname }} Podman 配置完成
📦 Podman 版本: {{ podman_version.stdout }}
🐳 Podman 状态: {{ 'SUCCESS' if podman_info.rc == 0 else 'WARNING' }}
👤 Nomad 用户: {{ 'FOUND' if nomad_user_check is succeeded else 'NOT FOUND' }}

View File

@@ -0,0 +1,168 @@
---
- name: 磁盘空间分析 - 使用 ncdu 工具
hosts: all
become: yes
vars:
ncdu_scan_paths:
- "/"
- "/var"
- "/opt"
- "/home"
output_dir: "/tmp/disk-analysis"
tasks:
- name: 安装 ncdu 工具
package:
name: ncdu
state: present
register: ncdu_install
- name: 创建输出目录
file:
path: "{{ output_dir }}"
state: directory
mode: '0755'
- name: 检查磁盘空间使用情况
shell: df -h
register: disk_usage
- name: 显示当前磁盘使用情况
debug:
msg: |
=== {{ inventory_hostname }} 磁盘使用情况 ===
{{ disk_usage.stdout }}
- name: 使用 ncdu 扫描根目录并生成报告
shell: |
ncdu -x -o {{ output_dir }}/ncdu-root-{{ inventory_hostname }}.json /
async: 300
poll: 0
register: ncdu_root_scan
- name: 使用 ncdu 扫描 /var 目录
shell: |
ncdu -x -o {{ output_dir }}/ncdu-var-{{ inventory_hostname }}.json /var
async: 180
poll: 0
register: ncdu_var_scan
when: ansible_mounts | selectattr('mount', 'equalto', '/var') | list | length > 0 or '/var' in ansible_mounts | map(attribute='mount') | list
- name: 使用 ncdu 扫描 /opt 目录
shell: |
ncdu -x -o {{ output_dir }}/ncdu-opt-{{ inventory_hostname }}.json /opt
async: 120
poll: 0
register: ncdu_opt_scan
when: ansible_mounts | selectattr('mount', 'equalto', '/opt') | list | length > 0 or '/opt' in ansible_mounts | map(attribute='mount') | list
- name: 等待根目录扫描完成
async_status:
jid: "{{ ncdu_root_scan.ansible_job_id }}"
register: ncdu_root_result
until: ncdu_root_result.finished
retries: 60
delay: 5
- name: 等待 /var 目录扫描完成
async_status:
jid: "{{ ncdu_var_scan.ansible_job_id }}"
register: ncdu_var_result
until: ncdu_var_result.finished
retries: 36
delay: 5
when: ncdu_var_scan is defined and ncdu_var_scan.ansible_job_id is defined
- name: 等待 /opt 目录扫描完成
async_status:
jid: "{{ ncdu_opt_scan.ansible_job_id }}"
register: ncdu_opt_result
until: ncdu_opt_result.finished
retries: 24
delay: 5
when: ncdu_opt_scan is defined and ncdu_opt_scan.ansible_job_id is defined
- name: 生成磁盘使用分析报告
shell: |
echo "=== {{ inventory_hostname }} 磁盘分析报告 ===" > {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
echo "生成时间: $(date)" >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
echo "" >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
echo "=== 磁盘使用情况 ===" >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
df -h >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
echo "" >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
echo "=== 最大的目录 (前10个) ===" >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
du -h --max-depth=2 / 2>/dev/null | sort -hr | head -10 >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
echo "" >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
echo "=== /var 目录最大文件 ===" >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
find /var -type f -size +100M -exec ls -lh {} \; 2>/dev/null | head -10 >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
echo "" >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
echo "=== /tmp 目录使用情况 ===" >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
du -sh /tmp/* 2>/dev/null | sort -hr | head -5 >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
echo "" >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
echo "=== 日志文件大小 ===" >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
find /var/log -name "*.log" -type f -size +50M -exec ls -lh {} \; 2>/dev/null >> {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
- name: 显示分析报告
shell: cat {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
register: disk_report
- name: 输出磁盘分析结果
debug:
msg: "{{ disk_report.stdout }}"
- name: 检查是否有磁盘使用率超过 80%
shell: df -h | awk 'NR>1 {gsub(/%/, "", $5); if($5 > 80) print $0}'
register: high_usage_disks
- name: 警告高磁盘使用率
debug:
msg: |
⚠️ 警告: {{ inventory_hostname }} 发现高磁盘使用率!
{{ high_usage_disks.stdout }}
when: high_usage_disks.stdout != ""
- name: 创建清理建议
shell: |
echo "=== {{ inventory_hostname }} 清理建议 ===" > {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
echo "" >> {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
echo "1. 检查日志文件:" >> {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
find /var/log -name "*.log" -type f -size +100M -exec echo " 大日志文件: {}" \; 2>/dev/null >> {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
echo "" >> {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
echo "2. 检查临时文件:" >> {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
find /tmp -type f -size +50M -exec echo " 大临时文件: {}" \; 2>/dev/null >> {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
echo "" >> {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
echo "3. 检查包缓存:" >> {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
if [ -d /var/cache/apt ]; then
echo " APT 缓存大小: $(du -sh /var/cache/apt 2>/dev/null | cut -f1)" >> {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
fi
if [ -d /var/cache/yum ]; then
echo " YUM 缓存大小: $(du -sh /var/cache/yum 2>/dev/null | cut -f1)" >> {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
fi
echo "" >> {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
echo "4. 检查容器相关:" >> {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
if command -v podman >/dev/null 2>&1; then
echo " Podman 镜像: $(podman images --format 'table {{.Repository}} {{.Tag}} {{.Size}}' 2>/dev/null | wc -l) 个" >> {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
echo " Podman 容器: $(podman ps -a --format 'table {{.Names}} {{.Status}}' 2>/dev/null | wc -l) 个" >> {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
fi
- name: 显示清理建议
shell: cat {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt
register: cleanup_suggestions
- name: 输出清理建议
debug:
msg: "{{ cleanup_suggestions.stdout }}"
- name: 保存 ncdu 文件位置信息
debug:
msg: |
📁 ncdu 扫描文件已保存到:
- 根目录: {{ output_dir }}/ncdu-root-{{ inventory_hostname }}.json
- /var 目录: {{ output_dir }}/ncdu-var-{{ inventory_hostname }}.json (如果存在)
- /opt 目录: {{ output_dir }}/ncdu-opt-{{ inventory_hostname }}.json (如果存在)
💡 使用方法:
ncdu -f {{ output_dir }}/ncdu-root-{{ inventory_hostname }}.json
📊 完整报告: {{ output_dir }}/disk-report-{{ inventory_hostname }}.txt
🧹 清理建议: {{ output_dir }}/cleanup-suggestions-{{ inventory_hostname }}.txt

View File

@@ -0,0 +1,96 @@
---
- name: 磁盘清理工具
hosts: all
become: yes
vars:
cleanup_logs: true
cleanup_cache: true
cleanup_temp: true
cleanup_containers: false # 谨慎操作
tasks:
- name: 检查磁盘使用情况 (清理前)
shell: df -h
register: disk_before
- name: 显示清理前磁盘使用情况
debug:
msg: |
=== {{ inventory_hostname }} 清理前磁盘使用情况 ===
{{ disk_before.stdout }}
- name: 清理系统日志 (保留最近7天)
shell: |
journalctl --vacuum-time=7d
find /var/log -name "*.log" -type f -mtime +7 -exec truncate -s 0 {} \;
find /var/log -name "*.log.*" -type f -mtime +7 -delete
when: cleanup_logs | bool
register: log_cleanup
- name: 清理包管理器缓存
block:
- name: 清理 APT 缓存 (Debian/Ubuntu)
shell: |
apt-get clean
apt-get autoclean
apt-get autoremove -y
when: ansible_os_family == "Debian"
- name: 清理 YUM/DNF 缓存 (RedHat/CentOS)
shell: |
if command -v dnf >/dev/null 2>&1; then
dnf clean all
elif command -v yum >/dev/null 2>&1; then
yum clean all
fi
when: ansible_os_family == "RedHat"
when: cleanup_cache | bool
- name: 清理临时文件
shell: |
find /tmp -type f -atime +7 -delete 2>/dev/null || true
find /var/tmp -type f -atime +7 -delete 2>/dev/null || true
rm -rf /tmp/.* 2>/dev/null || true
when: cleanup_temp | bool
- name: 清理 Podman 资源 (谨慎操作)
block:
- name: 停止所有容器
shell: podman stop --all
ignore_errors: yes
- name: 删除未使用的容器
shell: podman container prune -f
ignore_errors: yes
- name: 删除未使用的镜像
shell: podman image prune -f
ignore_errors: yes
- name: 删除未使用的卷
shell: podman volume prune -f
ignore_errors: yes
when: cleanup_containers | bool
- name: 清理核心转储文件
shell: |
find /var/crash -name "core.*" -type f -delete 2>/dev/null || true
find / -name "core" -type f -size +10M -delete 2>/dev/null || true
ignore_errors: yes
- name: 检查磁盘使用情况 (清理后)
shell: df -h
register: disk_after
- name: 显示清理结果
debug:
msg: |
=== {{ inventory_hostname }} 清理完成 ===
清理前:
{{ disk_before.stdout }}
清理后:
{{ disk_after.stdout }}
🧹 清理操作完成!

View File

@@ -0,0 +1,76 @@
---
- name: Distribute Nomad Podman Driver to all nodes
hosts: nomad_cluster
become: yes
vars:
nomad_user: nomad
nomad_data_dir: /opt/nomad/data
nomad_plugins_dir: "{{ nomad_data_dir }}/plugins"
tasks:
- name: Stop Nomad service
systemd:
name: nomad
state: stopped
- name: Create plugins directory
file:
path: "{{ nomad_plugins_dir }}"
state: directory
owner: "{{ nomad_user }}"
group: "{{ nomad_user }}"
mode: '0755'
- name: Copy Nomad Podman driver from local
copy:
src: /tmp/nomad-driver-podman
dest: "{{ nomad_plugins_dir }}/nomad-driver-podman"
owner: "{{ nomad_user }}"
group: "{{ nomad_user }}"
mode: '0755'
- name: Update Nomad configuration for plugin directory
lineinfile:
path: /etc/nomad.d/nomad.hcl
regexp: '^plugin_dir'
line: 'plugin_dir = "{{ nomad_plugins_dir }}"'
insertafter: 'data_dir = "/opt/nomad/data"'
- name: Ensure Podman is installed
package:
name: podman
state: present
- name: Enable Podman socket
systemd:
name: podman.socket
enabled: yes
state: started
ignore_errors: yes
- name: Start Nomad service
systemd:
name: nomad
state: started
enabled: yes
- name: Wait for Nomad to be ready
wait_for:
port: 4646
host: localhost
delay: 10
timeout: 60
- name: Wait for plugins to load
pause:
seconds: 15
- name: Check driver status
shell: |
/usr/local/bin/nomad node status -self | grep -A 10 "Driver Status" || /usr/bin/nomad node status -self | grep -A 10 "Driver Status"
register: driver_status
failed_when: false
- name: Display driver status
debug:
var: driver_status.stdout_lines

View File

@@ -0,0 +1,12 @@
- name: Distribute new podman binary to specified nomad_clients
hosts: nomadlxc,hcp,huawei,ditigalocean
gather_facts: false
tasks:
- name: Copy new podman binary to /usr/local/bin
copy:
src: /root/mgmt/configuration/podman-remote-static-linux_amd64
dest: /usr/local/bin/podman
owner: root
group: root
mode: '0755'
become: yes

View File

@@ -0,0 +1,161 @@
---
- name: Install and Configure Nomad Podman Driver on Client Nodes
hosts: nomad_clients
become: yes
vars:
nomad_plugin_dir: "/opt/nomad/plugins"
tasks:
- name: Create backup directory with timestamp
set_fact:
backup_dir: "/root/backup/{{ ansible_date_time.date }}_{{ ansible_date_time.hour }}{{ ansible_date_time.minute }}{{ ansible_date_time.second }}"
- name: Create backup directory
file:
path: "{{ backup_dir }}"
state: directory
mode: '0755'
- name: Backup current Nomad configuration
copy:
src: /etc/nomad.d/nomad.hcl
dest: "{{ backup_dir }}/nomad.hcl.backup"
remote_src: yes
ignore_errors: yes
- name: Backup current apt sources
shell: |
cp -r /etc/apt/sources.list* {{ backup_dir }}/
dpkg --get-selections > {{ backup_dir }}/installed_packages.txt
ignore_errors: yes
- name: Create temporary directory for apt
file:
path: /tmp/apt-temp
state: directory
mode: '1777'
- name: Download HashiCorp GPG key
get_url:
url: https://apt.releases.hashicorp.com/gpg
dest: /tmp/hashicorp.gpg
mode: '0644'
environment:
TMPDIR: /tmp/apt-temp
- name: Install HashiCorp GPG key
shell: |
gpg --dearmor < /tmp/hashicorp.gpg > /usr/share/keyrings/hashicorp-archive-keyring.gpg
environment:
TMPDIR: /tmp/apt-temp
- name: Add HashiCorp repository
lineinfile:
path: /etc/apt/sources.list.d/hashicorp.list
line: "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com {{ ansible_distribution_release }} main"
create: yes
mode: '0644'
- name: Update apt cache
apt:
update_cache: yes
environment:
TMPDIR: /tmp/apt-temp
ignore_errors: yes
- name: Install nomad-driver-podman
apt:
name: nomad-driver-podman
state: present
environment:
TMPDIR: /tmp/apt-temp
- name: Create Nomad plugin directory
file:
path: "{{ nomad_plugin_dir }}"
state: directory
owner: nomad
group: nomad
mode: '0755'
- name: Create symlink for nomad-driver-podman in plugin directory
file:
src: /usr/bin/nomad-driver-podman
dest: "{{ nomad_plugin_dir }}/nomad-driver-podman"
state: link
owner: nomad
group: nomad
- name: Get server IP address
shell: |
ip route get 1.1.1.1 | grep -oP 'src \K\S+'
register: server_ip_result
changed_when: false
- name: Set server IP fact
set_fact:
server_ip: "{{ server_ip_result.stdout }}"
- name: Stop Nomad service
systemd:
name: nomad
state: stopped
- name: Create updated Nomad client configuration
copy:
content: |
datacenter = "{{ nomad_datacenter }}"
data_dir = "/opt/nomad/data"
log_level = "INFO"
bind_addr = "{{ server_ip }}"
server {
enabled = false
}
client {
enabled = true
servers = ["100.117.106.136:4647", "100.116.80.94:4647", "100.97.62.111:4647", "100.116.112.45:4647", "100.84.197.26:4647"]
}
plugin_dir = "{{ nomad_plugin_dir }}"
plugin "nomad-driver-podman" {
config {
volumes {
enabled = true
}
recover_stopped = true
}
}
consul {
address = "127.0.0.1:8500"
}
dest: /etc/nomad.d/nomad.hcl
owner: nomad
group: nomad
mode: '0640'
backup: yes
- name: Validate Nomad configuration
shell: nomad config validate /etc/nomad.d/nomad.hcl
register: nomad_validate
failed_when: nomad_validate.rc != 0
- name: Start Nomad service
systemd:
name: nomad
state: started
enabled: yes
- name: Wait for Nomad to be ready
wait_for:
port: 4646
host: "{{ server_ip }}"
delay: 5
timeout: 60
- name: Display backup location
debug:
msg: "Backup created at: {{ backup_dir }}"

View File

@@ -0,0 +1,68 @@
---
- 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'

View File

@@ -0,0 +1,131 @@
---
- name: Install Nomad by direct download from HashiCorp
hosts: all
become: yes
vars:
nomad_user: "nomad"
nomad_group: "nomad"
nomad_home: "/opt/nomad"
nomad_data_dir: "/opt/nomad/data"
nomad_config_dir: "/etc/nomad.d"
nomad_datacenter: "dc1"
nomad_region: "global"
nomad_server_addresses:
- "100.116.158.95:4647" # semaphore server address
tasks:
- name: Create nomad user
user:
name: "{{ nomad_user }}"
group: "{{ nomad_group }}"
system: yes
shell: /bin/false
home: "{{ nomad_home }}"
create_home: yes
- name: Create nomad directories
file:
path: "{{ item }}"
state: directory
owner: "{{ nomad_user }}"
group: "{{ nomad_group }}"
mode: '0755'
loop:
- "{{ nomad_home }}"
- "{{ nomad_data_dir }}"
- "{{ nomad_config_dir }}"
- /var/log/nomad
- name: Install unzip package
apt:
name: unzip
state: present
update_cache: yes
- name: Download Nomad binary
get_url:
url: "{{ nomad_url }}"
dest: "/tmp/nomad_{{ nomad_version }}_linux_amd64.zip"
mode: '0644'
timeout: 300
- name: Extract Nomad binary
unarchive:
src: "/tmp/nomad_{{ nomad_version }}_linux_amd64.zip"
dest: /tmp
remote_src: yes
- name: Copy Nomad binary to /usr/local/bin
copy:
src: /tmp/nomad
dest: /usr/local/bin/nomad
mode: '0755'
owner: root
group: root
remote_src: yes
- name: Create Nomad client configuration
template:
src: templates/nomad-client.hcl.j2
dest: "{{ nomad_config_dir }}/nomad.hcl"
owner: "{{ nomad_user }}"
group: "{{ nomad_group }}"
mode: '0640'
- name: Create Nomad systemd service
copy:
content: |
[Unit]
Description=Nomad
Documentation=https://www.nomadproject.io/
Requires=network-online.target
After=network-online.target
ConditionFileNotEmpty={{ nomad_config_dir }}/nomad.hcl
[Service]
Type=notify
User={{ nomad_user }}
Group={{ nomad_group }}
ExecStart=/usr/local/bin/nomad agent -config={{ nomad_config_dir }}
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
dest: /etc/systemd/system/nomad.service
mode: '0644'
- name: Reload systemd daemon
systemd:
daemon_reload: yes
- name: Enable and start Nomad service
systemd:
name: nomad
enabled: yes
state: started
- name: Wait for Nomad to be ready
wait_for:
port: 4646
host: localhost
delay: 5
timeout: 60
- name: Verify Nomad installation
command: /usr/local/bin/nomad version
register: nomad_version_output
- name: Display Nomad version
debug:
msg: "{{ nomad_version_output.stdout }}"
- name: Clean up downloaded files
file:
path: "{{ item }}"
state: absent
loop:
- "/tmp/nomad_{{ nomad_version }}_linux_amd64.zip"
- /tmp/nomad

View File

@@ -0,0 +1,131 @@
---
- name: Install Nomad Podman Driver Plugin
hosts: target_nodes
become: yes
vars:
nomad_user: nomad
nomad_data_dir: /opt/nomad/data
nomad_plugins_dir: "{{ nomad_data_dir }}/plugins"
podman_driver_version: "0.6.1"
podman_driver_url: "https://releases.hashicorp.com/nomad-driver-podman/{{ podman_driver_version }}/nomad-driver-podman_{{ podman_driver_version }}_linux_amd64.zip"
tasks:
- name: Stop Nomad service
systemd:
name: nomad
state: stopped
- name: Create plugins directory
file:
path: "{{ nomad_plugins_dir }}"
state: directory
owner: "{{ nomad_user }}"
group: "{{ nomad_user }}"
mode: '0755'
- name: Download Nomad Podman driver
get_url:
url: "{{ podman_driver_url }}"
dest: "/tmp/nomad-driver-podman_{{ podman_driver_version }}_linux_amd64.zip"
mode: '0644'
- name: Extract Nomad Podman driver
unarchive:
src: "/tmp/nomad-driver-podman_{{ podman_driver_version }}_linux_amd64.zip"
dest: "/tmp"
remote_src: yes
- name: Install Nomad Podman driver
copy:
src: "/tmp/nomad-driver-podman"
dest: "{{ nomad_plugins_dir }}/nomad-driver-podman"
owner: "{{ nomad_user }}"
group: "{{ nomad_user }}"
mode: '0755'
remote_src: yes
- name: Update Nomad configuration for plugin directory
blockinfile:
path: /etc/nomad.d/nomad.hcl
marker: "# {mark} PLUGIN DIRECTORY CONFIGURATION"
block: |
plugin_dir = "{{ nomad_plugins_dir }}"
insertafter: 'data_dir = "/opt/nomad/data"'
- name: Fix Podman socket permissions
file:
path: /run/user/1001/podman/podman.sock
mode: '0666'
ignore_errors: yes
- name: Ensure nomad user can access Podman socket
user:
name: "{{ nomad_user }}"
groups: ben
append: yes
- name: Start Nomad service
systemd:
name: nomad
state: started
enabled: yes
- name: Wait for Nomad to be ready
wait_for:
port: 4646
host: localhost
delay: 10
timeout: 60
- name: Verify Nomad is running
systemd:
name: nomad
register: nomad_service_status
- name: Display Nomad service status
debug:
msg: "Nomad service is {{ nomad_service_status.status.ActiveState }}"
- name: Wait for plugins to load
pause:
seconds: 15
- name: Check available drivers
shell: |
sudo -u {{ nomad_user }} /usr/local/bin/nomad node status -self | grep -A 20 "Driver Status"
register: driver_status
failed_when: false
- name: Display driver status
debug:
var: driver_status.stdout_lines
- name: Test Podman driver functionality
shell: |
sudo -u {{ nomad_user }} /usr/local/bin/nomad node status -json | jq -r '.Drivers | keys[]'
register: available_drivers
failed_when: false
- name: Display available drivers
debug:
msg: "Available drivers: {{ available_drivers.stdout_lines | join(', ') }}"
- name: Clean up downloaded files
file:
path: "{{ item }}"
state: absent
loop:
- "/tmp/nomad-driver-podman_{{ podman_driver_version }}_linux_amd64.zip"
- "/tmp/nomad-driver-podman"
- name: Final verification - Check if Podman driver is loaded
shell: |
sudo -u {{ nomad_user }} /usr/local/bin/nomad node status -json | jq -r '.Drivers.podman.Detected'
register: podman_driver_detected
failed_when: false
- name: Display final result
debug:
msg: |
Podman driver installation: {{ 'SUCCESS' if podman_driver_detected.stdout == 'true' else 'NEEDS VERIFICATION' }}
Driver detected: {{ podman_driver_detected.stdout | default('unknown') }}

View File

@@ -0,0 +1,61 @@
---
- name: Install Podman Compose on all Nomad cluster nodes
hosts: nomad_cluster
become: yes
tasks:
- name: Display target node
debug:
msg: "正在安装 Podman Compose 到节点: {{ inventory_hostname }}"
- name: Update package cache
apt:
update_cache: yes
ignore_errors: yes
- name: Install Podman and related tools
apt:
name:
- podman
- podman-compose
- buildah
- skopeo
state: present
ignore_errors: yes
- name: Install additional dependencies
apt:
name:
- python3-pip
- python3-setuptools
state: present
ignore_errors: yes
- name: Install podman-compose via pip if package manager failed
pip:
name: podman-compose
state: present
ignore_errors: yes
- name: Verify Podman installation
shell: podman --version
register: podman_version
- name: Verify Podman Compose installation
shell: podman-compose --version
register: podman_compose_version
ignore_errors: yes
- name: Display installation results
debug:
msg: |
✅ 节点 {{ inventory_hostname }} 安装结果:
📦 Podman: {{ podman_version.stdout }}
🐳 Podman Compose: {{ podman_compose_version.stdout if podman_compose_version.rc == 0 else '安装失败或不可用' }}
- name: Ensure Podman socket is enabled
systemd:
name: podman.socket
enabled: yes
state: started
ignore_errors: yes

View File

@@ -0,0 +1,115 @@
---
- name: 在Kali Linux上安装和配置VNC服务器
hosts: kali
become: yes
vars:
vnc_password: "3131" # VNC连接密码
vnc_port: "5901" # VNC服务端口
vnc_geometry: "1280x1024" # VNC分辨率
vnc_depth: "24" # 颜色深度
tasks:
- name: 更新APT缓存
apt:
update_cache: yes
- name: 安装VNC服务器和客户端
apt:
name:
- tigervnc-standalone-server
- tigervnc-viewer
- xfce4
- xfce4-goodies
state: present
- name: 创建VNC配置目录
file:
path: /home/ben/.vnc
state: directory
owner: ben
group: ben
mode: '0700'
- name: 设置VNC密码
shell: |
echo "{{ vnc_password }}" | vncpasswd -f > /home/ben/.vnc/passwd
echo "{{ vnc_password }}" | vncpasswd -f > /home/ben/.vnc/passwd2
become_user: ben
- name: 设置VNC密码文件权限
file:
path: /home/ben/.vnc/passwd
owner: ben
group: ben
mode: '0600'
- name: 设置VNC密码文件2权限
file:
path: /home/ben/.vnc/passwd2
owner: ben
group: ben
mode: '0600'
- name: 创建VNC启动脚本
copy:
dest: /home/ben/.vnc/xstartup
content: |
#!/bin/bash
unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS
exec startxfce4
owner: ben
group: ben
mode: '0755'
- name: 创建VNC服务文件
copy:
dest: /etc/systemd/system/vncserver@.service
content: |
[Unit]
Description=Start TigerVNC server at startup
After=syslog.target network.target
[Service]
Type=forking
User=ben
Group=ben
WorkingDirectory=/home/ben
PIDFile=/home/ben/.vnc/%H:%i.pid
ExecStartPre=-/usr/bin/vncserver -kill :%i > /dev/null 2>&1
ExecStart=/usr/bin/vncserver -depth {{ vnc_depth }} -geometry {{ vnc_geometry }} :%i
ExecStop=/usr/bin/vncserver -kill :%i
[Install]
WantedBy=multi-user.target
- name: 重新加载systemd配置
systemd:
daemon_reload: yes
- name: 启用并启动VNC服务
systemd:
name: vncserver@1.service
enabled: yes
state: started
- name: 检查VNC服务状态
command: systemctl status vncserver@1.service
register: vnc_status
ignore_errors: yes
- name: 显示VNC服务状态
debug:
msg: "{{ vnc_status.stdout_lines }}"
- name: 显示VNC连接信息
debug:
msg: |
VNC服务器已成功配置
连接信息:
- 地址: {{ ansible_host }}
- 端口: {{ vnc_port }}
- 密码: {{ vnc_password }}
- 连接命令: vnc://{{ ansible_host }}:{{ vnc_port }}
- 使用macOS屏幕共享应用连接到上述地址

View File

@@ -0,0 +1,36 @@
---
# install_vault.yml
- name: Install HashiCorp Vault
hosts: vault_servers
become: yes
tasks:
- name: Check if Vault is already installed
command: which vault
register: vault_check
ignore_errors: yes
changed_when: false
- name: Install Vault using apt
apt:
name: vault
state: present
update_cache: yes
when: vault_check.rc != 0
- name: Create Vault data directory
file:
path: "{{ vault_data_dir | default('/opt/nomad/data/vault/config') }}"
state: directory
owner: root
group: root
mode: '0755'
recurse: yes
- name: Verify Vault installation
command: vault --version
register: vault_version
changed_when: false
- name: Display Vault version
debug:
var: vault_version.stdout

View File

@@ -0,0 +1,42 @@
---
- name: 配置Nomad节点NFS挂载
hosts: nomad_nodes
become: yes
vars:
nfs_server: "snail"
nfs_share: "/fs/1000/nfs/Fnsync"
mount_point: "/mnt/fnsync"
tasks:
- name: 安装NFS客户端
package:
name: nfs-common
state: present
- name: 创建挂载目录
file:
path: "{{ mount_point }}"
state: directory
mode: '0755'
- name: 临时挂载NFS共享
mount:
path: "{{ mount_point }}"
src: "{{ nfs_server }}:{{ nfs_share }}"
fstype: nfs4
opts: "rw,relatime,vers=4.2"
state: mounted
- name: 配置开机自动挂载
lineinfile:
path: /etc/fstab
line: "{{ nfs_server }}:{{ nfs_share }} {{ mount_point }} nfs4 rw,relatime,vers=4.2 0 0"
state: present
- name: 验证挂载
command: df -h {{ mount_point }}
register: mount_check
- name: 显示挂载信息
debug:
var: mount_check.stdout_lines

View File

@@ -0,0 +1,81 @@
---
- name: Setup complete SSH key authentication for browser host
hosts: browser
become: yes
vars:
target_user: ben
ssh_key_comment: "ansible-generated-key-for-{{ inventory_hostname }}"
tasks:
- name: Copy existing Ed25519 SSH public key to target user
copy:
src: /root/.ssh/id_ed25519.pub
dest: /home/{{ target_user }}/.ssh/id_ed25519.pub
owner: "{{ target_user }}"
group: "{{ target_user }}"
mode: '0644'
- name: Copy existing Ed25519 SSH private key to target user
copy:
src: /root/.ssh/id_ed25519
dest: /home/{{ target_user }}/.ssh/id_ed25519
owner: "{{ target_user }}"
group: "{{ target_user }}"
mode: '0600'
- name: Get SSH public key content
command: cat /home/{{ target_user }}/.ssh/id_ed25519.pub
register: ssh_public_key
become_user: "{{ target_user }}"
changed_when: false
- name: Ensure .ssh directory exists for user
file:
path: /home/{{ target_user }}/.ssh
state: directory
owner: "{{ target_user }}"
group: "{{ target_user }}"
mode: '0700'
- name: Add public key to authorized_keys
authorized_key:
user: "{{ target_user }}"
state: present
key: "{{ ssh_public_key.stdout }}"
become_user: "{{ target_user }}"
- name: Configure SSH to prefer key authentication
lineinfile:
path: /etc/ssh/sshd_config
regexp: '^PasswordAuthentication'
line: 'PasswordAuthentication yes'
backup: yes
notify: restart sshd
when: ansible_connection != 'local'
- name: Configure SSH to allow key authentication
lineinfile:
path: /etc/ssh/sshd_config
regexp: '^PubkeyAuthentication'
line: 'PubkeyAuthentication yes'
backup: yes
notify: restart sshd
when: ansible_connection != 'local'
- name: Configure SSH authorized keys file permissions
file:
path: /home/{{ target_user }}/.ssh/authorized_keys
owner: "{{ target_user }}"
group: "{{ target_user }}"
mode: '0600'
- name: Display success message
debug:
msg: "SSH key authentication has been configured for user {{ target_user }} on {{ inventory_hostname }}"
handlers:
- name: restart sshd
systemd:
name: sshd
state: restarted
when: ansible_connection != 'local'

View File

@@ -0,0 +1,62 @@
---
- name: Setup SSH key authentication for browser host
hosts: browser
become: yes
vars:
target_user: ben
ssh_key_comment: "ansible-generated-key"
tasks:
- name: Generate SSH key pair if it doesn't exist
user:
name: "{{ target_user }}"
generate_ssh_key: yes
ssh_key_bits: 4096
ssh_key_comment: "{{ ssh_key_comment }}"
become_user: "{{ target_user }}"
- name: Get SSH public key content
command: cat /home/{{ target_user }}/.ssh/id_rsa.pub
register: ssh_public_key
become_user: "{{ target_user }}"
changed_when: false
- name: Display SSH public key for manual configuration
debug:
msg: |
SSH Public Key for {{ inventory_hostname }}:
{{ ssh_public_key.stdout }}
To complete key-based authentication setup:
1. Copy the above public key to the target system's authorized_keys
2. Or use ssh-copy-id command from this system:
ssh-copy-id -i /home/{{ target_user }}/.ssh/id_rsa.pub {{ target_user }}@{{ inventory_hostname }}
- name: Ensure .ssh directory exists for user
file:
path: /home/{{ target_user }}/.ssh
state: directory
owner: "{{ target_user }}"
group: "{{ target_user }}"
mode: '0700'
- name: Configure SSH to prefer key authentication
lineinfile:
path: /etc/ssh/sshd_config
regexp: '^PasswordAuthentication'
line: 'PasswordAuthentication yes'
backup: yes
notify: restart sshd
- name: Configure SSH to allow key authentication
lineinfile:
path: /etc/ssh/sshd_config
regexp: '^PubkeyAuthentication'
line: 'PubkeyAuthentication yes'
backup: yes
notify: restart sshd
handlers:
- name: restart sshd
systemd:
name: sshd
state: restarted

View File

@@ -0,0 +1,43 @@
---
- name: 设置Nomad节点NFS挂载
hosts: nomad_nodes
become: yes
vars:
nfs_server: "snail"
nfs_share: "/fs/1000/nfs/Fnsync"
mount_point: "/mnt/fnsync"
tasks:
- name: 安装NFS客户端
package:
name: nfs-common
state: present
- name: 创建挂载目录
file:
path: "{{ mount_point }}"
state: directory
mode: '0755'
- name: 临时挂载NFS共享
mount:
path: "{{ mount_point }}"
src: "{{ nfs_server }}:{{ nfs_share }}"
fstype: nfs4
opts: "rw,relatime,vers=4.2"
state: mounted
- name: 配置开机自动挂载
lineinfile:
path: /etc/fstab
line: "{{ nfs_server }}:{{ nfs_share }} {{ mount_point }} nfs4 rw,relatime,vers=4.2 0 0"
state: present
- name: 验证挂载
command: df -h {{ mount_point }}
register: mount_check
- name: 显示挂载信息
debug:
var: mount_check.stdout_lines

View File

@@ -0,0 +1,187 @@
---
- name: 部署 Telegraf 硬盘监控到 Nomad 集群
hosts: all
become: yes
vars:
# 连接现有的 InfluxDB 2.x + Grafana 监控栈
influxdb_url: "{{ influxdb_url | default('http://influxdb1.tailnet-68f9.ts.net:8086') }}"
influxdb_token: "{{ influxdb_token }}"
influxdb_org: "{{ influxdb_org | default('nomad') }}"
influxdb_bucket: "{{ influxdb_bucket | default('nomad_monitoring') }}"
# 远程 Telegraf 配置模式(优先)
use_remote_config: "{{ use_remote_config | default(true) }}"
telegraf_config_url: "{{ telegraf_config_url | default('') }}"
# 硬盘监控阈值
disk_usage_warning: 80 # 80% 使用率警告
disk_usage_critical: 90 # 90% 使用率严重告警
# 监控间隔(秒)
collection_interval: 30
tasks:
- name: 显示正在处理的节点
debug:
msg: "🔧 正在为节点 {{ inventory_hostname }} 安装硬盘监控"
- name: 添加 InfluxData 仓库密钥
apt_key:
url: https://repos.influxdata.com/influxdata-archive_compat.key
state: present
retries: 3
delay: 5
- name: 添加 InfluxData 仓库
apt_repository:
repo: "deb https://repos.influxdata.com/ubuntu {{ ansible_distribution_release }} stable"
state: present
update_cache: yes
retries: 3
delay: 5
- name: 安装 Telegraf
apt:
name: telegraf
state: present
update_cache: yes
retries: 3
delay: 10
- name: 创建 Telegraf 配置目录
file:
path: /etc/telegraf/telegraf.d
state: directory
owner: telegraf
group: telegraf
mode: '0755'
- name: 清理旧的 Telegraf 日志文件(节省硬盘空间)
file:
path: "{{ item }}"
state: absent
loop:
- /var/log/telegraf
- /var/log/telegraf.log
ignore_errors: yes
- name: 禁用 Telegraf 日志目录创建
file:
path: /var/log/telegraf
state: absent
ignore_errors: yes
- name: 创建 Telegraf 环境变量文件
template:
src: telegraf-env.j2
dest: /etc/default/telegraf
owner: root
group: root
mode: '0600'
backup: yes
notify: restart telegraf
- name: 创建 Telegraf systemd 服务文件(支持远程配置)
template:
src: telegraf.service.j2
dest: /etc/systemd/system/telegraf.service
owner: root
group: root
mode: '0644'
backup: yes
notify:
- reload systemd
- restart telegraf
when: telegraf_config_url is defined and telegraf_config_url != ''
- name: 生成 Telegraf 主配置文件(本地配置模式)
template:
src: telegraf.conf.j2
dest: /etc/telegraf/telegraf.conf
owner: telegraf
group: telegraf
mode: '0644'
backup: yes
notify: restart telegraf
when: telegraf_config_url is not defined or telegraf_config_url == ''
- name: 生成硬盘监控配置
template:
src: disk-monitoring.conf.j2
dest: /etc/telegraf/telegraf.d/disk-monitoring.conf
owner: telegraf
group: telegraf
mode: '0644'
backup: yes
notify: restart telegraf
- name: 生成系统监控配置
template:
src: system-monitoring.conf.j2
dest: /etc/telegraf/telegraf.d/system-monitoring.conf
owner: telegraf
group: telegraf
mode: '0644'
backup: yes
notify: restart telegraf
- name: 启用并启动 Telegraf 服务
systemd:
name: telegraf
state: started
enabled: yes
daemon_reload: yes
- name: 验证 Telegraf 状态
systemd:
name: telegraf
register: telegraf_status
- name: 检查 InfluxDB 连接
uri:
url: "{{ influxdb_url }}/ping"
method: GET
timeout: 5
register: influxdb_ping
ignore_errors: yes
delegate_to: localhost
run_once: true
- name: 显示 InfluxDB 连接状态
debug:
msg: "{{ '✅ InfluxDB 连接正常' if influxdb_ping.status == 204 else '❌ InfluxDB 连接失败,请检查配置' }}"
run_once: true
- name: 显示 Telegraf 状态
debug:
msg: "✅ Telegraf 状态: {{ telegraf_status.status.ActiveState }}"
- name: 检查硬盘使用情况
shell: |
df -h | grep -vE '^Filesystem|tmpfs|cdrom|udev' | awk '{print $5 " " $1 " " $6}' | while read output;
do
usage=$(echo $output | awk '{print $1}' | sed 's/%//g')
partition=$(echo $output | awk '{print $2}')
mount=$(echo $output | awk '{print $3}')
if [ $usage -ge {{ disk_usage_warning }} ]; then
echo "⚠️ 警告: $mount ($partition) 使用率 $usage%"
else
echo "✅ $mount ($partition) 使用率 $usage%"
fi
done
register: disk_check
changed_when: false
- name: 显示硬盘检查结果
debug:
msg: "{{ disk_check.stdout_lines }}"
handlers:
- name: reload systemd
systemd:
daemon_reload: yes
- name: restart telegraf
systemd:
name: telegraf
state: restarted

View File

@@ -0,0 +1,76 @@
---
- name: 安装并配置新的 Nomad Server 节点
hosts: influxdb1
become: yes
gather_facts: no
tasks:
- name: 更新包缓存
apt:
update_cache: yes
cache_valid_time: 3600
retries: 3
delay: 10
- name: 安装依赖包
apt:
name:
- wget
- curl
- unzip
- podman
- buildah
- skopeo
state: present
retries: 3
delay: 10
- name: 检查 Nomad 是否已安装
shell: which nomad || echo "not_found"
register: nomad_check
changed_when: false
- name: 下载并安装 Nomad
block:
- name: 下载 Nomad 1.10.5
get_url:
url: "https://releases.hashicorp.com/nomad/1.10.5/nomad_1.10.5_linux_amd64.zip"
dest: "/tmp/nomad.zip"
mode: '0644'
- name: 解压 Nomad
unarchive:
src: "/tmp/nomad.zip"
dest: "/usr/bin/"
remote_src: yes
owner: root
group: root
mode: '0755'
- name: 清理临时文件
file:
path: "/tmp/nomad.zip"
state: absent
when: nomad_check.stdout == "not_found"
- name: 验证 Nomad 安装
shell: nomad version
register: nomad_version_output
- name: 显示安装结果
debug:
msg: |
✅ 节点 {{ inventory_hostname }} 软件安装完成
📦 Podman: {{ ansible_facts.packages.podman[0].version if ansible_facts.packages.podman is defined else 'checking...' }}
🎯 Nomad: {{ nomad_version_output.stdout.split('\n')[0] }}
- name: 启用 Podman socket
systemd:
name: podman.socket
enabled: yes
state: started
ignore_errors: yes
- name: 继续完整配置
debug:
msg: "软件安装完成,现在将运行完整的 Nomad 配置..."

View File

@@ -0,0 +1,114 @@
---
- name: Setup Xfce desktop environment and Chrome Dev for browser automation
hosts: browser
become: yes
vars:
target_user: ben
tasks:
- name: Update package lists
apt:
update_cache: yes
cache_valid_time: 3600
- name: Install Xfce desktop environment
apt:
name:
- xfce4
- xfce4-goodies
- lightdm
- xorg
- dbus-x11
state: present
- name: Install additional useful packages for desktop environment
apt:
name:
- firefox-esr
- geany
- thunar-archive-plugin
- xfce4-terminal
- gvfs
- fonts-noto
- fonts-noto-cjk
state: present
- name: Download Google Chrome Dev .deb package
get_url:
url: https://dl.google.com/linux/direct/google-chrome-unstable_current_amd64.deb
dest: /tmp/google-chrome-unstable_current_amd64.deb
mode: '0644'
- name: Install Google Chrome Dev
apt:
deb: /tmp/google-chrome-unstable_current_amd64.deb
- name: Clean up downloaded .deb package
file:
path: /tmp/google-chrome-unstable_current_amd64.deb
state: absent
- name: Install Chrome automation dependencies
apt:
name:
- python3-pip
- python3-venv
- python3-dev
- build-essential
- libssl-dev
- libffi-dev
state: present
- name: Install Python packages for browser automation
pip:
name:
- selenium
- webdriver-manager
- pyvirtualdisplay
executable: pip3
- name: Set up Xfce as default desktop environment
copy:
dest: /etc/lightdm/lightdm.conf
content: |
[Seat:*]
autologin-user={{ target_user }}
autologin-user-timeout=0
autologin-session=xfce
user-session=xfce
- name: Ensure user is in necessary groups
user:
name: "{{ target_user }}"
groups:
- audio
- video
- input
- netdev
append: yes
- name: Create .xprofile for user
copy:
dest: /home/{{ target_user }}/.xprofile
content: |
# Start Xfce on login
startxfce4
owner: "{{ target_user }}"
group: "{{ target_user }}"
mode: '0644'
- name: Enable and start lightdm service
systemd:
name: lightdm
enabled: yes
state: started
- name: Display success message
debug:
msg: "Xfce desktop environment and Chrome Dev have been configured for user {{ target_user }} on {{ inventory_hostname }}"
handlers:
- name: restart lightdm
systemd:
name: lightdm
state: restarted

View File

@@ -0,0 +1,110 @@
# Kali Linux Ansible 测试套件
本目录包含用于测试Kali Linux系统的Ansible playbook集合。
## 测试Playbook列表
### 1. kali-health-check.yml
**用途**: Kali Linux快速健康检查
**描述**: 执行基本的系统状态检查包括系统信息、更新状态、磁盘空间、关键工具安装状态、网络连接、系统负载和SSH服务状态。
**运行方式**:
```bash
cd /root/mgmt/configuration
ansible-playbook -i inventories/production/inventory.ini playbooks/test/kali-health-check.yml
```
### 2. kali-security-tools.yml
**用途**: Kali Linux安全工具测试
**描述**: 专门测试各种Kali Linux安全工具的安装和基本功能包括
- Nmap
- Metasploit Framework
- Wireshark
- John the Ripper
- Hydra
- SQLMap
- Aircrack-ng
- Burp Suite
- Netcat
- Curl
**运行方式**:
```bash
cd /root/mgmt/configuration
ansible-playbook -i inventories/production/inventory.ini playbooks/test/kali-security-tools.yml
```
### 3. test-kali.yml
**用途**: Kali Linux完整系统测试
**描述**: 执行全面的系统测试,包括:
- 系统基本信息收集
- 网络连接测试
- 包管理器测试
- Kali工具检查
- 系统安全性检查
- 系统性能测试
- 网络工具测试
- 生成详细测试报告
**运行方式**:
```bash
cd /root/mgmt/configuration
ansible-playbook -i inventories/production/inventory.ini playbooks/test/test-kali.yml
```
### 4. kali-full-test-suite.yml
**用途**: Kali Linux完整测试套件
**描述**: 按顺序执行所有上述测试,提供全面的系统测试覆盖。
**运行方式**:
```bash
cd /root/mgmt/configuration
ansible-playbook playbooks/test/kali-full-test-suite.yml
```
## 测试结果
### 健康检查
- 直接在终端显示测试结果
- 无额外文件生成
### 安全工具测试
- 终端显示测试结果摘要
- 在Kali系统上生成 `/tmp/kali_security_tools_report.md` 报告文件
### 完整系统测试
- 终端显示测试进度
- 在Kali系统上生成 `/tmp/kali_test_results/` 目录,包含:
- `system_info.txt`: 系统基本信息
- `tool_check.txt`: Kali工具检查结果
- `security_check.txt`: 系统安全检查
- `performance.txt`: 系统性能信息
- `network_tools.txt`: 网络工具测试
- `kali_test.log`: 完整测试日志
- `README.md`: 测试报告摘要
## 前提条件
1. 确保Kali系统在inventory中正确配置
2. 确保Ansible可以连接到Kali系统
3. 确保有足够的权限在Kali系统上执行测试
## 注意事项
1. 某些测试可能需要网络连接
2. 完整系统测试可能需要较长时间
3. 测试结果文件会保存在Kali系统的临时目录中
4. 建议定期清理测试结果文件以节省磁盘空间
## 故障排除
如果测试失败,请检查:
1. 网络连接是否正常
2. Ansible inventory配置是否正确
3. SSH连接是否正常
4. Kali系统是否正常运行
5. 是否有足够的权限执行测试
## 自定义测试
您可以根据需要修改playbook中的测试内容或添加新的测试任务。所有playbook都使用模块化设计便于扩展和维护。

View File

@@ -0,0 +1,50 @@
---
- name: Kali Linux 完整测试套件
hosts: localhost
gather_facts: no
tasks:
- name: 显示测试开始信息
debug:
msg: "开始执行 Kali Linux 完整测试套件"
- name: 执行Kali快速健康检查
command: "ansible-playbook -i ../inventories/production/inventory.ini kali-health-check.yml"
args:
chdir: "/root/mgmt/configuration/playbooks/test"
register: health_check_result
- name: 显示健康检查结果
debug:
msg: "健康检查完成,退出码: {{ health_check_result.rc }}"
- name: 执行Kali安全工具测试
command: "ansible-playbook -i ../inventories/production/inventory.ini kali-security-tools.yml"
args:
chdir: "/root/mgmt/configuration/playbooks/test"
register: security_tools_result
- name: 显示安全工具测试结果
debug:
msg: "安全工具测试完成,退出码: {{ security_tools_result.rc }}"
- name: 执行Kali完整系统测试
command: "ansible-playbook -i ../inventories/production/inventory.ini test-kali.yml"
args:
chdir: "/root/mgmt/configuration/playbooks/test"
register: full_test_result
- name: 显示完整测试结果
debug:
msg: "完整系统测试完成,退出码: {{ full_test_result.rc }}"
- name: 显示测试完成信息
debug:
msg: |
Kali Linux 完整测试套件执行完成!
测试结果摘要:
- 健康检查: {{ '成功' if health_check_result.rc == 0 else '失败' }}
- 安全工具测试: {{ '成功' if security_tools_result.rc == 0 else '失败' }}
- 完整系统测试: {{ '成功' if full_test_result.rc == 0 else '失败' }}
详细测试结果请查看各测试生成的报告文件。

View File

@@ -0,0 +1,86 @@
---
- name: Kali Linux 快速健康检查
hosts: kali
become: yes
gather_facts: yes
tasks:
- name: 显示系统基本信息
debug:
msg: |
=== Kali Linux 系统信息 ===
主机名: {{ ansible_hostname }}
操作系统: {{ ansible_distribution }} {{ ansible_distribution_version }}
内核版本: {{ ansible_kernel }}
架构: {{ ansible_architecture }}
CPU核心数: {{ ansible_processor_vcpus }}
内存总量: {{ ansible_memtotal_mb }} MB
- name: 修复损坏的依赖关系
command: apt --fix-broken install -y
when: ansible_os_family == "Debian"
ignore_errors: yes
- name: 检查系统更新状态
apt:
update_cache: yes
upgrade: dist
check_mode: yes
register: update_check
changed_when: false
ignore_errors: yes
- name: 显示系统更新状态
debug:
msg: "{% if update_check.changed %}系统有可用更新{% else %}系统已是最新{% endif %}"
- name: 检查磁盘空间
command: "df -h /"
register: disk_space
- name: 显示根分区磁盘空间
debug:
msg: "根分区使用情况: {{ disk_space.stdout_lines[1] }}"
- name: 检查关键Kali工具
command: "which {{ item }}"
loop:
- nmap
- metasploit-framework
- wireshark
register: tool_check
ignore_errors: yes
changed_when: false
- name: 显示工具检查结果
debug:
msg: "{% for result in tool_check.results %}{{ result.item }}: {% if result.rc == 0 %}已安装{% else %}未安装{% endif %}{% endfor %}"
- name: 检查网络连接
uri:
url: https://httpbin.org/get
method: GET
timeout: 5
register: network_test
ignore_errors: yes
- name: 显示网络连接状态
debug:
msg: "{% if network_test.failed %}网络连接测试失败{% else %}网络连接正常{% endif %}"
- name: 检查系统负载
command: "uptime"
register: uptime
- name: 显示系统负载
debug:
msg: "系统负载: {{ uptime.stdout }}"
- name: 检查SSH服务状态
systemd:
name: ssh
register: ssh_service
- name: 显示SSH服务状态
debug:
msg: "SSH服务状态: {{ ssh_service.status.ActiveState }}"

View File

@@ -0,0 +1,228 @@
---
- name: Kali Linux 安全工具测试
hosts: kali
become: yes
gather_facts: yes
vars:
test_results: []
tasks:
- name: 初始化测试结果
set_fact:
test_results: []
- name: 测试Nmap
block:
- name: 检查Nmap是否安装
command: "which nmap"
register: nmap_check
ignore_errors: yes
changed_when: false
- name: 测试Nmap基本功能
command: "nmap -sn 127.0.0.1"
register: nmap_test
when: nmap_check.rc == 0
ignore_errors: yes
changed_when: false
- name: 记录Nmap测试结果
set_fact:
test_results: "{{ test_results + ['Nmap: ' + ('✓ 正常工作' if nmap_check.rc == 0 and nmap_test.rc == 0 else '✗ 未安装或异常')] }}"
- name: 测试Metasploit Framework
block:
- name: 检查Metasploit是否安装
command: "which msfconsole"
register: msf_check
ignore_errors: yes
changed_when: false
- name: 测试Metasploit版本
command: "msfconsole --version"
register: msf_version
when: msf_check.rc == 0
ignore_errors: yes
changed_when: false
- name: 记录Metasploit测试结果
set_fact:
test_results: "{{ test_results + ['Metasploit: ' + ('✓ 正常工作' if msf_check.rc == 0 else '✗ 未安装')] }}"
- name: 测试Wireshark
block:
- name: 检查Wireshark是否安装
command: "which wireshark"
register: wireshark_check
ignore_errors: yes
changed_when: false
- name: 检查tshark是否可用
command: "which tshark"
register: tshark_check
when: wireshark_check.rc == 0
ignore_errors: yes
changed_when: false
- name: 记录Wireshark测试结果
set_fact:
test_results: "{{ test_results + ['Wireshark: ' + ('✓ 正常工作' if wireshark_check.rc == 0 else '✗ 未安装')] }}"
- name: 测试John the Ripper
block:
- name: 检查John是否安装
command: "which john"
register: john_check
ignore_errors: yes
changed_when: false
- name: 测试John版本
command: "john --version"
register: john_version
when: john_check.rc == 0
ignore_errors: yes
changed_when: false
- name: 记录John测试结果
set_fact:
test_results: "{{ test_results + ['John the Ripper: ' + ('✓ 正常工作' if john_check.rc == 0 else '✗ 未安装')] }}"
- name: 测试Hydra
block:
- name: 检查Hydra是否安装
command: "which hydra"
register: hydra_check
ignore_errors: yes
changed_when: false
- name: 测试Hydra帮助
command: "hydra -h"
register: hydra_help
when: hydra_check.rc == 0
ignore_errors: yes
changed_when: false
- name: 记录Hydra测试结果
set_fact:
test_results: "{{ test_results + ['Hydra: ' + ('✓ 正常工作' if hydra_check.rc == 0 else '✗ 未安装')] }}"
- name: 测试SQLMap
block:
- name: 检查SQLMap是否安装
command: "which sqlmap"
register: sqlmap_check
ignore_errors: yes
changed_when: false
- name: 测试SQLMap版本
command: "sqlmap --version"
register: sqlmap_version
when: sqlmap_check.rc == 0
ignore_errors: yes
changed_when: false
- name: 记录SQLMap测试结果
set_fact:
test_results: "{{ test_results + ['SQLMap: ' + ('✓ 正常工作' if sqlmap_check.rc == 0 else '✗ 未安装')] }}"
- name: 测试Aircrack-ng
block:
- name: 检查Aircrack-ng是否安装
command: "which airmon-ng"
register: aircrack_check
ignore_errors: yes
changed_when: false
- name: 测试Aircrack-ng版本
command: "airmon-ng --version"
register: aircrack_version
when: aircrack_check.rc == 0
ignore_errors: yes
changed_when: false
- name: 记录Aircrack-ng测试结果
set_fact:
test_results: "{{ test_results + ['Aircrack-ng: ' + ('✓ 正常工作' if aircrack_check.rc == 0 else '✗ 未安装')] }}"
- name: 测试Burp Suite
block:
- name: 检查Burp Suite是否安装
command: "which burpsuite"
register: burp_check
ignore_errors: yes
changed_when: false
- name: 记录Burp Suite测试结果
set_fact:
test_results: "{{ test_results + ['Burp Suite: ' + ('✓ 正常工作' if burp_check.rc == 0 else '✗ 未安装')] }}"
- name: 测试Netcat
block:
- name: 检查Netcat是否安装
command: "which nc"
register: nc_check
ignore_errors: yes
changed_when: false
- name: 测试Netcat基本功能
command: "nc -z 127.0.0.1 22"
register: nc_test
when: nc_check.rc == 0
ignore_errors: yes
changed_when: false
- name: 记录Netcat测试结果
set_fact:
test_results: "{{ test_results + ['Netcat: ' + ('✓ 正常工作' if nc_check.rc == 0 else '✗ 未安装')] }}"
- name: 测试Curl
block:
- name: 检查Curl是否安装
command: "which curl"
register: curl_check
ignore_errors: yes
changed_when: false
- name: 测试Curl基本功能
command: "curl -s -o /dev/null -w '%{http_code}' https://httpbin.org/get"
register: curl_test
when: curl_check.rc == 0
ignore_errors: yes
changed_when: false
- name: 记录Curl测试结果
set_fact:
test_results: "{{ test_results + ['Curl: ' + ('✓ 正常工作' if curl_check.rc == 0 else '✗ 未安装')] }}"
- name: 显示所有测试结果
debug:
msg: |
=== Kali Linux 安全工具测试结果 ===
{% for result in test_results %}
{{ result }}
{% endfor %}
- name: 生成测试报告
copy:
content: |
# Kali Linux 安全工具测试报告
**测试时间**: {{ ansible_date_time.iso8601 }}
**测试主机**: {{ ansible_hostname }}
## 测试结果
{% for result in test_results %}
{{ result }}
{% endfor %}
## 建议
{% for result in test_results %}
{% if '✗' in result %}
- {{ result.split(':')[0] }} 未安装,可以使用以下命令安装: `sudo apt install {{ result.split(':')[0].lower().replace(' ', '-') }}`
{% endif %}
{% endfor %}
dest: "/tmp/kali_security_tools_report.md"

View File

@@ -0,0 +1,260 @@
---
- name: Kali Linux 系统测试
hosts: kali
become: yes
gather_facts: yes
vars:
test_results_dir: "/tmp/kali_test_results"
test_log_file: "{{ test_results_dir }}/kali_test.log"
tasks:
- name: 创建测试结果目录
file:
path: "{{ test_results_dir }}"
state: directory
mode: '0755'
- name: 初始化测试日志
copy:
content: "Kali Linux 系统测试日志 - {{ ansible_date_time.iso8601 }}\n\n"
dest: "{{ test_log_file }}"
- name: 记录系统基本信息
block:
- name: 获取系统信息
setup:
register: system_info
- name: 记录系统信息到日志
copy:
content: |
=== 系统基本信息 ===
主机名: {{ ansible_hostname }}
操作系统: {{ ansible_distribution }} {{ ansible_distribution_version }}
内核版本: {{ ansible_kernel }}
架构: {{ ansible_architecture }}
CPU核心数: {{ ansible_processor_vcpus }}
内存总量: {{ ansible_memtotal_mb }} MB
磁盘空间: {{ ansible_mounts | map(attribute='size_total') | sum | human_readable }}
dest: "{{ test_results_dir }}/system_info.txt"
- name: 记录到主日志
lineinfile:
path: "{{ test_log_file }}"
line: "[✓] 系统基本信息收集完成"
- name: 测试网络连接
block:
- name: 测试网络连通性
uri:
url: https://www.google.com
method: GET
timeout: 10
register: network_test
ignore_errors: yes
- name: 记录网络测试结果
lineinfile:
path: "{{ test_log_file }}"
line: "{% if network_test.failed %}[✗] 网络连接测试失败{% else %}[✓] 网络连接测试成功{% endif %}"
- name: 测试包管理器
block:
- name: 更新包列表
apt:
update_cache: yes
changed_when: false
- name: 记录包管理器测试结果
lineinfile:
path: "{{ test_log_file }}"
line: "[✓] APT包管理器工作正常"
- name: 检查Kali工具
block:
- name: 检查常见Kali工具是否安装
command: "which {{ item }}"
loop:
- nmap
- metasploit-framework
- wireshark
- john
- hydra
- sqlmap
- burpsuite
- aircrack-ng
register: tool_check
ignore_errors: yes
changed_when: false
- name: 记录工具检查结果
copy:
content: |
=== Kali工具检查结果 ===
{% for result in tool_check.results %}
{{ result.item }}: {% if result.rc == 0 %}已安装{% else %}未安装{% endif %}
{% endfor %}
dest: "{{ test_results_dir }}/tool_check.txt"
- name: 记录到主日志
lineinfile:
path: "{{ test_log_file }}"
line: "[✓] Kali工具检查完成"
- name: 测试系统安全性
block:
- name: 检查防火墙状态
command: "ufw status"
register: firewall_status
ignore_errors: yes
changed_when: false
- name: 检查SSH配置
command: "grep -E '^PermitRootLogin|^PasswordAuthentication' /etc/ssh/sshd_config"
register: ssh_config
ignore_errors: yes
changed_when: false
- name: 记录安全检查结果
copy:
content: |
=== 系统安全检查 ===
防火墙状态:
{{ firewall_status.stdout }}
SSH配置:
{{ ssh_config.stdout }}
dest: "{{ test_results_dir }}/security_check.txt"
- name: 记录到主日志
lineinfile:
path: "{{ test_log_file }}"
line: "[✓] 系统安全检查完成"
- name: 测试系统性能
block:
- name: 获取CPU使用率
command: "top -bn1 | grep 'Cpu(s)'"
register: cpu_usage
changed_when: false
- name: 获取内存使用情况
command: "free -h"
register: memory_usage
changed_when: false
- name: 获取磁盘使用情况
command: "df -h"
register: disk_usage
changed_when: false
- name: 记录性能测试结果
copy:
content: |
=== 系统性能信息 ===
CPU使用率:
{{ cpu_usage.stdout }}
内存使用情况:
{{ memory_usage.stdout }}
磁盘使用情况:
{{ disk_usage.stdout }}
dest: "{{ test_results_dir }}/performance.txt"
- name: 记录到主日志
lineinfile:
path: "{{ test_log_file }}"
line: "[✓] 系统性能测试完成"
- name: 测试网络工具
block:
- name: 测试ping命令
command: "ping -c 4 8.8.8.8"
register: ping_test
ignore_errors: yes
changed_when: false
- name: 测试nslookup命令
command: "nslookup google.com"
register: nslookup_test
ignore_errors: yes
changed_when: false
- name: 记录网络工具测试结果
copy:
content: |
=== 网络工具测试 ===
Ping测试结果:
{{ ping_test.stdout }}
NSlookup测试结果:
{{ nslookup_test.stdout }}
dest: "{{ test_results_dir }}/network_tools.txt"
- name: 记录到主日志
lineinfile:
path: "{{ test_log_file }}"
line: "[✓] 网络工具测试完成"
- name: 生成测试报告
block:
- name: 创建测试报告
copy:
content: |
# Kali Linux 系统测试报告
**测试时间**: {{ ansible_date_time.iso8601 }}
**测试主机**: {{ ansible_hostname }}
## 测试结果摘要
{% if network_test.failed %}- [✗] 网络连接测试失败{% else %}- [✓] 网络连接测试成功{% endif %}
- [✓] APT包管理器工作正常
- [✓] Kali工具检查完成
- [✓] 系统安全检查完成
- [✓] 系统性能测试完成
- [✓] 网络工具测试完成
## 详细结果
请查看以下文件获取详细测试结果:
- system_info.txt: 系统基本信息
- tool_check.txt: Kali工具检查结果
- security_check.txt: 系统安全检查
- performance.txt: 系统性能信息
- network_tools.txt: 网络工具测试
- kali_test.log: 完整测试日志
## 建议
{% for result in tool_check.results %}
{% if result.rc != 0 %}
- 建议安装 {{ result.item }} 工具: `sudo apt install {{ result.item }}`
{% endif %}
{% endfor %}
dest: "{{ test_results_dir }}/README.md"
- name: 记录到主日志
lineinfile:
path: "{{ test_log_file }}"
line: "[✓] 测试报告生成完成"
- name: 显示测试结果位置
debug:
msg: "Kali Linux 系统测试完成!测试结果保存在 {{ test_results_dir }} 目录中"
- name: 显示测试日志最后几行
command: "tail -10 {{ test_log_file }}"
register: log_tail
- name: 输出测试日志摘要
debug:
msg: "{{ log_tail.stdout_lines }}"