xref: /aosp_15_r20/external/google-cloud-java/.cloud/helpers/gcloud-create-service-account.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
18# Use the project ID in gcloud set-quota-project. Clear the existing quota project directly from
19# the configuration, and re-set.
20gcloud config set project "$GOOGLE_CLOUD_PROJECT"
21sed -i.bak '/quota_project_id/d' ~/.config/gcloud/application_default_credentials.json
22gcloud auth application-default set-quota-project "$GOOGLE_CLOUD_PROJECT"
23
24# Assign permission for current gcloud account to impersonate a service account.
25gcloud_account=$(gcloud config get account)
26gcloud projects add-iam-policy-binding "$GOOGLE_CLOUD_PROJECT" \
27  --member="user:$gcloud_account" \
28  --role="roles/iam.serviceAccountTokenCreator" >/dev/null
29
30# Set up service account for impersonation
31source ./helpers/common.sh
32service_account_name=$(getTerraformServiceAccountName)
33service_account_email=$(getTerraformServiceAccountEmail)
34# If it doesn't already exist, create the service account.
35set +e
36gcloud iam service-accounts describe "$service_account_email" &>/dev/null
37if [[ $? -ne 0 ]]; then
38  gcloud iam service-accounts create "$service_account_name"
39  createdServiceAccount=true
40else
41  createdServiceAccount=false
42fi
43set -e
44
45# Assign permissions to the service account.
46gcloud projects add-iam-policy-binding "$GOOGLE_CLOUD_PROJECT" \
47  --member="serviceAccount:$service_account_email" \
48  --role="roles/owner" >/dev/null
49gcloud projects add-iam-policy-binding "$GOOGLE_CLOUD_PROJECT" \
50  --member="serviceAccount:$service_account_email" \
51  --role="roles/resourcemanager.projectIamAdmin" >/dev/null
52
53# See https://cloud.google.com/blog/topics/developers-practitioners/using-google-cloud-service-account-impersonation-your-terraform-code
54export GOOGLE_IMPERSONATE_SERVICE_ACCOUNT=$service_account_email
55
56if $createdServiceAccount; then
57  echo "Waiting 2m for service account permissions to take effect... [0s elapsed]"
58  sleep 30
59  echo "Waiting 2m for service account permissions to take effect... [30s elapsed]"
60  sleep 30
61  echo "Waiting 2m for service account permissions to take effect... [1m0s elapsed]"
62  sleep 30
63  echo "Waiting 2m for service account permissions to take effect... [1m30s elapsed]"
64  sleep 30
65fi
66