Skip to main content
In this guide, you’ll learn how to inject your Kubernetes kubeconfig into a GitLab CI pipeline so that kubectl can authenticate and interact with your cluster. This setup is essential for automated deployments, health checks, and infrastructure management within your CI/CD workflows.

Why You Need to Provide a Kubeconfig

When kubectl runs without a valid kubeconfig, it can only display client information and will fail to contact the API server:
Attempting to run the job yields:
Without server credentials in a kubeconfig, kubectl cannot reach your cluster’s API endpoint.

Local vs. CI: Kubernetes Authentication

On Your Local Machine

With a valid ~/.kube/config, you will see both client and server versions:
Your trimmed kubeconfig might look like this:
Verify your context and nodes locally:

Storing Kubeconfig in GitLab CI/CD

To securely pass your kubeconfig into CI jobs, add it as a File-type variable in your project’s CI/CD Settings:
The image shows a GitLab CI/CD settings page where variables are being managed, with options to add a new variable and configure its type and flags.
Treat your kubeconfig as sensitive data. File variables are stored encrypted, but avoid exposing them in job logs or unsecured scopes.

Updating the CI Job to Use Kubeconfig

Modify your .gitlab-ci.yml job to export the KUBECONFIG environment variable from the File variable before invoking any kubectl commands:
Commit your changes and trigger the pipeline. The k8s_dev_deploy job should now complete successfully:
The image shows a GitLab CI/CD job interface where a job named "k8s_dev_deploy" has successfully passed. The job log details the steps executed, and the interface includes project navigation options on the left.

Verifying the CI Job Output

With the kubeconfig in place, your CI job will display both client and server details and list the cluster nodes:

Further Reading and References

Watch Video