解决AWS Lambda(Node.js)调用EKS获取Pod时的ECONNREFUSED错误
解决AWS Lambda连接EKS时的ECONNREFUSED错误(localhost:8080)
你的问题出在kc.loadFromDefault()调用上——Lambda运行环境里没有默认的kubeconfig文件,客户端找不到有效配置时会自动 fallback 到本地集群地址http://localhost:8080,导致连接失败。下面是具体修复步骤和代码:
核心修复步骤
1. 手动构建EKS集群的kubeconfig
不要依赖默认加载逻辑,直接通过AWS SDK获取EKS集群的API端点和证书,结合Lambda的IAM角色完成身份验证。
2. 确认网络连通性
虽然Lambda和EKS在同一VPC,仍需检查:
- EKS集群的安全组允许Lambda所在安全组的出站流量访问EKS API的443端口
- 若为私有EKS集群,Lambda所在子网需通过VPC端点访问EKS;若为公有集群,子网需配置NAT网关或具备互联网访问能力
3. 补全必要权限
除已有的AmazonEKSClusterPolicy和AmazonEKSWorkerNodePolicy,需确保:
- Lambda角色拥有
eks:DescribeCluster权限(用于获取集群信息) - 通过EKS的RBAC绑定,给该IAM角色授予查看Pod的权限(比如绑定
view集群角色)
修正后的代码示例
const k8s = require('@kubernetes/client-node'); const AWS = require('aws-sdk'); exports.handler = async (event, context) => { try { // 初始化EKS客户端 const eks = new AWS.EKS(); const clusterName = '你的EKS集群名称'; // 替换为实际集群名 // 获取EKS集群的API端点和证书 const clusterData = await eks.describeCluster({ name: clusterName }).promise(); const clusterEndpoint = clusterData.cluster.endpoint; const clusterCertAuthority = clusterData.cluster.certificateAuthority.data; // 手动构建kubeconfig配置 const kc = new k8s.KubeConfig(); kc.loadFromOptions({ clusters: [ { name: clusterName, server: clusterEndpoint, caData: clusterCertAuthority } ], users: [ { name: clusterName, user: { exec: { apiVersion: 'client.authentication.k8s.io/v1beta1', command: 'aws-iam-authenticator', args: ['token', '-i', clusterName] } } } ], contexts: [ { name: clusterName, user: clusterName, cluster: clusterName } ], currentContext: clusterName }); // 创建K8s API客户端 const k8sApi = kc.makeApiClient(k8s.CoreV1Api); // 批量获取多个Namespace的Pod详情(示例:kube-system和default) const targetNamespaces = ['kube-system', 'default']; const podResults = await Promise.all( targetNamespaces.map(ns => k8sApi.listNamespacedPod(ns)) ); // 整理返回结果,只保留关键信息 const formattedResult = targetNamespaces.reduce((acc, ns, index) => { acc[ns] = podResults[index].body.items.map(pod => ({ podName: pod.metadata.name, status: pod.status.phase, nodeName: pod.spec.nodeName })); return acc; }, {}); return { statusCode: 200, body: JSON.stringify(formattedResult) }; } catch (error) { console.error('获取Pod详情失败:', error); return { statusCode: 500, body: JSON.stringify({ error: error.message }) }; } };
额外注意事项
- 确保Lambda部署包或层包含
@kubernetes/client-node依赖(AWS SDK在Lambda环境默认提供) - 若使用新版AWS IAM Authenticator,可将
apiVersion替换为client.authentication.k8s.io/v1 - 绑定K8s RBAC权限示例(通过kubectl):
kubectl create clusterrolebinding lambda-eks-view \ --clusterrole=view \ --user=arn:aws:iam::你的AWS账号ID:role/你的Lambda角色名
内容的提问来源于stack exchange,提问作者user28442653
相关产品推荐
相关产品推荐

