xref: /aosp_15_r20/external/google-cloud-java/.cloud/helpers/common.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# Find all directories starting with 'java-', sort them, then join
19# with ',' as the delimiter.
20function listAllModules() {
21  # Ensure current directory is repo root.
22  helperDir="$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
23  pushd "$helperDir/../.." >/dev/null
24
25  ls -1 -d java-* | sort | paste -s -d, -
26
27  popd >/dev/null
28}
29
30# Replaces '-' with '_' to get a Terraform output-friendly label
31function getFriendlyOutputName() {
32  echo "$1" | tr '-' _
33}
34
35# Get the output object in JSON format for the given module.
36function getOutput() {
37  friendlyName=$(getFriendlyOutputName "$1")
38  terraform output -json "$friendlyName"
39}
40
41# Parse stdin and get the value associated with the given key.
42function parseJson() {
43  jq ".$1" -r
44}
45
46# Example use: getModuleOutput java-redis redis_network
47function getModuleOutput() {
48  getOutput "$1" | parseJson "$2"
49}
50
51# @returns exit code 0 if list $1 contains entry $2.
52function contains() {
53  echo "$1" | grep -w -q "$2"
54}
55
56# @returns a "new line"-delimited list of active terraform modules
57function getActiveTerraformModules() {
58  terraform state list | awk -F'[/.]' '{print $2}' | uniq
59}
60
61function getTerraformServiceAccountName() {
62  echo "terraform-service-account"
63}
64
65function getTerraformServiceAccountEmail() {
66  if [ -z "${GOOGLE_CLOUD_PROJECT}" ]; then
67    echo "GOOGLE_CLOUD_PROJECT must be defined."
68    exit 1
69  fi
70  echo "$(getTerraformServiceAccountName)@$GOOGLE_CLOUD_PROJECT.iam.gserviceaccount.com"
71}
72