default:
  image: registry.gitlab.com/gitlab-org/terraform-images/stable:latest

variables:
  TF_ROOT: ${CI_PROJECT_DIR}/terraform
  TF_ADDRESS: ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/terraform/state/${TF_STATE_NAME}
  TF_STATE_NAME: ${ENVIRONMENT}
  TF_CACHE_KEY: default

before_script:
  - cd ${TF_ROOT}
  - which ssh-agent || ( apt-get install -qq openssh-client )
  - ssh-keygen -b 2048 -t rsa -f ./tf.rsa -q -N "" -C "FORGE alpha-project-manager"
  - export TF_VAR_SCW_ACCESS_KEY=${TF_VAR_SCW_ACCESS_KEY}
  - export TF_VAR_SCW_SECRET_KEY=${TF_VAR_SCW_SECRET_KEY}
  - export TF_VAR_SCW_PROJECT_ID=${TF_VAR_SCW_PROJECT_ID}
  - export TF_VAR_INSTANCES_COUNT=${TF_VAR_INSTANCES_COUNT}
  - export TF_VAR_ENVIRONMENT=${ENVIRONMENT}
  - export TF_VAR_SCW_SSH_PUB_KEY=$(cat tf.rsa.pub)
  - export TF_VAR_SCW_SSH_PRIVATE_KEY=$(cat tf.rsa)
  - echo ${TF_VAR_SCW_SSH_PUB_KEY}
  - echo ${TF_VAR_SCW_SSH_PRIVATE_KEY}
  - echo $(ssh-keygen -E md5 -lf ./tf.rsa.pub)

stages:
  - prepare
  - validate
  - build
  - deploy
  - destroy

init:
  stage: prepare
  script:
    - gitlab-terraform init

validate:
  stage: validate
  script:
    - gitlab-terraform validate

plan:
  stage: build
  script:
    - gitlab-terraform plan
    - gitlab-terraform plan-json
  artifacts:
    name: plan
    paths:
      - ${TF_ROOT}/plan.cache
    reports:
      terraform: ${TF_ROOT}/plan.json

apply:
  stage: deploy
  environment:
    name: ${ENVIRONMENT}
  script:
    - gitlab-terraform apply
  dependencies:
    - plan
  when: manual
  only:
    - develop
    - main

destroy:
  stage: destroy
  environment:
    name: ${ENVIRONMENT}
  script:
    - gitlab-terraform destroy
  when: manual
  only:
    - develop
    - main