Files
xgj/setup-env/scripts/setup-kubectl.sh

68 lines
1.2 KiB
Bash
Executable File
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.

#!/bin/bash
set -euo pipefail
# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# 输出函数
log_info() {
echo -e "${BLUE} $1${NC}"
}
log_success() {
echo -e "${GREEN}$1${NC}"
}
log_warning() {
echo -e "${YELLOW}⚠️ $1${NC}"
}
log_error() {
echo -e "${RED}$1${NC}"
}
# 配置 kubectl
setup_kubectl_config() {
log_info "配置 kubectl..."
# 检查环境变量
if [[ -z "${KUBE_CONFIG_BASE64:-}" ]]; then
log_error "KUBE_CONFIG_BASE64 环境变量未设置"
exit 1
fi
# 创建 .kube 目录
mkdir -p "$HOME/.kube"
# 解码并写入配置文件
echo "$KUBE_CONFIG_BASE64" | base64 -d > "$HOME/.kube/config"
# 设置正确的权限
chmod 600 "$HOME/.kube/config"
log_success "kubectl 配置文件已创建"
# 验证配置文件格式
if ! kubectl config view --minify >/dev/null 2>&1; then
log_error "kubectl 配置文件格式无效"
exit 1
fi
log_success "kubectl 配置验证通过"
}
# 主函数
main() {
setup_kubectl_config
}
# 错误处理
trap 'log_error "kubectl 配置失败,退出码: $?"' ERR
# 执行主函数
main "$@"