--- build: stage: build image: docker:19.03.0 services: - docker:19.03.0-dind script: - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY - docker build --tag=$CI_REGISTRY_IMAGE/$CI_COMMIT_REF_SLUG . - docker push $CI_REGISTRY_IMAGE/$CI_COMMIT_REF_SLUG # Common base for jobs that deploy to k8s .deploy-base: # For deploying, we need an image that can interact with k8s. Using # GitLab's own official image for this should be safe enough: image: registry.gitlab.com/gitlab-org/cluster-integration/helm-install-image/releases/2.16.6-kube-1.13.12 variables: # Define k8s namespace and domain used for deployment: NS: $CI_COMMIT_REF_SLUG CI_ENVIRONMENT_DOMAIN: $CI_COMMIT_REF_SLUG.$KUBE_INGRESS_BASE_DOMAIN only: refs: # Deploy only branches and tags: - branches - tags # Deploy only if k8s integration is actually set up: kubernetes: active # Job that deploys the app to k8s: deploy:branch: stage: deploy extends: .deploy-base environment: name: $CI_COMMIT_REF_SLUG url: http://$CI_COMMIT_REF_SLUG.$KUBE_INGRESS_BASE_DOMAIN on_stop: deploy:stop_branch before_script: - apk add gettext script: # Create dedicated namespace to deploy in (delete first, if it already exists): - kubectl get namespace $NS && kubectl delete namespace $NS || true - kubectl create namespace $NS # Make Docker credentials available for deployment: - kubectl -n $NS create secret docker-registry gitlab-registry --docker-server="$CI_REGISTRY" --docker-username="$CI_REGISTRY_USER" --docker-password="$CI_REGISTRY_PASSWORD" - kubectl -n $NS patch serviceaccount default -p '{"imagePullSecrets":[{"name":"gitlab-registry"}]}' # Start and expose deployment, set up ingress: - kubectl -n $NS create deployment myapp --image=$CI_REGISTRY_IMAGE/$CI_COMMIT_REF_SLUG - kubectl -n $NS expose deployment/myapp --type=NodePort --port 3000 # Set up ingress with env var expansion from template: - envsubst < k8s/ingress.yml.tpl | kubectl -n $NS apply -f - # Wait for pod - kubectl -n $NS wait --for=condition=available deployment/myapp --timeout=180s # Job that destroys the k8s namespace used to deploy the app. This gets # triggered when the environment is stopped (e.g., when the branch is deleted) deploy:stop_branch: stage: deploy extends: .deploy-base when: manual # This job must not have any dependencies, otherwise it will refuse to run # when the artifact retention of previous jobs has expired: dependencies: [] environment: name: $CI_COMMIT_REF_SLUG action: stop variables: # Disable checkout here because the ref might not be available anymore GIT_STRATEGY: none script: - kubectl delete namespace $NS