Auto-DevOps.gitlab-ci.yml 26 KB
Newer Older
1 2 3 4 5 6 7 8 9
# Auto DevOps
# This CI/CD configuration provides a standard pipeline for
# * building a Docker image (using a buildpack if necessary),
# * storing the image in the container registry,
# * running tests from a buildpack,
# * running code quality analysis,
# * creating a review app for each topic branch,
# * and continuous deployment to production
#
10 11 12
# Test jobs may be disabled by setting environment variables:
# * test: TEST_DISABLED
# * code_quality: CODE_QUALITY_DISABLED
13
# * license_management: LICENSE_MANAGEMENT_DISABLED
14 15 16 17 18 19 20 21
# * performance: PERFORMANCE_DISABLED
# * sast: SAST_DISABLED
# * dependency_scanning: DEPENDENCY_SCANNING_DISABLED
# * container_scanning: CONTAINER_SCANNING_DISABLED
# * dast: DAST_DISABLED
# * review: REVIEW_DISABLED
# * stop_review: REVIEW_DISABLED
#
22 23
# In order to deploy, you must have a Kubernetes cluster configured either
# via a project integration, or via group/project variables.
24 25
# KUBE_INGRESS_BASE_DOMAIN must also be set on the cluster settings,
# as a variable at the group or project level, or manually added below.
26
#
27
# Continuous deployment to production is enabled by default.
28 29
# If you want to deploy to staging first, set STAGING_ENABLED environment variable.
# If you want to enable incremental rollout, either manual or time based,
30
# set INCREMENTAL_ROLLOUT_MODE environment variable to "manual" or "timed".
31
# If you want to use canary deployments, set CANARY_ENABLED environment variable.
32 33 34 35 36 37 38 39 40 41 42 43
#
# If Auto DevOps fails to detect the proper buildpack, or if you want to
# specify a custom buildpack, set a project variable `BUILDPACK_URL` to the
# repository URL of the buildpack.
# e.g. BUILDPACK_URL=https://github.com/heroku/heroku-buildpack-ruby.git#v142
# If you need multiple buildpacks, add a file to your project called
# `.buildpacks` that contains the URLs, one on each line, in order.
# Note: Auto CI does not work with multiple buildpacks yet

image: alpine:latest

variables:
44 45
  # KUBE_INGRESS_BASE_DOMAIN is the application deployment domain and should be set as a variable at the group or project level.
  # KUBE_INGRESS_BASE_DOMAIN: domain.example.com
46 47 48 49 50

  POSTGRES_USER: user
  POSTGRES_PASSWORD: testing-password
  POSTGRES_ENABLED: "true"
  POSTGRES_DB: $CI_ENVIRONMENT_SLUG
51
  POSTGRES_VERSION: 9.6.2
52

Thong Kuah's avatar
Thong Kuah committed
53
  KUBERNETES_VERSION: 1.11.7
Thong Kuah's avatar
Thong Kuah committed
54
  HELM_VERSION: 2.12.3
55

56 57
  DOCKER_DRIVER: overlay2

58 59
  ROLLOUT_RESOURCE_TYPE: deployment

60 61 62 63
stages:
  - build
  - test
  - review
64
  - dast
65 66 67
  - staging
  - canary
  - production
68 69 70 71
  - incremental rollout 10%
  - incremental rollout 25%
  - incremental rollout 50%
  - incremental rollout 100%
72
  - performance
73 74 75 76
  - cleanup

build:
  stage: build
77
  image: "registry.gitlab.com/gitlab-org/cluster-integration/auto-build-image/master:stable"
78
  services:
79
    - docker:stable-dind
80
  script:
81
    - /build/build.sh
82 83
  only:
    - branches
Aaron Walker's avatar
Aaron Walker committed
84
    - tags
85 86 87 88 89 90 91 92 93 94 95 96 97 98

test:
  services:
    - postgres:latest
  variables:
    POSTGRES_DB: test
  stage: test
  image: gliderlabs/herokuish:latest
  script:
    - setup_test_db
    - cp -R . /tmp/app
    - /bin/herokuish buildpack test
  only:
    - branches
Aaron Walker's avatar
Aaron Walker committed
99
    - tags
100 101 102
  except:
    variables:
      - $TEST_DISABLED
103

104
code_quality:
105
  stage: test
106
  image: docker:stable
107 108
  allow_failure: true
  services:
109
    - docker:stable-dind
110 111
  script:
    - setup_docker
112
    - code_quality
113
  artifacts:
114
    paths: [gl-code-quality-report.json]
115 116
  only:
    - branches
Aaron Walker's avatar
Aaron Walker committed
117
    - tags
118 119 120
  except:
    variables:
      - $CODE_QUALITY_DISABLED
121

122
license_management:
123
  stage: test
124
  image:
125 126
    name: "registry.gitlab.com/gitlab-org/security-products/license-management:$CI_SERVER_VERSION_MAJOR-$CI_SERVER_VERSION_MINOR-stable"
    entrypoint: [""]
127 128 129 130 131
  allow_failure: true
  script:
    - license_management
  artifacts:
    paths: [gl-license-management-report.json]
132
  only:
133 134
    refs:
      - branches
Aaron Walker's avatar
Aaron Walker committed
135
      - tags
136 137
    variables:
      - $GITLAB_FEATURES =~ /\blicense_management\b/
138 139 140 141
  except:
    variables:
      - $LICENSE_MANAGEMENT_DISABLED

142 143
performance:
  stage: performance
144
  image: docker:stable
145 146
  allow_failure: true
  services:
147
    - docker:stable-dind
148
  script:
149
    - setup_docker
150 151 152 153
    - performance
  artifacts:
    paths:
    - performance.json
154
    - sitespeed-results/
155 156 157
  only:
    refs:
      - branches
158
      - tags
159
    kubernetes: active
160 161 162
  except:
    variables:
      - $PERFORMANCE_DISABLED
163

164
sast:
165
  stage: test
166
  image: docker:stable
167
  allow_failure: true
168
  services:
169
    - docker:stable-dind
170
  script:
171 172
    - setup_docker
    - sast
173
  artifacts:
174 175
    reports:
      sast: gl-sast-report.json
176
  only:
177 178
    refs:
      - branches
Aaron Walker's avatar
Aaron Walker committed
179
      - tags
180 181
    variables:
      - $GITLAB_FEATURES =~ /\bsast\b/
182 183 184
  except:
    variables:
      - $SAST_DISABLED
185

186
dependency_scanning:
187
  stage: test
188 189 190 191 192 193 194 195
  image: docker:stable
  allow_failure: true
  services:
    - docker:stable-dind
  script:
    - setup_docker
    - dependency_scanning
  artifacts:
196 197
    reports:
      dependency_scanning: gl-dependency-scanning-report.json
198
  only:
199 200
    refs:
      - branches
Aaron Walker's avatar
Aaron Walker committed
201
      - tags
202 203
    variables:
      - $GITLAB_FEATURES =~ /\bdependency_scanning\b/
204 205 206
  except:
    variables:
      - $DEPENDENCY_SCANNING_DISABLED
207

208
container_scanning:
209
  stage: test
210
  image: docker:stable
Luke Bennett's avatar
Luke Bennett committed
211 212
  allow_failure: true
  services:
213
    - docker:stable-dind
Luke Bennett's avatar
Luke Bennett committed
214 215
  script:
    - setup_docker
216
    - container_scanning
Luke Bennett's avatar
Luke Bennett committed
217
  artifacts:
218
    paths: [gl-container-scanning-report.json]
219
  only:
220 221
    refs:
      - branches
Aaron Walker's avatar
Aaron Walker committed
222
      - tags
223
    variables:
224
      - $GITLAB_FEATURES =~ /\bcontainer_scanning\b/
225 226 227
  except:
    variables:
      - $CONTAINER_SCANNING_DISABLED
228

229 230 231
dast:
  stage: dast
  allow_failure: true
232
  image: registry.gitlab.com/gitlab-org/security-products/zaproxy
233 234 235 236 237 238 239 240 241
  variables:
    POSTGRES_DB: "false"
  script:
    - dast
  artifacts:
    paths: [gl-dast-report.json]
  only:
    refs:
      - branches
242
      - tags
243
    kubernetes: active
244 245
    variables:
      - $GITLAB_FEATURES =~ /\bdast\b/
246
  except:
247 248 249 250
    refs:
      - master
    variables:
      - $DAST_DISABLED
251

252 253 254 255 256 257 258
review:
  stage: review
  script:
    - check_kube_domain
    - install_dependencies
    - download_chart
    - ensure_namespace
259
    - initialize_tiller
260 261
    - create_secret
    - deploy
262
    - persist_environment_url
263 264
  environment:
    name: review/$CI_COMMIT_REF_NAME
265
    url: http://$CI_PROJECT_ID-$CI_ENVIRONMENT_SLUG.$KUBE_INGRESS_BASE_DOMAIN
266
    on_stop: stop_review
267 268
  artifacts:
    paths: [environment_url.txt]
269 270 271
  only:
    refs:
      - branches
272
      - tags
273
    kubernetes: active
274
  except:
275 276 277 278
    refs:
      - master
    variables:
      - $REVIEW_DISABLED
279 280 281 282 283 284 285

stop_review:
  stage: cleanup
  variables:
    GIT_STRATEGY: none
  script:
    - install_dependencies
286
    - initialize_tiller
287 288 289 290 291 292 293 294 295
    - delete
  environment:
    name: review/$CI_COMMIT_REF_NAME
    action: stop
  when: manual
  allow_failure: true
  only:
    refs:
      - branches
296
      - tags
297
    kubernetes: active
298
  except:
299 300 301 302
    refs:
      - master
    variables:
      - $REVIEW_DISABLED
303 304 305 306

# Staging deploys are disabled by default since
# continuous deployment to production is enabled by default
# If you prefer to automatically deploy to staging and
307 308
# only manually promote to production, enable this job by setting
# STAGING_ENABLED.
309

310
staging:
311 312 313 314 315 316
  stage: staging
  script:
    - check_kube_domain
    - install_dependencies
    - download_chart
    - ensure_namespace
317
    - initialize_tiller
318 319 320 321
    - create_secret
    - deploy
  environment:
    name: staging
322
    url: http://$CI_PROJECT_PATH_SLUG-staging.$KUBE_INGRESS_BASE_DOMAIN
323 324 325
  only:
    refs:
      - master
326
    kubernetes: active
327 328
    variables:
      - $STAGING_ENABLED
329

330 331 332
# Canaries are also disabled by default, but if you want them,
# and know what the downsides are, you can enable this by setting
# CANARY_ENABLED.
333

334
canary:
335 336 337 338 339 340
  stage: canary
  script:
    - check_kube_domain
    - install_dependencies
    - download_chart
    - ensure_namespace
341
    - initialize_tiller
342 343 344 345
    - create_secret
    - deploy canary
  environment:
    name: production
346
    url: http://$CI_PROJECT_PATH_SLUG.$KUBE_INGRESS_BASE_DOMAIN
347 348 349 350
  when: manual
  only:
    refs:
      - master
351
    kubernetes: active
352 353
    variables:
      - $CANARY_ENABLED
354

355
.production: &production_template
356 357 358 359 360 361
  stage: production
  script:
    - check_kube_domain
    - install_dependencies
    - download_chart
    - ensure_namespace
362
    - initialize_tiller
363 364 365
    - create_secret
    - deploy
    - delete canary
366
    - delete rollout
367
    - persist_environment_url
368 369
  environment:
    name: production
370
    url: http://$CI_PROJECT_PATH_SLUG.$KUBE_INGRESS_BASE_DOMAIN
371 372
  artifacts:
    paths: [environment_url.txt]
373 374 375

production:
  <<: *production_template
376 377 378
  only:
    refs:
      - master
379
    kubernetes: active
380 381 382
  except:
    variables:
      - $STAGING_ENABLED
383
      - $CANARY_ENABLED
384
      - $INCREMENTAL_ROLLOUT_ENABLED
385
      - $INCREMENTAL_ROLLOUT_MODE
386 387 388 389

production_manual:
  <<: *production_template
  when: manual
390
  allow_failure: false
391 392 393
  only:
    refs:
      - master
394
    kubernetes: active
395 396
    variables:
      - $STAGING_ENABLED
397
      - $CANARY_ENABLED
398 399 400
  except:
    variables:
      - $INCREMENTAL_ROLLOUT_ENABLED
401
      - $INCREMENTAL_ROLLOUT_MODE
402 403 404 405 406 407 408 409 410

# This job implements incremental rollout on for every push to `master`.

.rollout: &rollout_template
  script:
    - check_kube_domain
    - install_dependencies
    - download_chart
    - ensure_namespace
411
    - initialize_tiller
412 413 414 415 416 417 418
    - create_secret
    - deploy rollout $ROLLOUT_PERCENTAGE
    - scale stable $((100-ROLLOUT_PERCENTAGE))
    - delete canary
    - persist_environment_url
  environment:
    name: production
419
    url: http://$CI_PROJECT_PATH_SLUG.$KUBE_INGRESS_BASE_DOMAIN
420 421 422
  artifacts:
    paths: [environment_url.txt]

423
.manual_rollout_template: &manual_rollout_template
424
  <<: *rollout_template
425
  stage: production
426
  when: manual
427
  # This selectors are backward compatible mode with $INCREMENTAL_ROLLOUT_ENABLED (before 11.4)
428 429 430
  only:
    refs:
      - master
431
    kubernetes: active
432
    variables:
433
      - $INCREMENTAL_ROLLOUT_MODE == "manual"
434
      - $INCREMENTAL_ROLLOUT_ENABLED
435 436 437
  except:
    variables:
      - $INCREMENTAL_ROLLOUT_MODE == "timed"
438

439
.timed_rollout_template: &timed_rollout_template
440
  <<: *rollout_template
441 442
  when: delayed
  start_in: 5 minutes
443 444 445
  only:
    refs:
      - master
446
    kubernetes: active
447
    variables:
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
      - $INCREMENTAL_ROLLOUT_MODE == "timed"

timed rollout 10%:
  <<: *timed_rollout_template
  stage: incremental rollout 10%
  variables:
    ROLLOUT_PERCENTAGE: 10

timed rollout 25%:
  <<: *timed_rollout_template
  stage: incremental rollout 25%
  variables:
    ROLLOUT_PERCENTAGE: 25

timed rollout 50%:
  <<: *timed_rollout_template
  stage: incremental rollout 50%
  variables:
    ROLLOUT_PERCENTAGE: 50

timed rollout 100%:
  <<: *timed_rollout_template
  <<: *production_template
  stage: incremental rollout 100%
  variables:
    ROLLOUT_PERCENTAGE: 100

rollout 10%:
  <<: *manual_rollout_template
  variables:
    ROLLOUT_PERCENTAGE: 10

rollout 25%:
  <<: *manual_rollout_template
  variables:
    ROLLOUT_PERCENTAGE: 25
484 485

rollout 50%:
486
  <<: *manual_rollout_template
487 488 489 490
  variables:
    ROLLOUT_PERCENTAGE: 50

rollout 100%:
491
  <<: *manual_rollout_template
492
  <<: *production_template
493
  allow_failure: false
494 495 496 497 498 499 500 501

# ---------------------------------------------------------------------------

.auto_devops: &auto_devops |
  # Auto DevOps variables and functions
  [[ "$TRACE" ]] && set -x
  auto_database_url=postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${CI_ENVIRONMENT_SLUG}-postgres:5432/${POSTGRES_DB}
  export DATABASE_URL=${DATABASE_URL-$auto_database_url}
Aaron Walker's avatar
Aaron Walker committed
502 503 504 505 506 507 508
  if [[ -z "$CI_COMMIT_TAG" ]]; then
    export CI_APPLICATION_REPOSITORY=$CI_REGISTRY_IMAGE/$CI_COMMIT_REF_SLUG
    export CI_APPLICATION_TAG=$CI_COMMIT_SHA
  else
    export CI_APPLICATION_REPOSITORY=$CI_REGISTRY_IMAGE
    export CI_APPLICATION_TAG=$CI_COMMIT_TAG
  fi
509
  export TILLER_NAMESPACE=$KUBE_NAMESPACE
510 511
  # Extract "MAJOR.MINOR" from CI_SERVER_VERSION and generate "MAJOR-MINOR-stable" for Security Products
  export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
512

513
  function registry_login() {
514 515 516 517 518
    if [[ -n "$CI_REGISTRY_USER" ]]; then
      echo "Logging to GitLab Container Registry with CI credentials..."
      docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" "$CI_REGISTRY"
      echo ""
    fi
519 520 521 522
  }

  function container_scanning() {
    registry_login
523

Luke Bennett's avatar
Luke Bennett committed
524
    docker run -d --name db arminc/clair-db:latest
525
    docker run -p 6060:6060 --link db:postgres -d --name clair --restart on-failure arminc/clair-local-scan:v2.0.1
Luke Bennett's avatar
Luke Bennett committed
526 527
    apk add -U wget ca-certificates
    docker pull ${CI_APPLICATION_REPOSITORY}:${CI_APPLICATION_TAG}
528 529
    wget https://github.com/arminc/clair-scanner/releases/download/v8/clair-scanner_linux_amd64
    mv clair-scanner_linux_amd64 clair-scanner
Luke Bennett's avatar
Luke Bennett committed
530 531
    chmod +x clair-scanner
    touch clair-whitelist.yml
532 533 534
    retries=0
    echo "Waiting for clair daemon to start"
    while( ! wget -T 10 -q -O /dev/null http://docker:6060/v1/namespaces ) ; do sleep 1 ; echo -n "." ; if [ $retries -eq 10 ] ; then echo " Timeout, aborting." ; exit 1 ; fi ; retries=$(($retries+1)) ; done
535
    ./clair-scanner -c http://docker:6060 --ip $(hostname -i) -r gl-container-scanning-report.json -l clair.log -w clair-whitelist.yml ${CI_APPLICATION_REPOSITORY}:${CI_APPLICATION_TAG} || true
Luke Bennett's avatar
Luke Bennett committed
536
  }
537

538
  function code_quality() {
539
    docker run --env SOURCE_CODE="$PWD" \
540 541
               --volume "$PWD":/code \
               --volume /var/run/docker.sock:/var/run/docker.sock \
542
               "registry.gitlab.com/gitlab-org/security-products/codequality:$SP_VERSION" /code
543 544
  }

545
  function license_management() {
546
    /run.sh analyze .
547 548
  }

549 550 551
  function sast() {
    case "$CI_SERVER_VERSION" in
      *-ee)
552

553 554 555 556 557 558 559 560
        # Deprecation notice for CONFIDENCE_LEVEL variable
        if [ -z "$SAST_CONFIDENCE_LEVEL" -a "$CONFIDENCE_LEVEL" ]; then
          SAST_CONFIDENCE_LEVEL="$CONFIDENCE_LEVEL"
          echo "WARNING: CONFIDENCE_LEVEL is deprecated and MUST be replaced with SAST_CONFIDENCE_LEVEL"
        fi

        docker run --env SAST_CONFIDENCE_LEVEL="${SAST_CONFIDENCE_LEVEL:-3}" \
                   --volume "$PWD:/code" \
561
                   --volume /var/run/docker.sock:/var/run/docker.sock \
562
                   "registry.gitlab.com/gitlab-org/security-products/sast:$SP_VERSION" /app/bin/run /code
563 564 565 566 567 568 569
        ;;
      *)
        echo "GitLab EE is required"
        ;;
    esac
  }

570 571 572 573 574 575 576 577 578 579 580 581 582 583
  function dependency_scanning() {
    case "$CI_SERVER_VERSION" in
      *-ee)
        docker run --env DEP_SCAN_DISABLE_REMOTE_CHECKS="${DEP_SCAN_DISABLE_REMOTE_CHECKS:-false}" \
                   --volume "$PWD:/code" \
                   --volume /var/run/docker.sock:/var/run/docker.sock \
                   "registry.gitlab.com/gitlab-org/security-products/dependency-scanning:$SP_VERSION" /code
        ;;
      *)
        echo "GitLab EE is required"
        ;;
    esac
  }

584 585 586
  function get_replicas() {
    track="${1:-stable}"
    percentage="${2:-100}"
587 588 589 590

    env_track=$( echo $track | tr -s  '[:lower:]'  '[:upper:]' )
    env_slug=$( echo ${CI_ENVIRONMENT_SLUG//-/_} | tr -s  '[:lower:]'  '[:upper:]' )

591
    if [[ "$track" == "stable" ]] || [[ "$track" == "rollout" ]]; then
592 593
      # for stable track get number of replicas from `PRODUCTION_REPLICAS`
      eval new_replicas=\$${env_slug}_REPLICAS
594 595 596
      if [[ -z "$new_replicas" ]]; then
        new_replicas=$REPLICAS
      fi
597 598 599
    else
      # for all tracks get number of replicas from `CANARY_PRODUCTION_REPLICAS`
      eval new_replicas=\$${env_track}_${env_slug}_REPLICAS
600 601 602
      if [[ -z "$new_replicas" ]]; then
        eval new_replicas=\${env_track}_REPLICAS
      fi
603
    fi
604 605 606 607 608 609 610 611 612 613 614 615

    replicas="${new_replicas:-1}"
    replicas="$(($replicas * $percentage / 100))"

    # always return at least one replicas
    if [[ $replicas -gt 0 ]]; then
      echo "$replicas"
    else
      echo 1
    fi
  }

616 617 618
  # Extracts variables prefixed with K8S_SECRET_
  # and creates a Kubernetes secret.
  #
Thong Kuah's avatar
Thong Kuah committed
619
  # e.g. If we have the following environment variables:
620 621 622
  #   K8S_SECRET_A=value1
  #   K8S_SECRET_B=multi\ word\ value
  #
Thong Kuah's avatar
Thong Kuah committed
623 624 625 626
  # Then we will create a secret with the following key-value pairs:
  #   data:
  #     A: dmFsdWUxCg==
  #     B: bXVsdGkgd29yZCB2YWx1ZQo=
627
  function create_application_secret() {
628 629 630
    track="${1-stable}"
    export APPLICATION_SECRET_NAME=$(application_secret_name "$track")

631
    env | sed -n "s/^K8S_SECRET_\(.*\)$/\1/p" > k8s_prefixed_variables
632

633 634 635 636 637 638 639 640
    kubectl create secret \
      -n "$KUBE_NAMESPACE" generic "$APPLICATION_SECRET_NAME" \
      --from-env-file k8s_prefixed_variables -o yaml --dry-run |
      kubectl replace -n "$KUBE_NAMESPACE" --force -f -

    export APPLICATION_SECRET_CHECKSUM=$(cat k8s_prefixed_variables | sha256sum | cut -d ' ' -f 1)

    rm k8s_prefixed_variables
641 642
  }

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
  function deploy_name() {
    name="$CI_ENVIRONMENT_SLUG"
    track="${1-stable}"

    if [[ "$track" != "stable" ]]; then
      name="$name-$track"
    fi

    echo $name
  }

  function application_secret_name() {
    track="${1-stable}"
    name=$(deploy_name "$track")

    echo "${name}-secret"
  }

661 662 663
  function deploy() {
    track="${1-stable}"
    percentage="${2:-100}"
664
    name=$(deploy_name "$track")
665 666 667 668 669 670 671 672 673 674

    replicas="1"
    service_enabled="true"
    postgres_enabled="$POSTGRES_ENABLED"

    # if track is different than stable,
    # re-use all attached resources
    if [[ "$track" != "stable" ]]; then
      service_enabled="false"
      postgres_enabled="false"
675 676
    fi

677 678
    replicas=$(get_replicas "$track" "$percentage")

679 680 681 682 683 684
    if [[ "$CI_PROJECT_VISIBILITY" != "public" ]]; then
      secret_name='gitlab-registry'
    else
      secret_name=''
    fi

685
    create_application_secret "$track"
686

687 688 689 690 691 692 693 694
    env_slug=$(echo ${CI_ENVIRONMENT_SLUG//-/_} | tr -s '[:lower:]' '[:upper:]')
    eval env_ADDITIONAL_HOSTS=\$${env_slug}_ADDITIONAL_HOSTS
    if [ -n "$env_ADDITIONAL_HOSTS" ]; then
      additional_hosts="{$env_ADDITIONAL_HOSTS}"
    elif [ -n "$ADDITIONAL_HOSTS" ]; then
      additional_hosts="{$ADDITIONAL_HOSTS}"
    fi

695
    if [[ -n "$DB_INITIALIZE" && -z "$(helm ls -q "^$name$")" ]]; then
696
      echo "Deploying first release with database initialization..."
697 698 699 700 701 702 703 704 705 706
      helm upgrade --install \
        --wait \
        --set service.enabled="$service_enabled" \
        --set releaseOverride="$CI_ENVIRONMENT_SLUG" \
        --set image.repository="$CI_APPLICATION_REPOSITORY" \
        --set image.tag="$CI_APPLICATION_TAG" \
        --set image.pullPolicy=IfNotPresent \
        --set image.secrets[0].name="$secret_name" \
        --set application.track="$track" \
        --set application.database_url="$DATABASE_URL" \
707
        --set application.secretName="$APPLICATION_SECRET_NAME" \
708
        --set application.secretChecksum="$APPLICATION_SECRET_CHECKSUM" \
709
        --set service.commonName="le.$KUBE_INGRESS_BASE_DOMAIN" \
710
        --set service.url="$CI_ENVIRONMENT_URL" \
711
        --set service.additionalHosts="$additional_hosts" \
712 713 714 715 716 717
        --set replicaCount="$replicas" \
        --set postgresql.enabled="$postgres_enabled" \
        --set postgresql.nameOverride="postgres" \
        --set postgresql.postgresUser="$POSTGRES_USER" \
        --set postgresql.postgresPassword="$POSTGRES_PASSWORD" \
        --set postgresql.postgresDatabase="$POSTGRES_DB" \
718
        --set postgresql.imageTag="$POSTGRES_VERSION" \
719 720 721 722 723
        --set application.initializeCommand="$DB_INITIALIZE" \
        --namespace="$KUBE_NAMESPACE" \
        "$name" \
        chart/

724
      echo "Deploying second release..."
725 726 727 728 729 730 731 732
      helm upgrade --reuse-values \
        --wait \
        --set application.initializeCommand="" \
        --set application.migrateCommand="$DB_MIGRATE" \
        --namespace="$KUBE_NAMESPACE" \
        "$name" \
        chart/
    else
733
      echo "Deploying new release..."
734 735 736 737 738 739 740 741 742 743
      helm upgrade --install \
        --wait \
        --set service.enabled="$service_enabled" \
        --set releaseOverride="$CI_ENVIRONMENT_SLUG" \
        --set image.repository="$CI_APPLICATION_REPOSITORY" \
        --set image.tag="$CI_APPLICATION_TAG" \
        --set image.pullPolicy=IfNotPresent \
        --set image.secrets[0].name="$secret_name" \
        --set application.track="$track" \
        --set application.database_url="$DATABASE_URL" \
744
        --set application.secretName="$APPLICATION_SECRET_NAME" \
745
        --set application.secretChecksum="$APPLICATION_SECRET_CHECKSUM" \
746
        --set service.commonName="le.$KUBE_INGRESS_BASE_DOMAIN" \
747
        --set service.url="$CI_ENVIRONMENT_URL" \
748
        --set service.additionalHosts="$additional_hosts" \
749 750 751 752 753 754 755 756 757 758 759
        --set replicaCount="$replicas" \
        --set postgresql.enabled="$postgres_enabled" \
        --set postgresql.nameOverride="postgres" \
        --set postgresql.postgresUser="$POSTGRES_USER" \
        --set postgresql.postgresPassword="$POSTGRES_PASSWORD" \
        --set postgresql.postgresDatabase="$POSTGRES_DB" \
        --set application.migrateCommand="$DB_MIGRATE" \
        --namespace="$KUBE_NAMESPACE" \
        "$name" \
        chart/
    fi
760

761
    kubectl rollout status -n "$KUBE_NAMESPACE" -w "$ROLLOUT_RESOURCE_TYPE/$name"
762 763
  }

764 765 766
  function scale() {
    track="${1-stable}"
    percentage="${2-100}"
767
    name=$(deploy_name "$track")
768 769 770

    replicas=$(get_replicas "$track" "$percentage")

771 772 773 774 775 776 777 778
    if [[ -n "$(helm ls -q "^$name$")" ]]; then
      helm upgrade --reuse-values \
        --wait \
        --set replicaCount="$replicas" \
        --namespace="$KUBE_NAMESPACE" \
        "$name" \
        chart/
    fi
779 780
  }

781 782
  function install_dependencies() {
    apk add -U openssl curl tar gzip bash ca-certificates git
783 784
    curl -sSL -o /etc/apk/keys/sgerrand.rsa.pub https://alpine-pkgs.sgerrand.com/sgerrand.rsa.pub
    curl -sSL -O https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.28-r0/glibc-2.28-r0.apk
785 786
    apk add glibc-2.28-r0.apk
    rm glibc-2.28-r0.apk
787

788
    curl -sS "https://kubernetes-helm.storage.googleapis.com/helm-v${HELM_VERSION}-linux-amd64.tar.gz" | tar zx
789
    mv linux-amd64/helm /usr/bin/
790
    mv linux-amd64/tiller /usr/bin/
791
    helm version --client
792 793
    tiller -version

794
    curl -sSL -o /usr/bin/kubectl "https://storage.googleapis.com/kubernetes-release/release/v${KUBERNETES_VERSION}/bin/linux/amd64/kubectl"
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
    chmod +x /usr/bin/kubectl
    kubectl version --client
  }

  function setup_docker() {
    if ! docker info &>/dev/null; then
      if [ -z "$DOCKER_HOST" -a "$KUBERNETES_PORT" ]; then
        export DOCKER_HOST='tcp://localhost:2375'
      fi
    fi
  }

  function setup_test_db() {
    if [ -z ${KUBERNETES_PORT+x} ]; then
      DB_HOST=postgres
    else
      DB_HOST=localhost
    fi
    export DATABASE_URL="postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${DB_HOST}:5432/${POSTGRES_DB}"
  }

  function download_chart() {
    if [[ ! -d chart ]]; then
      auto_chart=${AUTO_DEVOPS_CHART:-gitlab/auto-deploy-app}
      auto_chart_name=$(basename $auto_chart)
      auto_chart_name=${auto_chart_name%.tgz}
821
      auto_chart_name=${auto_chart_name%.tar.gz}
822 823 824 825 826 827
    else
      auto_chart="chart"
      auto_chart_name="chart"
    fi

    helm init --client-only
828
    helm repo add gitlab ${AUTO_DEVOPS_CHART_REPOSITORY:-https://charts.gitlab.io}
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
    if [[ ! -d "$auto_chart" ]]; then
      helm fetch ${auto_chart} --untar
    fi
    if [ "$auto_chart_name" != "chart" ]; then
      mv ${auto_chart_name} chart
    fi

    helm dependency update chart/
    helm dependency build chart/
  }

  function ensure_namespace() {
    kubectl describe namespace "$KUBE_NAMESPACE" || kubectl create namespace "$KUBE_NAMESPACE"
  }

844 845 846

  # Function to ensure backwards compatibility with AUTO_DEVOPS_DOMAIN
  function ensure_kube_ingress_base_domain() {
847
    if [ -z ${KUBE_INGRESS_BASE_DOMAIN+x} ] && [ -n "$AUTO_DEVOPS_DOMAIN" ] ; then
848
      export KUBE_INGRESS_BASE_DOMAIN=$AUTO_DEVOPS_DOMAIN
849 850 851
    fi
  }

852
  function check_kube_domain() {
853 854 855 856 857 858 859
    ensure_kube_ingress_base_domain

    if [ -z ${KUBE_INGRESS_BASE_DOMAIN+x} ]; then
      echo "In order to deploy or use Review Apps,"
      echo "AUTO_DEVOPS_DOMAIN or KUBE_INGRESS_BASE_DOMAIN variables must be set"
      echo "From 11.8, you can set KUBE_INGRESS_BASE_DOMAIN in cluster settings"
      echo "or by defining a variable at group or project level."
860
      echo "You can also manually add it in .gitlab-ci.yml"
861
      echo "AUTO_DEVOPS_DOMAIN support will be dropped on 12.0"
862 863 864 865 866 867
      false
    else
      true
    fi
  }

868
  function initialize_tiller() {
869
    echo "Checking Tiller..."
870

871
    export HELM_HOST="localhost:44134"
872
    tiller -listen ${HELM_HOST} -alsologtostderr > /dev/null 2>&1 &
873
    echo "Tiller is listening on ${HELM_HOST}"
874

875 876 877 878 879 880 881 882
    if ! helm version --debug; then
      echo "Failed to init Tiller."
      return 1
    fi
    echo ""
  }

  function create_secret() {
883
    echo "Create secret..."
884 885 886
    if [[ "$CI_PROJECT_VISIBILITY" == "public" ]]; then
      return
    fi
887

888 889 890
    kubectl create secret -n "$KUBE_NAMESPACE" \
      docker-registry gitlab-registry \
      --docker-server="$CI_REGISTRY" \
891 892
      --docker-username="${CI_DEPLOY_USER:-$CI_REGISTRY_USER}" \
      --docker-password="${CI_DEPLOY_PASSWORD:-$CI_REGISTRY_PASSWORD}" \
893 894 895
      --docker-email="$GITLAB_USER_EMAIL" \
      -o yaml --dry-run | kubectl replace -n "$KUBE_NAMESPACE" --force -f -
  }
896

897 898 899 900 901 902 903 904
  function dast() {
    export CI_ENVIRONMENT_URL=$(cat environment_url.txt)

    mkdir /zap/wrk/
    /zap/zap-baseline.py -J gl-dast-report.json -t "$CI_ENVIRONMENT_URL" || true
    cp /zap/wrk/gl-dast-report.json .
  }

905 906
  function performance() {
    export CI_ENVIRONMENT_URL=$(cat environment_url.txt)
907

908
    mkdir gitlab-exporter
909
    wget -O gitlab-exporter/index.js https://gitlab.com/gitlab-org/gl-performance/raw/10-5/index.js
910

911
    mkdir sitespeed-results
912

913 914 915
    if [ -f .gitlab-urls.txt ]
    then
      sed -i -e 's@^@'"$CI_ENVIRONMENT_URL"'@' .gitlab-urls.txt
916
      docker run --shm-size=1g --rm -v "$(pwd)":/sitespeed.io sitespeedio/sitespeed.io:6.3.1 --plugins.add ./gitlab-exporter --outputFolder sitespeed-results .gitlab-urls.txt
917
    else
918
      docker run --shm-size=1g --rm -v "$(pwd)":/sitespeed.io sitespeedio/sitespeed.io:6.3.1 --plugins.add ./gitlab-exporter --outputFolder sitespeed-results "$CI_ENVIRONMENT_URL"
919
    fi
920

921 922
    mv sitespeed-results/data/performance.json performance.json
  }
923

924 925 926
  function persist_environment_url() {
      echo $CI_ENVIRONMENT_URL > environment_url.txt
  }
927 928 929

  function delete() {
    track="${1-stable}"
930
    name=$(deploy_name "$track")
931

932
    if [[ -n "$(helm ls -q "^$name$")" ]]; then
933
      helm delete --purge "$name"
934
    fi
935

936 937
    secret_name=$(application_secret_name "$track")
    kubectl delete secret --ignore-not-found -n "$KUBE_NAMESPACE" "$secret_name"
938 939 940 941
  }

before_script:
  - *auto_devops