如何在 Jenkinsfile 中使用 kubectl sh 在 Kubernetes 上部署

How to deploy on Kubernetes using kubectl sh in Jenkinsfile

我正在尝试创建一个在 git 中提交后触发的管道。我已经使用 kvm2 驱动程序安装了 minikube。但是我不确定是否一切都按预期设置。 之前已经安装了 Jenkins,但它没有 运行 在 kubernetes 上。

下面是我的 Jenkinsfile。

pipeline {

    environment {
        ....
    }

    agent any

    stages {

        stage ('Clone') {
            ....
        }

        stage('Build') {
            ....
        }

        stage(‘Containerize’) {
            .... build images with docker
        }

        stage('Deploy Image') {
            .... push images on Docker hub
        }

        stage('Deploy Application') {
            steps {
                // Create namespace if it doesn't exist
                sh("kubectl get ns development || kubectl create ns development")
               .... 
            }
        }
    }
}

我还将 Kubernetes 配置为 Cloud。我添加了 kubernetes URL 作为 ./kube/config 中的展示 kubernetes 服务器证书作为 /.minikube/ca.crt 的内容 使用

创建的凭据
sudo openssl pkcs12 -export -out kubernetes.pfx -inkey apiserver.key -in apiserver.crt -certfile ca.crt -passout pass:jenkins

我遇到的问题是:

[Pipeline] { (Deploy Application)
[Pipeline] sh
+ kubectl get ns development
The connection to the server localhost:8080 was refused - did you specify the right host or port?

这跟RBAC有关系吗?我尝试使用 kubectl create serviceaccount jenkins 使用秘密令牌并复制令牌,但是当我测试连接时它不起作用。

我不确定这是否是在 Kubernetes 上使用 管道。 请建议是否有更好的方法来部署我的微服务。

  • 部署到 kubernetes 的方法有很多,请使用更适合您的方法

  • 以上错误与集群的address/API端点有关,因此无法找到您的集群,您需要在合适的位置提供kubeconfig或使用其他方式连接到集群

类似于:

kubectl --kubeconfig=/path/to/kubeconfig-file get ns development || kubectl --kubeconfig=/path/to/kubeconfig-file  create ns development")

一如既往,请手动尝试 运行 这些命令并确保它们在将它们放入 automation/pipeline

之前有效