Skip to content

Instantly share code, notes, and snippets.

@joshuaquek
Last active May 31, 2021 15:23
Show Gist options
  • Save joshuaquek/1774b64b667bdefe62b96df35b6e0318 to your computer and use it in GitHub Desktop.
Save joshuaquek/1774b64b667bdefe62b96df35b6e0318 to your computer and use it in GitHub Desktop.
# 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:
# Deploy only branches and tags:
refs:
- branches
- tags
# Deploy only if k8s integration is configured:
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 either manually or when the environment is stopped (e.g., when an
# MR is merged):
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
Summary: How to deploy to Kubernetes using a Gitlab.com managed Kubernetes Cluster
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment