You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jenkins中切换AWS账户并动态获取对应K8s命名空间?

解决Jenkins Active Choice参数动态切换AWS账户并获取K8s命名空间的问题

你遇到的核心问题是:Active Choice参数的Groovy脚本无法使用Pipeline的withAWS步骤(毕竟参数初始化阶段不属于Pipeline运行阶段,那些Pipeline专属步骤在这里不生效),而且当前脚本缺少切换AWS账户/集群上下文的逻辑,导致不管选哪个环境,kubectl都只会用Jenkins节点默认的配置。

下面是具体的解决方案,我会一步步给你说明修改思路和代码:

核心思路

在Groovy脚本中直接通过aws-cli命令完成以下操作:

  1. 根据选中的CLUSTER_NAME切换到对应的AWS账户/集群
  2. 更新本地kubeconfig到目标集群
  3. 执行kubectl命令获取命名空间

前提是你的Jenkins节点已经安装了aws-cli和kubectl,并且具备访问对应AWS集群的权限(建议用Jenkins凭证管理安全存储AWS密钥,别硬编码在脚本里)。

修改后的参数配置脚本

把你原来的CascadeChoiceParameter中的script部分替换成下面的代码:

if (CLUSTER_NAME.equals("development")) {
    // 1. 从Jenkins凭证库中获取development环境的AWS密钥
    def devCreds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
        com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl.class,
        Jenkins.instance,
        null,
        null
    ).find { it.id == "aws-dev-creds" }
    
    // 2. 设置临时环境变量,让aws-cli使用dev环境的凭证
    env.AWS_ACCESS_KEY_ID = devCreds.accessKey
    env.AWS_SECRET_ACCESS_KEY = devCreds.secretKey
    
    // 3. 更新kubeconfig到development集群(替换成你的EKS集群名称和区域)
    "aws eks update-kubeconfig --name dev-eks-cluster --region us-east-1".execute()
} else if (CLUSTER_NAME.equals("pre-prod")) {
    // 同理配置pre-prod环境的凭证和集群
    def preProdCreds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
        com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl.class,
        Jenkins.instance,
        null,
        null
    ).find { it.id == "aws-preprod-creds" }
    
    env.AWS_ACCESS_KEY_ID = preProdCreds.accessKey
    env.AWS_SECRET_ACCESS_KEY = preProdCreds.secretKey
    
    "aws eks update-kubeconfig --name preprod-eks-cluster --region us-east-1".execute()
}

// 4. 获取当前集群的命名空间,可选过滤系统命名空间
def getNamespacesCmd = "kubectl get namespaces -o jsonpath={.items[*].metadata.name}"
def namespaces = getNamespacesCmd.execute().in.text.split().toList()
namespaces = namespaces.findAll { !it.startsWith("kube-") && !it.equals("default") }
return namespaces ?: ["No namespaces found"]

关键说明

  • 安全存储凭证:用Jenkins凭证管理存储AWS密钥,通过凭证ID查找对应的凭证,完全避免硬编码,安全性拉满。
  • 切换集群上下文:aws eks update-kubeconfig命令会自动把目标集群设为当前kubectl的默认上下文,确保后续kubectl命令指向正确的集群。
  • 临时环境变量:脚本中设置的AWS密钥只会在当前参数脚本的执行周期内生效,不会影响Jenkins节点的全局配置。
  • 可选过滤:最后过滤系统命名空间的步骤可以根据你的需求调整,不需要的话直接删掉即可。

额外注意事项

  1. 确保Jenkins节点的aws-cli版本足够新,支持eks update-kubeconfig命令。
  2. 给运行脚本的Jenkins节点权限:在全局安全配置中,允许Groovy脚本调用凭证相关的API。
  3. 如果你的集群不是EKS,可以替换成对应的kubeconfig获取方式,比如从S3下载kubeconfig文件等。

内容的提问来源于stack exchange,提问作者FreedomOnce

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:09:35