image: 
  name: hashicorp/terraform:0.14.8
  entrypoint:
    - '/usr/bin/env'
    - 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
workflow:
  rules:
    - if: '$CI_COMMIT_MESSAGE =~ /^(no-pipe)/'
      when: never
stages:
  - Test and Lint
  - Staging Plan
  - Staging Apply
  - Integration Test
  - Production Plan
  - Production Apply
  - Destroy

Test and Lint:
  stage: Test and Lint
  script:
    - echo "test to do"
  rules:
    - if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME =~ /^(master|production)$/ || $CI_COMMIT_BRANCH =~ /^(master|production)$/'

Validate Terraform:
  stage: Test and Lint
  script:
    - cd deploy/
    - terraform init -backend=false
    - terraform validate
    - terraform fmt -check
  rules:
    - if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME =~ /^(master|production)$/ || $CI_COMMIT_BRANCH =~ /^(master|production)$/'

Staging Plan:
  stage: Staging Plan
  script:
    - cd deploy/
    - terraform init
    - terraform workspace select staging || terraform workspace new staging
    - terraform plan
  rules:
    - if: '$CI_COMMIT_BRANCH =~ /^(master|production)$/'

Staging Apply:
  stage: Staging Apply
  script:
    - apk add --update npm
    - cd deploy/
    - cd lambda/src
    - npm install
    - cd -
    - terraform init
    - terraform workspace select staging
    - terraform apply -auto-approve
    - echo "API_ENDPOINT=$(terraform output -raw api_endpoint)" >> ../deploy.env
  artifacts:
    reports:
      dotenv: deploy.env
  rules:
    - if: '$CI_COMMIT_BRANCH =~ /^(master|production)$/'

Integration Tests:
  stage: Integration Test
  image: 
    name: postman/newman
    entrypoint: [""]
  script:
    - newman run Lambda_CRUD.postman_collection.json --env-var "endpoint=$API_ENDPOINT"
  rules:
    - if: '$CI_COMMIT_BRANCH =~ /^(master|production)$/'

Production Plan:
  stage: Production Plan
  script:
    - cd deploy/
    - terraform init
    - terraform workspace select production || terraform workspace new production
    - terraform plan
  rules:
    - if: '$CI_COMMIT_BRANCH == "production"'

Production Apply:
  stage: Production Apply
  script:
    - cd deploy/
    - terraform init
    - terraform workspace select production
    - terraform apply -auto-approve
  rules:
    - if: '$CI_COMMIT_BRANCH == "production"'

Staging Destroy:
  stage: Destroy
  script:
    - cd deploy/
    - terraform init
    - terraform workspace select staging
    - terraform destroy -auto-approve
  rules: 
    - if: '$CI_COMMIT_BRANCH =~ /^(master|production)$/'
      when: manual

Production Destroy:
  stage: Destroy
  script:
    - cd deploy/
    - terraform init
    - terraform workspace select production
    - terraform destroy -auto-approve
  rules: 
    - if: '$CI_COMMIT_BRANCH == "production"'
      when: manual