Skip to content

Creación de pipeline de Pruebas o Staging

Laboratorio: Creación de pipeline de Pruebas o Staging

Descripción

La presente guía enseña al estudiante el proceso de creación de pipelines como código para Gitlab CI.

Objetivos

  • Crear un pipeline que corra a través de Gitlab CI.

Antes de comenzar

  • Contar con el acceso al ambiente del laboratorio
  • Contar con las herramientas instaladas

Inicio de laboratorio

  1. Acceda a la carpeta angular-demo

    cd angular-demo
    

  2. Cree una carpeta llamada ci-templates

    mkdir ci-templates
    

  3. Cree un archivo llamado .dev.yaml en la carpeta ci-templates con el contenido actual de .gitlab-ci.yml

    cp .gitlab-ci.yml ci-templates/.dev.yaml
    

  4. Edite el archivo ci-templates/.dev.yaml cambiando el nombre de los Jobs agregando -dev al final

    package-dev:
    sonar-dev:
    build-image-dev:
    apply-dev:
    

  5. Edite el archivo ci-templates/.dev.yaml agregando a cada tarea un rules para verificar la rama

    1
    2
    3
    package-dev:
      rules:
        - if: $CI_COMMIT_BRANCH =~ /dev*/
    

  6. Edite el archivo .gitlab-ci.yml borrando su contenido y reemplazando por lo siguiente

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    include:
      - local: 'ci-templates/*.yaml'
    
    stages:
      - package
      - analyze
      - build
      - promote
      - deploy
      - test
    

  7. Edite el archivo ci/.dev.yaml agregando el Job de policy-test

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    policy-test-dev:
      rules:
        - if: $CI_COMMIT_BRANCH =~ /dev*/
      stage: analyze
      image:
        name: openpolicyagent/conftest:v0.32.0
        entrypoint:
          - ""
      tags:
        - dev
      script:
        - conftest test -p manifests/policy.rego manifests/k8s-template.yaml --output=junit > policy_results.xml
      artifacts:
        reports:
          junit: policy_results.xml
    

  8. Agregue el bloque artifacts al Job build-image

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    build-image-dev:
      stage: build
      image:
        name: gcr.io/kaniko-project/executor:debug
        entrypoint: [""]
      rules:
        - if: $CI_COMMIT_BRANCH =~ /dev*/
      tags:
        - dev
      artifacts:
        paths:
          - .sha-image
        expire_in: 1 week
      script:
        - mkdir -p /kaniko/.docker
        - |
          if [ $PROMOTE_SHA == 'yes' ]; then
            echo $CI_COMMIT_SHORT_SHA > .sha-image
          fi
        - echo "{\"auths\":{\"$REGISTRY_URL\":{\"username\":\"$REGISTRY_USER\",\"password\":\"$TOKEN\"}}}" > /kaniko/.docker/config.json
        - /kaniko/executor --context . --dockerfile docker/Dockerfile --destination ${REGISTRY_URL}/${REGISTRY_PROJECT}/${IMAGE_NAME}:${CI_COMMIT_SHORT_SHA} --skip-tls-verify $KANIKO_ARGS --image-fs-extract-retry 5
        - echo ${CI_COMMIT_SHORT_SHA} > .sha-image
    

  9. Cree el archivo llamado policy.rego en la carpeta manifests con el siguiente contenido

    package main
    
    name = input.metadata.name
    
    required_deployment_labels {
            input.metadata.labels["app"]
    }
    
    deny[msg] {
      input.kind = "Deployment"
      not required_deployment_labels
      msg = sprintf("%s must include Kubernetes recommended labels: https://kubernetes.io/docs/concepts/overview/working-with-objects/common-labels/#labels", [name])
    }
    
    deny[msg] {
      input.kind = "Deployment"
      not input.spec.selector.matchLabels.app
      msg = "Containers must provide app label for pod selectors"
    }
    

  10. Agregue la siguiente variable

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    variables:
      SONAR_ARGS: "-Dsonar.projectName=${PROJECT_NAME} -Dsonar.projectKey=some.org:${PROJECT_NAME} -Dsonar.host.url=$SONAR_URL -Dsonar.sources=. -Dsonar.login=$SONAR_TOKEN -Dsonar.coverage.exclusions=node_modules/*"
      PROJECT_NAME: "angular-demo"
      SONAR_URL: "http://sonarqube.xx-xxx-xx-xx/"
      REGISTRY_PROJECT: "api-test"
      IMAGE_NAME: "angular-demo"
      DEPLOYMENT_NAME: "angular-demo"
      NAMESPACE: "userx"
      SERVICE_PORT: "80"
      INGRESS_HOST: "angular-demo.xx-xxx-xx-xx.nip.io"
      PROMOTE_SHA: "yes"
    

  11. Guarde y suba los cambios

    git add .
    git commit -m "Initial structure"
    git push
    

  12. Revise en el portal de gitlab la ejecución del pipeline

  13. Revise los recursos actualizados

    kubectl get all,svc,ingress -n userx
    kubectl describe deploy/angular-demo -n userx
    

  14. Cree una rama nueva llamada qa

    git checkout -b qa
    

  15. Cree el archivo llamado .qa.yaml en la carpeta ci-templates con el siguiente contenido

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    variables:
      PROJECT_NAME: "angular-demo"
      REGISTRY_PROJECT: "api-test"
      IMAGE_NAME: "angular-demo"
      DEPLOYMENT_NAME: "angular-demo"
      NAMESPACE: "userx"
      SERVICE_PORT: "80"
      INGRESS_HOST: "angular-demo.x-x-x-x.nip.io"
    
    policy-test-qa:
      rules:
        - if: $CI_COMMIT_BRANCH =~ /qa*/
      stage: analyze
      image:
        name: openpolicyagent/conftest:v0.32.0
        entrypoint:
          - ""
      tags:
        - qa
      script:
        - conftest test -p manifests/policy.rego manifests/k8s-template.yaml --output=junit > policy_results.xml
      artifacts:
        reports:
          junit: policy_results.xml
    

  16. Agregue el Job de promote-image

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    variables:
      PROJECT_NAME: "angular-demo"
      REGISTRY_PROJECT: "apis"
      IMAGE_NAME: "angular-demo"
      DEPLOYMENT_NAME: "angular-demo"
      NAMESPACE: "userx"
      SERVICE_PORT: "80"
      INGRESS_HOST: "angular-demo.x-x-x-x.nip.io"
    
    policy-test-qa:
      rules:
        - if: $CI_COMMIT_BRANCH =~ /qa*/
      stage: analyze
      image:
        name: openpolicyagent/conftest:v0.32.0
        entrypoint:
          - ""
      tags:
        - qa
      script:
        - conftest test -p manifests/policy.rego manifests/k8s-template.yaml --output=junit > policy_results.xml
      artifacts:
        reports:
          junit: policy_results.xml
    
    promote-image-qa:
      rules:
        - if: $CI_COMMIT_BRANCH =~ /qa*/
      stage: promote
      tags:
        - qa
      image:
        name: quay.io/skopeo/stable:v1.20.0
        entrypoint: ["/bin/bash", "-c"]
      script:
        - |
          echo ${PROJECT_TOKEN}
          echo $CI_API_V4_URL
          echo $CI_PROJECT_ID
    
          curl -o .sha-image --header "PRIVATE-TOKEN: ${PROJECT_TOKEN}" "$CI_API_V4_URL/projects/$CI_PROJECT_ID/jobs/artifacts/dev/raw/.sha-image?job=build-image-dev"
    
          LAST_COMMIT=$(cat .sha-image)
          skopeo login -u "$REGISTRY_USER" --password "$TOKEN" $REGISTRY_URL --tls-verify=$DEST_TLS_VERIFY
          LAST_IMAGE=$(echo $REGISTRY_URL/$REGISTRY_PROJECT/$IMAGE_NAME):${LAST_COMMIT}
          echo $REGISTRY_URL/$REGISTRY_PROJECT/$IMAGE_NAME:${LAST_COMMIT}
          skopeo copy docker://$LAST_IMAGE docker://$REGISTRY_URL/$REGISTRY_PROJECT/$IMAGE_NAME:$CI_COMMIT_SHORT_SHA  --src-tls-verify=${SRC_TLS_VERIFY} --dest-tls-verify=${DEST_TLS_VERIFY}
    

  17. Agregue el Job de apply

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    apply-qa:
      rules:
        - if: $CI_COMMIT_BRANCH =~ /qa*/
      stage: deploy
      image: quay.io/itmlabs/kubectl-tools:v0.0.1
      tags:
        - qa
      script:
        - |
          echo "[INFO] Reemplazando variables en archivo template"
          envsubst < manifests/k8s-template.yaml > k8s-resources.yaml
    
          echo "[INFO] Recursos creados con valores substituidos"
          cat k8s-resources.yaml
    
          echo "[INFO] Desplegando aplicación"
          kubectl apply -f k8s-resources.yaml
    

  18. Agregue las siguientes variables

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    variables:
      PROJECT_NAME: "angular-demo"
      REGISTRY_PROJECT: "api-test"
      IMAGE_NAME: "angular-demo"
      DEPLOYMENT_NAME: "angular-demo"
      NAMESPACE: "userx"
      SERVICE_PORT: "80"
      INGRESS_HOST: "angular-demo.x-x-x-x.nip.io"
      SRC_TLS_VERIFY: "false"
      DEST_TLS_VERIFY: "false"
    

  19. Genere un Access Token de su cuenta de Gitlab con permisos sobre api y write repo y guarde como Variable en el repositorio

    Variable Type Value Mask
    PROJECT_TOKEN Variable token de gitlab asociado a la cuenta
  20. Guarde y suba los cambios

    git add .
    git commit -m "Add qa pipeline"
    git push --set-upstream origin qa
    

  21. Revise en el portal de gitlab la ejecución del pipeline