#!/usr/bin/env python3 import yaml import sys import os # 读取变量文件 config_file = 'config/cluster-vars.yml' if not os.path.exists(config_file): print(f"错误: 配置文件不存在: {config_file}") sys.exit(1) with open(config_file, 'r') as f: config = yaml.safe_load(f) # 生成inventory (k3s-ansible需要server和agent组) inventory = "[server]\n" for node in config['master_nodes']: line = f"{node['private_ip']} ansible_host={node['public_ip']} ansible_user={node['ssh_user']}" # 支持密码认证 if 'ssh_password' in node: line += f" ansible_ssh_pass={node['ssh_password']} ansible_become_pass={node['ssh_password']}" elif 'ssh_key_path' in node: line += f" ansible_ssh_private_key_file={node['ssh_key_path']}" inventory += line + "\n" inventory += "\n[agent]\n" for node in config['worker_nodes']: line = f"{node['private_ip']} ansible_host={node['public_ip']} ansible_user={node['ssh_user']}" if 'ssh_password' in node: line += f" ansible_ssh_pass={node['ssh_password']} ansible_become_pass={node['ssh_password']}" elif 'ssh_key_path' in node: line += f" ansible_ssh_private_key_file={node['ssh_key_path']}" inventory += line + "\n" inventory += "\n[k3s_cluster:children]\nserver\nagent\n" inventory += "\n[k3s_cluster:vars]\n" inventory += "ansible_python_interpreter=/usr/bin/python3\n" inventory += f"k3s_version={config.get('k3s_version', 'v1.28.5+k3s1')}\n" inventory += f"token={config.get('k3s_token', 'changeme!')}\n" # 使用master节点的内网IP作为API endpoint master_private_ip = config['master_nodes'][0]['private_ip'] inventory += f"api_endpoint={master_private_ip}\n" inventory += "flannel_iface=eth0\n" # 写入inventory文件 output_file = 'k3s-ansible/inventory/hosts.ini' with open(output_file, 'w') as f: f.write(inventory) print(f"✓ Inventory生成成功: {output_file}")