Using Gitlab+Kubernetes, how to deploy something to a specific (e.g. test) namespace? I’ve followed the Gitlab doc, but I can’t find how to select a specific namespace when deploying.
This .gitlab-ci.yml
file…
stages:
- deploy
deploy:
stage: deploy
tags: [local]
environment:
name: test
kubernetes:
namespace: test
script:
- kubectl config get-contexts
- kubectl apply -f nginx.yaml
- kubectl get pods --namespace deploy-2-test
- kubectl apply -f nginx.yaml --namespace test
…produces this result:
on rap N37D1QxB
Preparing the "shell" executor 00:00
Using Shell executor...
Preparing environment 00:00
... [everything fine until here]
Executing "step_script" stage of the job script 00:00
$ kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
* gitlab-deploy gitlab-deploy gitlab-deploy deploy-2-test
$ kubectl apply -f nginx.yaml
deployment.apps/nginx-deployment created
$ kubectl get pods --namespace deploy-2-test
NAME READY STATUS RESTARTS AGE
nginx-deployment-66b6c48dd5-4lx4s 0/1 ContainerCreating 0 0s
nginx-deployment-66b6c48dd5-dcpcr 0/1 ContainerCreating 0 0s
$ kubectl apply -f nginx.yaml --namespace test
Error from server (Forbidden): error when retrieving current configuration of:
Resource: "apps/v1, Resource=deployments", GroupVersionKind: "apps/v1, Kind=Deployment"
Name: "nginx-deployment", Namespace: "test"
from server for: "nginx.yaml": deployments.apps "nginx-deployment" is forbidden: User "system:serviceaccount:deploy-2-test:deploy-2-test-service-account" cannot get resource "deployments" in API group "apps" in the namespace "test"
Cleaning up file based variables 00:00
ERROR: Job failed: exit status 1
- Notice that the deployment is done on the deploy-2-test namespace, even if the .gitlab-ci.yml file points to the test namespace; and if the
--namespace
is included in the deploy command, there’s no right to deploy. - Following the Gitlab doc, I’ve added the cluster-admin Cluster Role
to the gitlab ServiceAccount, which should be allmighty…
The nginx deployment is the classic one. How to deploy to the test namespace? why and how is the namespace deploy-2-test generated?
3
Answers
Found the solution: just disable the option
GitLab-managed cluster
in the Gitlab cluster definition page.Excerpt from the output:
Effectively, the
deploy.environment.kubernetes.namespace
is the one defining the final k8s namespace.I’m not 100% sure, but setting the
environment:kubernetes:namespace
setting might not change your current context. It only applies that value to theKUBE_NAMESPACE
environment variable.If you want to be sure you can always use
--namespace $KUBE_NAMESPACE
in your scripts. That’s what we do too, to prevent any context issues with our scripts.Per the instructions, there’s a – kubectl config use-context line missing from your script after – kubectl config get-contexts. With this in place, –namespace works for me.