xref: /aosp_15_r20/external/google-cloud-java/.cloud/helpers/gcloud-sync-env.sh (revision 55e87721aa1bc457b326496a7ca40f3ea1a63287)
1#
2# Copyright 2022 Google LLC
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#      https://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16set -eo pipefail
17
18if ! terraform output -json project_id &>/dev/null; then
19  if ! terraform refresh &>/dev/null; then
20    echo "No terraform state found."
21    exit 1
22  fi
23  if ! terraform output -json project_id &>/dev/null; then
24    echo "No project found in terraform state."
25    exit 1
26  fi
27fi
28
29# Ensure the gcloud project matches Terraform's current state.
30terraform_project_id=$(terraform output -raw project_id)
31gcloud_project_id=$(gcloud config get project) || ""
32if [[ "$terraform_project_id" != "$gcloud_project_id" ]]; then
33  echo -n "Do you want to make $terraform_project_id your current gcloud project? (Y/n): "
34  read -r shouldSwitch
35  if [[ "$shouldSwitch" == n* ]] || [[ "$shouldSwitch" == N* ]]; then
36    exit
37  fi
38  gcloud config set project "$terraform_project_id"
39fi
40
41GOOGLE_CLOUD_PROJECT="$terraform_project_id"
42export GOOGLE_CLOUD_PROJECT
43
44source ./helpers/common.sh
45GOOGLE_IMPERSONATE_SERVICE_ACCOUNT=$(getTerraformServiceAccountEmail)
46export GOOGLE_IMPERSONATE_SERVICE_ACCOUNT
47