xref: /aosp_15_r20/external/google-cloud-java/.cloud/helpers/gcloud-create-project.sh (revision 55e87721aa1bc457b326496a7ca40f3ea1a63287)
1#!/bin/bash
2#
3# Copyright 2022 Google LLC
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      https://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17set -eo pipefail
18
19if [ -n "${GOOGLE_CLOUD_PROJECT}" ]; then
20  echo "Using current GOOGLE_CLOUD_PROJECT: $GOOGLE_CLOUD_PROJECT"
21  return
22fi
23
24currentProject=$(gcloud config get project)
25if [ -n "${currentProject}" ]; then
26  echo -n "Do you want to use the current gcloud project ($currentProject)? (Y|n): "
27  read -r shouldUseCurrent
28  if [[ "$shouldUseCurrent" != n* ]] && [[ "$shouldUseCurrent" != N* ]]; then
29    GOOGLE_CLOUD_PROJECT=$currentProject
30    export GOOGLE_CLOUD_PROJECT
31    return
32  fi
33fi
34
35echo -n "GOOGLE_CLOUD_PROJECT not set. Do you want to create a project? (Y|n): "
36read -r shouldCreate
37if [[ "$shouldCreate" == n* ]] || [[ "$shouldCreate" == N* ]]; then
38  echo "Project required. Exiting."
39  exit 1
40fi
41
42# Ensure required environment variables are set.
43if [ -z "${GOOGLE_CLOUD_FOLDER_ID}" ]; then
44  echo -n "GOOGLE_CLOUD_FOLDER_ID not set. GCP Folder ID: "
45  read -r folder_id
46  export GOOGLE_CLOUD_FOLDER_ID="${folder_id}"
47fi
48if [ -z "${GOOGLE_CLOUD_BILLING_ACCOUNT}" ]; then
49  echo -n "GOOGLE_CLOUD_BILLING_ACCOUNT not set. GCP Billing Account ID: "
50  read -r billing_acct
51  export GOOGLE_CLOUD_BILLING_ACCOUNT="${billing_acct}"
52fi
53if [ -z "${GOOGLE_CLOUD_PROJECT_PREFIX}" ]; then
54  echo -n "GOOGLE_CLOUD_PROJECT_PREFIX not set. Prefix for New Project: "
55  read -r prefix
56  export GOOGLE_CLOUD_PROJECT_PREFIX="${prefix}"
57fi
58
59# Provision GCP Project
60projectId="${GOOGLE_CLOUD_PROJECT_PREFIX}"-"$RANDOM"
61gcloud projects create --folder="$GOOGLE_CLOUD_FOLDER_ID" "$projectId" || exit
62gcloud config set project "$projectId"
63gcloud services enable cloudresourcemanager.googleapis.com
64gcloud beta billing projects link "$projectId" --billing-account="$GOOGLE_CLOUD_BILLING_ACCOUNT"
65GOOGLE_CLOUD_PROJECT=$projectId
66