image: 
  name: hashicorp/terraform:0.14.9
  entrypoint:
    - '/usr/bin/env'
    - 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'

stages:
  - Test and Lint
  - Staging Plan
  - Staging Apply
  - Integration Test
  - Destroy

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

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

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 -var-file=vars/staging.tfvars -auto-approve
    - echo "API_ENDPOINT=$(terraform output -raw api_endpoint)" >> ../deploy.env
  artifacts:
    reports:
      dotenv: deploy.env
  rules:
    - if: '$CI_COMMIT_BRANCH =~ /^(master)$/'

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

Load Tests:
  stage: Integration Test
  image: 
    name: peterevans/vegeta:6.9
    entrypoint: [""]
  script:
    - echo "GET $API_ENDPOINT/crud" | vegeta attack -duration=3s -rate=100/s | vegeta report
    - echo "PUT $API_ENDPOINT/crud" | vegeta attack -duration=3s -rate=100/s | vegeta report
    - echo "PATCH $API_ENDPOINT/crud" | vegeta attack -duration=3s -rate=100/s | vegeta report
    - echo "DELETE $API_ENDPOINT/crud" | vegeta attack -duration=3s -rate=100/s | vegeta report
  rules:
    - if: '$CI_COMMIT_BRANCH =~ /^(master)$/'
      when: manual

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