variables:
  CI_REGISTRY: registry.gitlab.metrix.com.ai
  CI_REGISTRY_USER: gitlab-ci-token
  GIT_STRATEGY: none
  CI_REGISTRY_IMAGE: ${CI_REGISTRY}/${CI_PROJECT_PATH}
  CI_APPLICATION_TAG: ${CI_COMMIT_SHORT_SHA}
  APP_DOMAIN: my-app.kube.metrix.com.ai
  DOCKER_HOST: tcp://docker:2375
  DOCKER_TLS_CERTDIR: ""

stages:
  - build
  - deploy

build:
  stage: build
  image: docker:latest
  services:
    - name: docker:dind
      alias: docker
      command: ["--storage-driver=vfs"]
  tags:
    - kube-my-app
  variables:
    DOCKER_HOST: tcp://docker:2375
    DOCKER_TLS_CERTDIR: ""
    DOCKER_DRIVER: vfs
  before_script:
    - until docker info > /dev/null 2>&1; do sleep 1; done
    - docker login -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN $CI_REGISTRY
  script:
    - git clone https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.metrix.com.ai/${CI_PROJECT_PATH}.git /tmp/repo
    - cd /tmp/repo
    - docker build -t ${CI_REGISTRY_IMAGE}:${CI_APPLICATION_TAG} .
    - docker push ${CI_REGISTRY_IMAGE}:${CI_APPLICATION_TAG}
  only:
    - main

deploy_to_k8s:
  stage: deploy
  tags:
    - kube-my-app
  image: bitnami/kubectl:latest
  needs: ["build"]
  before_script:
    # Команда в одну строку!
    - kubectl create secret docker-registry gitlab-registry-secret --namespace my-app --docker-server=$CI_REGISTRY --docker-username=$CI_REGISTRY_USER --docker-password=$CI_JOB_TOKEN --dry-run=client -o yaml | kubectl apply -f -
  script:
    - git clone https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.metrix.com.ai/${CI_PROJECT_PATH}.git /tmp/repo
    - cd /tmp/repo/k8s-manifests
    - sed -i "s|__IMAGE_TAG__|${CI_APPLICATION_TAG}|g" deployment.yaml
    - sed -i "s|__APP_DOMAIN__|${APP_DOMAIN}|g" ingress.yaml
    - kubectl apply -f namespace.yaml
    - kubectl apply -f deployment.yaml -n my-app
    - kubectl apply -f service.yaml -n my-app
    - kubectl apply -f ingress.yaml -n my-app
    - kubectl rollout status deployment/my-app-deployment -n my-app --timeout=3m
    - kubectl get pods,svc,ingress -n my-app
  only:
    - main