로컬 환경과 상용 서버에서 Kubernetes 클러스터에 접근하는 방법을 구분할 수 있어. 각각의 경우에 맞는 설정 방법을 정리해줄게.

1. 로컬 맥북 환경


로컬 환경에서 Docker Desktop의 Kubernetes 클러스터에 접근하려면 kubeconfig 파일을 사용해야 해. Jenkins 파이프라인에서 withCredentials 블록을 사용하여 kubeconfig 파일을 참조하도록 설정해.

Jenkinsfile 예시 (로컬 맥북)

pipeline {
    agent any

    stages {
        stage('Checkout') {
            steps {
                git '<https://your-repository-url.git>'
            }
        }
        stage('Build and Push Image') {
            steps {
                script {
                    sh './gradlew jib'
                }
            }
        }
        stage('Deploy to Kubernetes') {
            steps {
                script {
                    withCredentials([file(credentialsId: 'k8s-kubeconfig', variable: 'KUBECONFIG')]) {
                        sh 'kubectl apply -f k8s/spring-app-deployment.yaml'
                    }
                }
            }
        }
    }

    post {
        always {
            cleanWs()
        }
    }
}

근데 배포 단계에서 variable : ‘KUBECONFIG’ 가 뭐야?


withCredentials 블록에서 설정한 KUBECONFIG 환경 변수는 Jenkins 파이프라인 내에서 해당 자격 증명 파일(kubeconfig 파일)의 경로를 가리키게 돼. kubectl 명령어는 이 환경 변수를 사용하여 Kubernetes 클러스터에 접근할 수 있어.

실제로 KUBECONFIG 변수 사용

stage('Deploy to Kubernetes') {
    steps {
        script {
            withCredentials([file(credentialsId: 'k8s-kubeconfig', variable: 'KUBECONFIG')]) {
                sh 'kubectl apply -f k8s/spring-app-deployment.yaml'
            }
        }
    }
}

kubectl 명령어가 KUBECONFIG를 사용하는 방법