# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

timeout: 3600s
substitutions:
  _POLICY_REPO: '/workspace/policy-library' # add path to policies as per https://github.com/GoogleCloudPlatform/policy-library/blob/main/docs/user_guide.md#how-to-set-up-constraints-with-policy-library
  _DOCKER_TAG_VERSION_TERRAFORM: 'latest'
steps:
- id: 'setup'
  name: $_GAR_REGION-docker.pkg.dev/$_GAR_PROJECT_ID/$_GAR_REPOSITORY/terraform:$_DOCKER_TAG_VERSION_TERRAFORM
  entrypoint: /bin/bash
  args:
  - -c
  - |
   tf_sa_email=${_TF_SA_EMAIL}
    if [[ -n ${tf_sa_email} ]]; then
      echo "Setting up gcloud for impersonation"
      gcloud config set auth/impersonate_service_account $tf_sa_email
    fi
    echo "Adding bucket information to backends"
    for i in `find -name 'backend.tf'`; do sed -r -i 's/UPDATE_ME|UPDATE_PROJECTS_BACKEND|UPDATE_APP_INFRA_BUCKET/${_STATE_BUCKET_NAME}/' $i; done


# [START tf-init]
- id: 'tf init'
  name: $_GAR_REGION-docker.pkg.dev/$_GAR_PROJECT_ID/$_GAR_REPOSITORY/terraform:$_DOCKER_TAG_VERSION_TERRAFORM
  entrypoint: /bin/bash
  args:
  - -c
  - |
      ./tf-wrapper.sh init ${BRANCH_NAME}

# [START tf-plan]
- id: 'tf plan'
  name: $_GAR_REGION-docker.pkg.dev/$_GAR_PROJECT_ID/$_GAR_REPOSITORY/terraform:$_DOCKER_TAG_VERSION_TERRAFORM
  entrypoint: /bin/bash
  args:
  - -c
  - |
      ./tf-wrapper.sh plan ${BRANCH_NAME}

# [START tf-validate]
- id: 'tf validate'
  name: $_GAR_REGION-docker.pkg.dev/$_GAR_PROJECT_ID/$_GAR_REPOSITORY/terraform:$_DOCKER_TAG_VERSION_TERRAFORM
  entrypoint: /bin/bash
  args:
  - -c
  - |
      ./tf-wrapper.sh validate ${BRANCH_NAME} ${_POLICY_REPO} ${PROJECT_ID} CLOUDSOURCE

# [START tf-apply]
- id: 'tf apply'
  name: $_GAR_REGION-docker.pkg.dev/$_GAR_PROJECT_ID/$_GAR_REPOSITORY/terraform:$_DOCKER_TAG_VERSION_TERRAFORM
  entrypoint: /bin/bash
  args:
  - -c
  - |
      ./tf-wrapper.sh apply ${BRANCH_NAME}

artifacts:
  objects:
    location: 'gs://${_ARTIFACT_BUCKET_NAME}/terraform/cloudbuild/apply/${BUILD_ID}'
    paths: ['cloudbuild-tf-apply.yaml', 'tmp_plan/*.tfplan']

logsBucket: 'gs://${_LOG_BUCKET_NAME}'
options:
  worker_pool: '${_PRIVATE_POOL}'
  env:
  - 'TF_IN_AUTOMATION=true'
