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
  - Apply
  - Integration Test
  - Destroy

.load_tf_workspace: &load_tf_workspace |
  if [[ $CI_COMMIT_REF_SLUG == "master" ]]; then
    export TF_WORKSPACE="staging"
  else
    export TF_WORKSPACE="dev"
  fi


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"'

Apply:
  stage: Apply
  before_script:
    - *load_tf_workspace
  script:
    - apk add --update npm
    - cd deploy/
    - cd lambda/src
    - npm install
    - cd -
    - terraform init
    - terraform plan -var-file=vars/${TF_WORKSPACE}.tfvars -out=tfplan.out
    - terraform apply tfplan.out
    - echo "API_ENDPOINT=$(terraform output -raw api_endpoint)" >> ../deploy.env
  artifacts:
    reports:
      dotenv: deploy.env
  rules:
    - if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "master" || $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_MERGE_REQUEST_TARGET_BRANCH_NAME == "master" || $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_MERGE_REQUEST_TARGET_BRANCH_NAME == "master" || $CI_COMMIT_BRANCH == "master"'
      allow_failure: true
      when: manual

Destroy:
  stage: Destroy
  before_script:
    - *load_tf_workspace
  script:
    - cd deploy/
    - terraform init
    - terraform destroy -var-file=vars/${TF_WORKSPACE}.tfvars -auto-approve
  rules:
    - if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "master" || $CI_COMMIT_BRANCH == "master"'
      allow_failure: true
      when: manual