include:
  - template: Terraform/Base.latest.gitlab-ci.yml
  - template: Workflows/MergeRequest-Pipelines.gitlab-ci.yml
variables:
  TF_ROOT: terraform
stages:
  - build
  - plan_json
  - infracost
build:
  extends: .terraform:build
plan_json:
  stage: plan_json
  dependencies:
    - build
  before_script:
    - cd ${TF_ROOT}
    - gitlab-terraform init
  script:
    - gitlab-terraform show -json plan.cache > full-plan.json
  artifacts:
    paths:
      - ${TF_ROOT}/full-plan.json
infracost:
  stage: infracost
  image:
    name: infracost/infracost:ci-0.10
    entrypoint:
      - ''
  dependencies:
    - plan_json
  script:
    - >-
      find examples -type f  -name '*.tf' -o -name '*.hcl' -o -name '*.tfvars' |
      xargs sed -i 's/m5.4xlarge/m5.8xlarge/g'
    - >-
      find examples -type f  -name '*.tf' -o -name '*.hcl' -o -name '*.tfvars' |
      xargs sed -i 's/t2.micro/t2.medium/g'
    - |
      infracost diff --path=${TF_ROOT}/full-plan.json \
                     --format=json \
                     --out-file=infracost.json
    - >-
      infracost comment gitlab --path=infracost.json --repo=$CI_PROJECT_PATH
      --merge-request=1 --gitlab-server-url=$CI_SERVER_URL
      --gitlab-token=$GITLAB_TOKEN --behavior=update --dry-run >
      /tmp/infracost_comment.md
    - >-
      [ "$UPDATE_GOLDEN_FILES" = true ] && cp /tmp/infracost_comment.md
      testdata/plan-json-gitlab-terraform_comment_golden.md
    - >-
      [ "$UPDATE_GOLDEN_FILES" != true ] && diff
      testdata/plan-json-gitlab-terraform_comment_golden.md
      /tmp/infracost_comment.md
  variables:
    INFRACOST_API_KEY: $INFRACOST_API_KEY
    GITLAB_TOKEN: $GITLAB_TOKEN
