#!/usr/bin/env bash # shift2eu-inventory-gcp.sh builds a shift2eu inventory of a GCP project. # # Generated by ci/inventoryscripts (make inventory-scripts) from the inventory # guide, docs/guide/inventory.md (its sections "Collect from GCP" and "Build # the GCP inventory"), with the program docs/guide/inventory/gcp.jq embedded # below. Do not edit it by hand: change the guide or the program and generate # it again (PRD #828, ADR 0056). # # Every command it runs with the gcloud CLI only lists, describes, gets or # queries. It reads no credential: the gcloud CLI signs in through its own # credentials. It writes only under --out and in one temporary directory for # the program, which it removes on exit, and what it writes is readable by you # alone (umask 077). Run it with --help. set -eu set -o pipefail umask 077 script=shift2eu-inventory-gcp.sh guide=https://github.com/timothymamo/shift2eu/blob/main/docs/guide/inventory.md usage() { cat <<'USAGE' Usage: shift2eu-inventory-gcp.sh [--project ] [--out ] [--keep-raw] [--with-optional] Builds a shift2eu inventory of a GCP project. It runs the read-only commands of the inventory guide's "Collect from GCP" section, builds /gcp.inventory.json with the guide's program gcp.jq, embedded in this script, and deletes the raw output unless --keep-raw is given. Every command it runs with the gcloud CLI only lists, describes, gets or queries: it creates, changes, deletes or tags nothing in your project. Options: --project The project to collect. Default: the project your CLI is set to, which it prints. --out Where the raw output and the inventory go; default inventories. The raw output goes to /gcp/. --keep-raw Keep the raw output, /gcp/, after the build. --with-optional Also run the command the guide marks optional: the Cloud DNS routed record sets (dns-routing). --help Print this help. It needs the gcloud CLI, signed in as you normally sign in, and jq. Google Cloud Shell has both, signed in: the easy route. On Windows, run it in WSL. The permissions its commands need are in the guide: https://github.com/timothymamo/shift2eu/blob/main/docs/guide/inventory.md#gcp-permissions Exit status: 0 built; 1 built, but a step failed (stderr names it); 2 usage, or no project; 3 a tool is missing; 4 the CLI's reads failed (the sign-in); 5 the build or the inventory's write failed (the raw output is then kept). What it writes is readable by you alone. USAGE } say() { printf '%s: %s\n' "$script" "$*" >&2 } usage_error() { say "$*; run $script --help for its options" exit 2 } # has_control reports whether its argument holds a control character. A value # from an option, the environment or a CLI is checked with it before any # message echoes it: say prints what it is given, so a line break or a # terminal escape in a value would forge a line of the script's own output. # The refusal names where the value came from, never the value. The C1 # controls, U+0080-U+009F, are matched by their UTF-8 bytes (0xC2, then 0x80 to # 0x9F), which no character class marks in every locale: a terminal takes # U+009B as the start of an escape sequence. has_control() { case $1 in *[[:cntrl:]]*) return 0 ;; *$'\xc2'[$'\x80'-$'\x9f']*) return 0 ;; esac return 1 } # dir_is_empty reports whether a directory holds no entry, hidden ones included. dir_is_empty() { for entry in "$1"/* "$1"/.[!.]* "$1"/..?*; do if [ -e "$entry" ] || [ -L "$entry" ]; then return 1 fi done } # private_dir refuses the pre-existing directory $1, named $2 in the messages, # when another local user could write to it: one that is not yours, one whose # mode lets the group or others write, and one with an ACL, which macOS keeps # out of the mode bits. First it refuses $1 when it is a symbolic link (its mode # string in ls -ldn starts with l): one swapped in after an earlier [ -L ] check # would be followed by mkdir -p and by [ -O ]. When $3 is 1 and it is sticky # (the 10th character of its mode string t or T, as /tmp's), its mode may let # others write, but it must be owned by your effective uid or by root (the # numeric owner ls -ldn prints third, against $EUID, the uid [ -O ] and the # writes use): in a sticky directory an entry's own owner, the directory's owner # and root can rename that entry, so a sticky directory another user owns lets # them swap what this run writes there. ls -ldn marks an ACL with a + after the # mode bits (the 11th # character); macOS marks extended attributes with an @ there instead, hiding # the +, so behind an @ ls -lde is read, which prints an ACL's entries after the # mode line: more than that line is an ACL. $4 says what such a user could do, # for the messages. private_dir() { if ! dir_mode=$(ls -ldn -- "$1"); then usage_error "cannot read the mode of $2 with ls -ldn" fi case $dir_mode in l*) usage_error "$2 is a symbolic link: another local user could swap it in after the check, and the run would follow it; move it away, or pass the directory it points to as --out" ;; esac case $3$dir_mode in 1?????????[tT]*) # The third field: skip the mode and the link count, and their blanks. dir_owner=${dir_mode#*[[:blank:]]} dir_owner=${dir_owner#"${dir_owner%%[![:blank:]]*}"} dir_owner=${dir_owner#*[[:blank:]]} dir_owner=${dir_owner#"${dir_owner%%[![:blank:]]*}"} dir_owner=${dir_owner%%[[:blank:]]*} if [ "$dir_owner" != "$EUID" ] && [ "$dir_owner" != 0 ]; then usage_error "$2 is sticky and not yours: whoever owns it can rename what this run writes there; $4, so move it away or pass another --out" fi ;; *) if [ ! -O "$1" ]; then usage_error "$2 is not yours: $4, so move it away or pass another --out" fi case $dir_mode in ?????w* | ????????w*) case $3 in 1) usage_error "$2 is group- or other-writable and not sticky: $4, so move it away or pass another --out" ;; *) usage_error "$2 is group- or other-writable: $4, so move it away or pass another --out" ;; esac ;; esac ;; esac case $dir_mode in ??????????+*) usage_error "$2 has an ACL (the + after its mode in ls -ldn), which can let another local user write to it: $4, so move it away or pass another --out" ;; ??????????@*) # A command substitution drops the trailing line break, so a line break # left in the listing means a line after the mode line. if ! dir_acl=$(ls -lde -- "$1"); then usage_error "cannot read the ACL of $2 with ls -lde" fi case $dir_acl in *$'\n'*) usage_error "$2 has an ACL (the entries ls -lde prints after its mode line), which can let another local user write to it: $4, so move it away or pass another --out" ;; esac ;; esac } # project_name reports whether its argument can be a project's ID: never # empty, never an option, and only the characters an ID holds (a # domain-scoped ID holds a . and a :). project_name() { case $1 in '' | -* | *[!a-z0-9.:-]*) return 1 ;; esac } # resolves_to_root reports whether the directory path $1 resolves to the root # directory, the way mkdir -p and the kernel resolve it, and creates nothing: a # relative path starts at the working directory's physical path, a component # that exists as a directory is followed through cd -P, so a symbolic link # counts as where it points, and a component that does not exist yet is # appended as written, since mkdir -p would create it as a real directory. .. # then goes up one component of the path built so far, which is physical up to # there; . and empty components are skipped. resolves_to_root() { case $1 in /*) root_path=/ ;; *) if ! root_path=$(pwd -P); then return 1 fi ;; esac root_rest=$1 while [ -n "$root_rest" ]; do case $root_rest in */*) root_part=${root_rest%%/*} root_rest=${root_rest#*/} ;; *) root_part=$root_rest root_rest= ;; esac case $root_part in '' | .) ;; ..) root_path=${root_path%/*} if [ -z "$root_path" ]; then root_path=/ fi ;; *) if [ "$root_path" = / ]; then root_next="/$root_part" else root_next="$root_path/$root_part" fi if [ -d "$root_next" ] && root_resolved=$(cd -P -- "$root_next" 2> /dev/null && pwd -P); then root_path=$root_resolved else root_path=$root_next fi ;; esac done [ "$root_path" = / ] } failed= warned= step_skipped() { say "skipped without --with-optional: $1" } # step_mark is the line run_step's ERR trap writes to the step's stderr when a # command of the step fails, at any depth: a loop's failed call too. step_mark='shift2eu-inventory: a command of this step failed' # in_assignment opens each command substitution whose output a step assigns to # a variable (x=$(...)): it notes the substitution's level, where run_step's ERR # trap then marks nothing. The assignment's own status carries the # substitution's failure, and the trap sees it there unless the guide handles # it (if ! x=$(...)); bash 3.2 runs the trap inside the substitution even then, # bash 5 does not, so without this a handled failure failed the step under # macOS's /bin/bash alone (issue #848). in_assignment() { assignment_level=$BASH_SUBSHELL } # run_step runs one collect step, $1, named $2, and reports it. The step runs in # a subshell with pipefail, so a failed call at a pipeline's head fails it, and # an ERR trap: a command that fails at the step's own level ends the step, so # its later commands never run, and one that fails deeper, in a loop the guide # writes, is marked and the loop goes on, as the guide says its loops do. Every # loop runs deeper: a pipeline's loop in the pipeline's subshell, and a loop # that stands as a statement of its own in a subshell the generator adds, whose # status is ignored; the generator refuses a loop anywhere else. The step runs # with noclobber (set -C), so no > of the guide's opens a regular file, a link # or a directory that is already there: one planted in fails the step # instead of being written through (noclobber does not stop a FIFO or a device, # which is why and --out must be yours alone). The step fails when it # ends with a failure or a mark; it warns when it succeeds but writes to # stderr, which the guide's commands do when what they collected may be # incomplete. Its stderr is shown once it ends. Only its stderr is captured: fd # 3 is the script's stdout, opened outside the substitution, so what the step # prints to its stdout goes there and never counts as a warning. run_step() { say "$2" set +e { step_err=$( ( set -C -E -o pipefail step_level=$BASH_SUBSHELL assignment_level= trap 'if [ "$BASH_SUBSHELL" != "$assignment_level" ]; then printf "%s\n" "$step_mark" >&2; if [ "$BASH_SUBSHELL" = "$step_level" ]; then exit 1; fi; fi' ERR "$1" ) 2>&1 1>&3 3>&-) } 3>&1 step_status=$? set -e case $step_err in *"$step_mark"*) step_status=1 ;; esac step_err=${step_err//"$step_mark"$'\n'/} step_err=${step_err//"$step_mark"/} case $step_err in *[![:space:]]*) printf '%s\n' "$step_err" >&2 ;; *) step_err= ;; esac if [ "$step_status" != 0 ]; then say "failed: $2" failed="$failed $2" elif [ -n "$step_err" ]; then say "warned: $2" warned="$warned $2" fi } # The collect steps: the commands of the guide's "Collect from GCP" section, # in its order, one function each, run with project and out set, each by # run_step. A step's statements are not chained with &&: run_step's ERR trap # ends the step at its first failed statement, so a later statement runs only # after the earlier ones succeeded. A loop runs in a subshell whose status is # ignored, so a failed call in it marks the step, and the loop and the step go # on. The guide's # helper function follows them, defined once, so every step has it. # Keep only the one label gcp.jq reads, not the values of any other label. step_1() { gcloud asset search-all-resources --scope="projects/$project" --quiet \ --format='json(name,assetType,location,labels)' | jq '[.[] | if .labels then .labels |= with_entries(select(.key == "goog-gke-node")) else . end]' \ > "$out/assets.json" } # Writes compute-instances.json. step_2() { gcloud compute instances list --project="$project" --quiet \ --format='json(kind,selfLink,machineType,metadata.items[].key,disks[].source,disks[].boot,disks[].autoDelete,networkInterfaces[].stackType,networkInterfaces[].ipv6AccessConfigs[].type)' \ > "$out/compute-instances.json" # The vCPU and memory of the machine types in use, and every disk's size. types="$(in_assignment; jq -r '[.[].machineType // empty | split("/") | last] | unique | join(" ")' "$out/compute-instances.json")" # With no instances there are no types to ask for: write an empty list instead. if [ -n "$types" ]; then gcloud compute machine-types list --project="$project" --filter="name:($types)" --quiet \ --format='json(kind,selfLink,name,zone,guestCpus,memoryMb)' > "$out/compute-machine-types.json" else echo '[]' > "$out/compute-machine-types.json" fi } # Writes compute-disks.json. step_3() { gcloud compute disks list --project="$project" --quiet \ --format='json(kind,name,zone,region,sizeGb)' > "$out/compute-disks.json" } # Writes compute-instance-groups.json. step_4() { gcloud compute instance-groups managed list --project="$project" --quiet \ --format='json(kind,selfLink,status.autoscaler)' > "$out/compute-instance-groups.json" } # Writes compute-snapshots.json. step_5() { gcloud compute snapshots list --project="$project" --quiet \ --format='json(kind,sourceDisk)' > "$out/compute-snapshots.json" } # Writes sql-instances.json. step_6() { gcloud sql instances list --project="$project" --quiet \ --format='json(kind,selfLink,region,databaseVersion,replicaNames,settings.availabilityType,settings.tier,settings.dataDiskSizeGb,settings.backupConfiguration.pointInTimeRecoveryEnabled,settings.backupConfiguration.binaryLogEnabled)' \ > "$out/sql-instances.json" } # Writes storage-buckets.json. step_7() { gcloud storage buckets list --project="$project" --raw --quiet \ --format='json(kind,name,versioning)' > "$out/storage-buckets.json" } # Writes container-clusters.json. step_8() { gcloud container clusters list --project="$project" --quiet \ --format='json(selfLink,location,currentNodeCount,autopilot.enabled,nodePools[].autoscaling.enabled,nodePools[].instanceGroupUrls)' \ > "$out/container-clusters.json" } # Writes pubsub-subscriptions.json. step_9() { gcloud pubsub subscriptions list --project="$project" --quiet \ --format='json(name,deadLetterPolicy.deadLetterTopic)' > "$out/pubsub-subscriptions.json" } # Load balancers: global and every region's, each list by default. step_10() { gcloud compute url-maps list --project="$project" --quiet \ --format='json(selfLink,region,defaultService,defaultRouteAction.weightedBackendServices[].backendService,defaultRouteAction.requestMirrorPolicy.backendService,defaultCustomErrorResponsePolicy.errorService,pathMatchers[].defaultService,pathMatchers[].defaultRouteAction.weightedBackendServices[].backendService,pathMatchers[].defaultRouteAction.requestMirrorPolicy.backendService,pathMatchers[].defaultCustomErrorResponsePolicy.errorService,pathMatchers[].pathRules[].service,pathMatchers[].pathRules[].routeAction.weightedBackendServices[].backendService,pathMatchers[].pathRules[].routeAction.requestMirrorPolicy.backendService,pathMatchers[].pathRules[].customErrorResponsePolicy.errorService,pathMatchers[].routeRules[].service,pathMatchers[].routeRules[].routeAction.weightedBackendServices[].backendService,pathMatchers[].routeRules[].routeAction.requestMirrorPolicy.backendService,pathMatchers[].routeRules[].customErrorResponsePolicy.errorService)' \ > "$out/compute-url-maps.json" } # Writes compute-backend-services.json. step_11() { gcloud compute backend-services list --project="$project" --quiet \ --format='json(kind,selfLink,region,protocol,loadBalancingScheme,ipAddressSelectionPolicy)' \ > "$out/compute-backend-services.json" } # Writes compute-forwarding-rules.json. step_12() { gcloud compute forwarding-rules list --project="$project" --quiet \ --format='json(kind,selfLink,region,IPProtocol,ipVersion,target,backendService)' \ > "$out/compute-forwarding-rules.json" } # Writes compute-target-pools.json. step_13() { gcloud compute target-pools list --project="$project" --quiet \ --format='json(kind,selfLink,region)' > "$out/compute-target-pools.json" } # Writes compute-target-https-proxies.json. step_14() { gcloud compute target-https-proxies list --project="$project" --quiet \ --format='json(kind,selfLink,urlMap)' > "$out/compute-target-https-proxies.json" } # Writes compute-target-http-proxies.json. step_15() { gcloud compute target-http-proxies list --project="$project" --quiet \ --format='json(kind,selfLink,urlMap)' > "$out/compute-target-http-proxies.json" } # Cloud DNS managed zones: each zone's number, name, visibility and whether it is # signed. The list writes no project, so jq adds it, for the join with the asset # listing, which names a zone by its number. step_16() { gcloud dns managed-zones list --project="$project" --quiet \ --format='json(kind,id,name,visibility,dnssecConfig.state)' | jq --arg p "$project" '[.[] | .project = $p]' > "$out/dns-managed-zones.json" } # Optional, for dns-routing only (needs dns.resourceRecordSets.list, see "GCP permissions"): # how many record sets of each public zone route by a policy, a count and no record. step_17() { jq -r '.[] | select(.visibility == "public") | "\(.id) \(.name)"' "$out/dns-managed-zones.json" | while read -r id zone; do if routed_types=$(in_assignment; gcloud dns record-sets list --project="$project" --zone="$zone" --quiet \ --filter='routingPolicy:*' --format='value(type)'); then printf '%s' "$routed_types" | jq -R -s --arg p "$project" --arg i "$id" \ '{project: $p, id: $i, routedRecordSets: (split("\n") | map(select(. != "")) | length)}' fi done | jq -s . > "$out/dns-routed-record-sets.json" } # Memorystore, per region: the regions come from the asset listing, and each # list runs only in a region that holds its asset type. step_18() { # In a subshell of its own, so a failed call in the loop marks the step and the # loop goes on (run_step). Its closing : keeps the loop's status from ending the # step. ( for region in $(jq -r '[.[] | select(.assetType | test("^(redis|memorystore)\\.googleapis\\.com/")) | .name | capture("/locations/(?[^/]+)/").r] | unique | .[]' "$out/assets.json"); do if has redis.googleapis.com/Instance "$region"; then gcloud redis instances list --project="$project" --region="$region" --quiet \ --format='json(name,tier,memorySizeGb,replicaCount,locationId,alternativeLocationId,nodes[].zone,persistenceConfig.persistenceMode)' fi if has redis.googleapis.com/Cluster "$region"; then gcloud redis clusters list --project="$project" --region="$region" --quiet \ --format='json(name,shardCount,replicaCount,nodeType,sizeGb,zoneDistributionConfig.mode,persistenceConfig.mode)' fi if has memorystore.googleapis.com/Instance "$region"; then gcloud memorystore instances list --project="$project" --location="$region" --quiet \ --format='json(name,mode,shardCount,replicaCount,nodeType,nodeConfig.sizeGb,zoneDistributionConfig.mode,persistenceConfig.mode)' fi done > "$out/memorystore.json" : ) } # Filestore and Artifact Registry, when the asset listing holds one of theirs. step_19() { if has file.googleapis.com/Instance; then gcloud filestore instances list --project="$project" --quiet \ --format='json(name,tier,fileShares[].capacityGb,protocol)' > "$out/filestore-instances.json" else echo '[]' > "$out/filestore-instances.json" fi if has artifactregistry.googleapis.com/Repository; then gcloud artifacts repositories list --project="$project" --location=all --quiet \ --format='json(name,format,mode)' > "$out/artifacts-repositories.json" else echo '[]' > "$out/artifacts-repositories.json" fi } # Managed Service for Apache Kafka, per region the asset listing names a cluster in, # merged into one list (an empty one when there is none): only each cluster's name # and capacity, never its bootstrap address or network access. step_20() { # In a subshell of its own, so a failed call in the loop marks the step and the # loop goes on (run_step). Its closing : keeps the loop's status from ending the # step. ( for region in $(jq -r '[.[] | select(.assetType == "managedkafka.googleapis.com/Cluster") | .name | capture("/locations/(?[^/]+)/").r] | unique | .[]' "$out/assets.json"); do gcloud managed-kafka clusters list --project="$project" --location="$region" --quiet \ --format='json(name,capacityConfig)' done | jq -s 'add // []' > "$out/managed-kafka-clusters.json" : ) } # The Cloud Run service each 2nd gen function runs on, per region with functions. step_21() { # In a subshell of its own, so a failed call in the loop marks the step and the # loop goes on (run_step). Its closing : keeps the loop's status from ending the # step. ( for region in $(jq -r '[.[] | select(.assetType == "cloudfunctions.googleapis.com/Function") | .name | capture("/locations/(?[^/]+)/").r] | unique | .[]' "$out/assets.json"); do gcloud functions list --project="$project" --v2 --regions="$region" --quiet \ --format='json(name,serviceConfig.service)' done > "$out/functions.json" : ) } # Whether the asset listing holds an asset type, in a region when one is given: # the Memorystore, Filestore and Artifact Registry lists below run only then. has() { jq -e --arg t "$1" --arg r "${2:-}" \ 'any(.[]; .assetType == $t and ($r == "" or (.name | contains("/locations/" + $r + "/"))))' \ "$out/assets.json" > /dev/null; } # The options. out_dir=inventories keep_raw=0 with_optional=0 project= while [ "$#" -gt 0 ]; do case $1 in --project) if [ "$#" -lt 2 ]; then usage_error "--project needs a value" fi if has_control "$2"; then usage_error "--project holds a control character: pass the project ID alone" fi if ! project_name "$2"; then usage_error "--project $2 is no project ID" fi project=$2 shift 2 ;; --out) if [ "$#" -lt 2 ]; then usage_error "--out needs a value" fi out_dir=$2 shift 2 ;; --keep-raw) keep_raw=1 shift ;; --with-optional) with_optional=1 shift ;; --help | -h) usage exit 0 ;; *) if has_control "$1"; then usage_error "an unknown option holds a control character" fi usage_error "unknown option: $1" ;; esac done # --out: never empty, never /, never an option, never a symbolic link itself, # never a path that resolves to the root directory (/./, /x/../..). Neither # --out nor TMPDIR, which messages echo, holds a control character. if has_control "$out_dir"; then usage_error "--out holds a control character: pass a plain directory path" fi if has_control "${TMPDIR:-}"; then usage_error "TMPDIR holds a control character: set it to a plain directory path, or unset it" fi case $out_dir in '') usage_error "--out is empty" ;; -*) usage_error "--out $out_dir starts with -" ;; esac while [ "$out_dir" != / ] && [ "${out_dir%/}" != "$out_dir" ]; do out_dir=${out_dir%/} done if [ "$out_dir" = / ]; then usage_error "--out / is refused: pass a directory of its own" fi if [ -L "$out_dir" ]; then usage_error "--out $out_dir is a symbolic link: pass the directory it points to" fi if resolves_to_root "$out_dir"; then usage_error "--out $out_dir resolves to the root directory, /, and is refused: pass a directory of its own" fi # A --out that is there already is yours alone: whoever can write to it could # rename the raw output's directory in it away mid-run and put one of their own # in its place. A sticky one is safe from that only when it is yours or root's, # as /tmp is on Linux: there an entry's own owner, the directory's owner and # root can rename it. It is checked again once mkdir -p has made it. if [ -d "$out_dir" ]; then private_dir "$out_dir" "--out $out_dir" 1 "another local user could swap the raw output's directory in it for one of their own while this run writes into it" fi raw="$out_dir/gcp" inventory="$out_dir/gcp.inventory.json" if [ -L "$raw" ]; then usage_error "$raw is a symbolic link: move it away or pass another --out" fi if [ -e "$raw" ]; then if [ ! -d "$raw" ]; then usage_error "$raw exists and is no directory: move it away or pass another --out" fi # A directory another local user owns or can write to, sticky or not, could # get a file or a link planted where this run writes, so it is refused. private_dir "$raw" "$raw" 0 "another local user could plant a file this run writes into" if ! dir_is_empty "$raw"; then usage_error "$raw is not empty: two runs never merge their output, so move it away or pass another --out" fi fi if [ -L "$inventory" ]; then usage_error "$inventory is a symbolic link: move it away or pass another --out" fi # Tools. say "checking the tools: the gcloud CLI and jq" if ! command -v jq > /dev/null 2>&1; then say "jq is not on PATH: install it, as the guide's Before you start asks ($guide#before-you-start)" exit 3 fi cli="gcloud" if ! command -v "$cli" > /dev/null 2>&1; then say "the gcloud CLI is not on PATH: install the Google Cloud CLI, as the guide's Before you start asks ($guide#before-you-start)" exit 3 fi # The output directories: /gcp/ is created without -p, and only a # directory this run created is ever removed. --out is checked again once it is # there, whoever made it: another local user could have made it between the # check above and mkdir -p. if ! mkdir -p -- "$out_dir"; then usage_error "cannot create --out $out_dir" fi private_dir "$out_dir" "--out $out_dir" 1 "another local user could swap the raw output's directory in it for one of their own while this run writes into it" raw_created=0 raw_keep=$keep_raw tmp_dir= staged= # remove_raw removes the raw output this run wrote: /gcp/ when the run # created it. A /gcp/ that was there before the run, empty, is kept with # what the run wrote into it, since the run removes only a directory it created. remove_raw() { if [ "$raw_created" = 1 ]; then rm -r -- "$raw" raw_created=0 removed="the raw output in $raw" else removed="nothing: $raw was there before this run, so it is kept with the raw output in it; delete that once you are done" fi } on_exit() { status=$? trap - EXIT INT TERM HUP set +e if [ "$raw_keep" = 0 ]; then remove_raw fi if [ -n "$tmp_dir" ]; then rm -r -- "$tmp_dir" fi if [ -n "$staged" ] && [ -f "$staged" ]; then rm -f -- "$staged" fi exit "$status" } trap on_exit EXIT trap 'exit 130' INT trap 'exit 143' TERM trap 'exit 129' HUP if [ ! -d "$raw" ]; then if ! mkdir -- "$raw"; then usage_error "cannot create $raw" fi raw_created=1 fi # The project: --project, or the one the CLI is set to, a local read. if [ -z "$project" ]; then say "reading the project your CLI is set to with gcloud config get-value project" project=$(gcloud config get-value project 2> /dev/null) || project= if [ -z "$project" ]; then usage_error "no project: your CLI is set to none, so pass --project " fi if has_control "$project"; then usage_error "the project gcloud config get-value project named holds a control character: pass --project " fi if ! project_name "$project"; then usage_error "your CLI is set to the project $project, which is no project ID: pass --project " fi fi say "the project: $project" # Sign-in, which also proves the project readable. say "checking the sign-in with gcloud projects describe $project, its answer discarded" if ! gcloud projects describe "$project" --quiet > /dev/null; then say "gcloud projects describe $project failed: the CLI is not signed in, or may not read the project; sign in as you normally do; the permissions are at $guide#gcp-permissions" exit 4 fi # Collect. if [ "$with_optional" = 0 ]; then step_skipped 'Optional, for dns-routing only (needs dns.resourceRecordSets.list, see "GCP permissions"): how many record sets of each public zone route by a policy, a count and no record.' fi collect_steps() { run_step step_1 'Keep only the one label gcp.jq reads, not the values of any other label.' run_step step_2 'compute-instances.json' run_step step_3 'compute-disks.json' run_step step_4 'compute-instance-groups.json' run_step step_5 'compute-snapshots.json' run_step step_6 'sql-instances.json' run_step step_7 'storage-buckets.json' run_step step_8 'container-clusters.json' run_step step_9 'pubsub-subscriptions.json' run_step step_10 'Load balancers: global and every region'\''s, each list by default.' run_step step_11 'compute-backend-services.json' run_step step_12 'compute-forwarding-rules.json' run_step step_13 'compute-target-pools.json' run_step step_14 'compute-target-https-proxies.json' run_step step_15 'compute-target-http-proxies.json' run_step step_16 'Cloud DNS managed zones: each zone'\''s number, name, visibility and whether it is' if [ "$with_optional" = 1 ]; then run_step step_17 'Optional, for dns-routing only (needs dns.resourceRecordSets.list, see "GCP permissions"):' fi run_step step_18 'Memorystore, per region: the regions come from the asset listing, and each' run_step step_19 'Filestore and Artifact Registry, when the asset listing holds one of theirs.' run_step step_20 'Managed Service for Apache Kafka, per region the asset listing names a cluster in,' run_step step_21 'The Cloud Run service each 2nd gen function runs on, per region with functions.' } out="$raw" say "collecting the project $project into $raw" collect_steps report_steps() { if [ -n "$failed" ]; then say "these steps failed, and the inventory lacks what they collect (their errors are above):$failed" fi if [ -n "$warned" ]; then say "these steps warned, and what they collected may be incomplete (their warnings are above):$warned" fi } # build_failed ends a run whose inventory could not be built or written: the # raw output is kept, and an earlier run's inventory is left as it was. build_failed() { raw_keep=1 report_steps say "$1, so no inventory was written; the raw output is kept in $raw" if [ -f "$inventory" ]; then say "$inventory is an earlier run's inventory, left as it was" fi exit 5 } # The guide's program, gcp.jq, byte for byte, in a temporary directory made # only now, so a failure to make it keeps what the collect wrote. if ! tmp_dir=$(mktemp -d "${TMPDIR:-/tmp}/shift2eu-inventory.XXXXXX"); then tmp_dir= build_failed "cannot create a temporary directory for the embedded gcp.jq (TMPDIR=${TMPDIR:-/tmp})" fi program="$tmp_dir/gcp.jq" built="$tmp_dir/inventory.json" if ! cat > "$program" <<'SHIFT2EU_JQ_PROGRAM' # gcp.jq turns the output of the read-only gcloud calls in docs/guide/inventory.md # into a shift2eu inventory file, schema version 2 # (docs/adr/0025-json-inventory-file-format-v2.md). Run it with -n on every file # the guide's commands wrote: # # jq -n -f docs/guide/inventory/gcp.jq inventories/gcp/*.json > inventories/gcp.inventory.json # # The Cloud Asset Inventory listing (gcloud asset search-all-resources) is the list # of resources; the other calls only add the details the capabilities need. Each # element of each input is recognised by its shape, not by its file name. The # guide's --format projections keep only the fields read here; the full output is # read the same way: # # {"assetType": ..., "name": "//..."} asset search-all-resources # {"kind": "compute#instance"} compute instances list # {"kind": "compute#instanceGroupManager"} compute instance-groups managed list # {"kind": "compute#machineType"} compute machine-types list # {"kind": "compute#disk"} compute disks list # {"kind": "compute#snapshot"} compute snapshots list # {"kind": "sql#instance"} sql instances list # {"kind": "storage#bucket"} storage buckets list --raw # {"selfLink": "https://container..."} container clusters list # {"name": "projects/.../subscriptions/.."} pubsub subscriptions list # {"selfLink": ".../urlMaps/..."} compute url-maps list # {"selfLink": ".../backendServices/..."} compute backend-services list # {"selfLink": ".../forwardingRules/..."} compute forwarding-rules list # {"selfLink": ".../targetPools/..."} compute target-pools list # {"selfLink": ".../targetHttpsProxies/.."} compute target-https-proxies list # {"selfLink": ".../targetHttpProxies/.."} compute target-http-proxies list # {"name": ".../instances/..", "memorySizeGb"} redis instances list # {"name": ".../clusters/..", "shardCount"} redis clusters list # {"name": ".../instances/..", "nodeConfig"} memorystore instances list # {"name": ".../instances/..", "fileShares"} filestore instances list # {"name": ".../repositories/..", "format"} artifacts repositories list # {"name": ".../functions/..", "serviceConfig"} functions list # {"name": ".../clusters/..", "capacityConfig"} managed-kafka clusters list # {"kind": "dns#managedZone", "project"} dns managed-zones list, with the # project the guide's jq filter adds # {"project", "id", "routedRecordSets"} dns record-sets list, reduced to a # count per zone by the guide # # A Cloud DNS managed zone is its asset row, joined to the managed-zones list on # the project and the zone's number: the asset row names a zone by the numeric # `id` Google assigned it (//dns.googleapis.com/projects/PROJECT_ID/managedZones/ # ZONE_NUMBER, https://cloud.google.com/asset-inventory/docs/resource-name-format), # never by its name. The list writes no project, so the guide adds it, and an # entry without one joins no row. A joined zone's ID is its managed zone's name; # a zone that joins nothing keeps the asset row's number. A public zone is network.dns with # no region (Google serves it from name servers it picks); a private zone # (forwarding and peering zones included) and a zone the list does not hold # stay unclassified. A public zone is dnssec when dnssecConfig.state is on or # transfer, and dns-routing when the record-set count, the number of its record # sets with a routingPolicy, is above 0. No record set is ever read here. # # Resource IDs are short (the last part of the resource name), never the full name, # which carries the project. Anything it cannot classify is "unclassified" with its # rawType (a Cloud Asset Inventory asset type), so it shows up as a blocker. # # A load balancer is one URL map, one backend service no URL map names, or one # target pool, and those three come from the compute lists, not from the asset # listing, which may not hold a regional URL map: the asset rows of URL maps, # backend services, target pools, forwarding rules and target proxies are left # out, so nothing is listed twice. The forwarding rules and target proxies are # the load balancer's frontends: they are read for its protocol and IP version, # then left out. A backend service of scheme INTERNAL_SELF_MANAGED (a service # mesh: no load balancer runs in front of its backends) is no load balancer, nor # is a URL map that names only such services. A load balancer Kubernetes created # is kept: URL maps and backend services carry no labels, and no documented rule # tells them apart. # # The nodes of a GKE cluster are left out, the cluster stands for them: the # managed instance groups its node pools name (instanceGroupUrls), and instances # and disks labelled goog-gke-node. An instance a managed instance group created # is left out with its boot disk, the group stands for it. # # The size comes from the calls too: an instance's vCPU and memory from its # machine type (compute machine-types list, the instance's machineType URL # matched to the type's selfLink, zone included), a disk's GiB (compute # disks list, sizeGb, which the Compute API writes as a string; a regional disk # is matched by its region), and a Cloud SQL instance's storage # (settings.dataDiskSizeGb, a string too), its vCPU and memory when its tier is # a custom one (db-custom--; any other tier gives neither) and # a count of 1 when it is a single-node instance (availabilityType ZONAL; a # REGIONAL one with a standby gets no count, how many nodes a target bills for # a standby is the target's to say). A Memorystore cache's memory is per node # (a Redis instance's memorySizeGb, a Valkey instance's nodeConfig.sizeGb) and its # count its nodes (a Redis instance's nodes, or for a STANDARD_HA one that lists # none its replicaCount plus one; a cluster's or Valkey instance's shards times # one plus their replicas); a Redis cluster names only its whole memory # (sizeGb), so it gets a count and no memory. A Filestore instance's storage is # the sum of its shares' capacityGb (a string). A Managed Service for Apache # Kafka cluster's capacityConfig is its total vCPU and memory over the brokers # Google provisions, max(3, ceiling(vCPU / 15)) of them, all with the same vCPU # (https://cloud.google.com/managed-service-for-apache-kafka/docs/brokers): the # count is that number and the vCPU one broker's share. The memory share is # inferred: memory is provisioned per cluster at a fixed vCPU:GiB ratio # (https://cloud.google.com/managed-service-for-apache-kafka/docs/reference/rest/v1/CapacityConfig), # so each broker gets an equal share of it. The brokers have a disk, but the list # gives no disk size (capacityConfig holds only vcpuCount and memoryBytes), so # no storageGiB is written. The GB of these APIs are taken # as GiB. A number no call gives is left out, never guessed. The workload, # relations and monthlyCost fields are the user's to add by hand; this program # never writes them. # A key that names the same resource in an asset name # (//compute.googleapis.com/projects/p/zones/z/instances/n), a selfLink # (https://www.googleapis.com/compute/v1/projects/p/zones/z/instances/n) and a # Pub/Sub name (projects/p/subscriptions/s): the path from "projects/" on, with # zones and regions written as locations. A bucket's key is its name. def key: if . == null then null else (if test("projects/") then capture("(?projects/.*)$").k else sub("^//[^/]+/"; "") end) | gsub("/(zones|regions)/"; "/locations/") end; # A zone: europe-west1-b. def is_zone: test("^[a-z]+-[a-z]+[0-9]+-[a-z]$"); # The region of a location: a zone loses its suffix, global is none. def location_region: if . == null or . == "" or . == "global" then null elif is_zone then sub("-[a-z]$"; "") else ascii_downcase end; # The capability $name when the condition is true. def cap($name; cond): if cond then $name else empty end; # Gives every resource a distinct ID: two resources with the same short ID get # their rawType and region appended, and any still equal a counter. def unique_ids: def suffix: " (" + (.rawType // "unknown") + (if .region then ", " + .region else "" end) + ")"; group_by(.id) | map(if length == 1 then . else map(.id += suffix) end) | add // [] | group_by(.id) | map(if length == 1 then . else to_entries | map(.value.id += " #" + (.key + 1 | tostring) | .value) end) | add // []; # A size object without the fields no call gave; null when none is left. def size_of(fields): fields | with_entries(select(.value != null)) | if . == {} then null else . end; # Writes the inventory document: no empty region or capabilities, capabilities # sorted, identical resources listed once. def inventory($source): map( {id, rawType, category, region, capabilities, size} | if .region == null or .region == "" then del(.region) else . end | if .size == null then del(.size) else . end | .capabilities = ((.capabilities // []) | unique) | if .capabilities == [] then del(.capabilities) else . end ) | unique | unique_ids | sort_by(.id) | {schemaVersion: 2, source: $source, resources: .}; # The details of one kind, by key. def details(f; k): map(select(f)) | INDEX(k); # A compute object of a collection, recognised by its selfLink path: the # url-maps list writes no kind. def compute_of($collection): (.selfLink? // "") | test("/" + $collection + "/[^/]+$"); # A resource name of the API calls (projects/p/locations/l//n). def named_in($collection): (.name? // "") | test("^projects/[^/]+/locations/[^/]+/" + $collection + "/[^/]+$"); # The region of a compute selfLink: none for a global resource. def link_region: (capture("/regions/(?[^/]+)/") // {r: null}).r; # A number the API writes as a string (int64) or a number. def number: if . == null then null else tonumber end; # The keys of the backend services a URL map names, in any of its routes, its # route actions' weighted services and mirror policies included. A backend # bucket is not a backend service. def named_services: [.. | strings | select(test("/backendServices/[^/]+$")) | key] | unique; # The key of the load balancer a forwarding rule reaches: its backend service, # its target pool, or the URL map or backend service of its target proxy. def reaches($proxies): if .backendService then .backendService | key elif (.target // "") | test("/targetPools/") then .target | key elif .target then ($proxies[.target | key] // {}) | (.urlMap // .service // empty) | key else empty end; [inputs | if type == "array" then .[] else . end | objects] as $all | ($all | details(.kind? == "compute#instance"; .selfLink | key)) as $instances | ($all | details(.kind? == "compute#instanceGroupManager"; .selfLink | key)) as $groups | ($all | details(.kind? == "sql#instance"; .selfLink | key)) as $sql | ($all | details(.kind? == "compute#machineType"; .selfLink | key)) as $machinetypes | ($all | details(.kind? == "compute#disk"; (.zone // .region) + "/disks/" + .name | key)) as $disks | ($all | details(.kind? == "storage#bucket"; .name)) as $buckets | ($all | details((.selfLink? // "") | startswith("https://container.googleapis.com/"); .selfLink | key)) as $clusters | ($all | details((.name? // "") | test("^projects/[^/]+/subscriptions/"); .name | key)) as $subscriptions | ([$all[] | select(.kind? == "compute#snapshot") | .sourceDisk? // empty | key] | unique) as $snapshotted | ([$clusters[] | .nodePools[]?.instanceGroupUrls[]? | key] | unique) as $nodegroups # The disks a managed instance group's instances delete with them (autoDelete), # boot disks or not: the group stands for them. | ([$instances[] | select([.metadata.items[]?.key] | index("created-by")) | .disks[]? | select(.autoDelete == true) | .source // empty | key] | unique) as $groupdisks | ($all | details(named_in("instances") and (has("memorySizeGb") or (.tier? | IN("BASIC", "STANDARD_HA"))); .name | key)) as $redis | ($all | details(named_in("clusters") and (has("shardCount") or has("nodeType")); .name | key)) as $redisclusters | ($all | details(named_in("instances") and (has("nodeConfig") or has("shardCount")) and (has("memorySizeGb") or has("fileShares") | not); .name | key)) as $valkey | ($all | details(named_in("instances") and has("fileShares"); .name | key)) as $filestore | ($all | details(named_in("repositories") and has("format"); .name | key)) as $repositories | ($all | details(named_in("clusters") and has("capacityConfig"); .name | key)) as $kafka # Cloud DNS: the managed zones and the routed record-set counts, keyed as the # zone's asset name is (projects/p/managedZones/), from the project the # guide adds and the zone's number (`id`, a string in gcloud's and the API's # JSON; a number is taken too, but only jq 1.7 or later keeps a 19-digit number # exact: an earlier jq holds it as a double, rounds it and joins nothing, which # only a hand-edited file can meet, as gcloud writes a string). | (def zone_key: "projects/" + .project + "/managedZones/" + (.id | tostring) | key; def joinable: (.project? | type) == "string" and (.id? | type | IN("string", "number")); ($all | details(.kind? == "dns#managedZone" and joinable; zone_key)) as $dnszones | ($all | details(has("routedRecordSets") and joinable; zone_key)) as $dnsrouted | {zones: $dnszones, routed: $dnsrouted}) as $dns # A Filestore instance has snapshots when a snapshot asset is named under it. | ([$all[] | select(.assetType? == "file.googleapis.com/Snapshot") | .name | key | sub("/snapshots/[^/]+$"; "")] | unique) as $filesnapshotted # The Cloud Run services 2nd gen Cloud Functions run on. | ([$all[] | select(named_in("functions")) | .serviceConfig.service? // empty | key] | unique) as $functionservices | ($all | details(compute_of("urlMaps"); .selfLink | key)) as $urlmaps | ($all | details(compute_of("backendServices"); .selfLink | key)) as $backends | ($all | details(compute_of("targetPools"); .selfLink | key)) as $pools | ($all | details(compute_of("target(Https?|Grpc|Tcp|Ssl)Proxies"); .selfLink | key)) as $proxies | [$all[] | select(compute_of("forwardingRules"))] as $frontends | ([$urlmaps[] | named_services[]] | unique) as $named | (def mesh: $backends[.].loadBalancingScheme? == "INTERNAL_SELF_MANAGED"; [$urlmaps | to_entries[] | {key, link: .value.selfLink, rawType: "compute.googleapis.com/UrlMap", services: (.value | named_services)} # A URL map of a service mesh names only mesh services. | select((.services | length) == 0 or any(.services[]; mesh | not))] + [$backends | to_entries[] | select((.key | IN($named[]) | not) and (.key | mesh | not)) | {key, link: .value.selfLink, rawType: "compute.googleapis.com/BackendService", services: [.key]}] + [$pools | to_entries[] | {key, link: .value.selfLink, rawType: "compute.googleapis.com/TargetPool", services: []}] ) as $loadbalancers | [ $all[] | select(.assetType? and ((.name? // "") | startswith("//"))) # A GKE node or its disk: the cluster stands for it. | select(.labels["goog-gke-node"]? == null) | (.name | key) as $key | { id: (.name | split("/") | last), rawType: .assetType, region: (.location | location_region) } as $base | if .assetType == "compute.googleapis.com/Instance" then $instances[$key] as $d # An instance a managed instance group created is left out: the group # stands for it. | select([$d.metadata.items[]?.key] | index("created-by") | not) | $base + {category: "compute.vm", capabilities: [ cap("ipv6"; any($d.networkInterfaces[]?; (.ipv6AccessConfigs // []) | length > 0 or .stackType == "IPV4_IPV6")) ], # An instance the asset listing names but the instance list does not # (a failed list) has no machine type, and so no size. size: ($machinetypes[($d.machineType | key) // ""] as $m | if $m == null then null else size_of({vcpus: $m.guestCpus, memoryGiB: (if $m.memoryMb == null then null else $m.memoryMb / 1024 end)}) end)} elif .assetType == "compute.googleapis.com/InstanceGroupManager" then # The group of a GKE node pool is left out: the cluster stands for it. select($key | IN($nodegroups[]) | not) | $base + {category: "compute.vm", capabilities: [ cap("autoscaling"; $groups[$key].status.autoscaler? != null), cap("zone-high-availability"; .name | test("/regions/")) ]} elif .assetType == "baremetalsolution.googleapis.com/Instance" then # A Bare Metal Solution server: a dedicated physical server # (ADR 0023). $base + {category: "compute.baremetal"} elif .assetType == "compute.googleapis.com/Disk" then # A disk a managed instance group's instance deletes with it goes with # the instance. # Google Cloud encrypts all data at rest. select($key | IN($groupdisks[]) | not) | $base + {category: "storage.block", capabilities: [ "encryption-at-rest", cap("snapshots"; $key | IN($snapshotted[])) ], size: size_of({storageGiB: ($disks[$key].sizeGb? // null | if . == null then null else tonumber end)})} elif .assetType == "storage.googleapis.com/Bucket" then $buckets[$key] as $d | $base + {category: "storage.object", capabilities: [ "encryption-at-rest", cap("object-versioning"; ($d.versioning.enabled? // $d.versioning_enabled? // false) == true) ]} elif .assetType == "sqladmin.googleapis.com/Instance" then # The engine decides the category; without the sql instances list it is # unknown, so unclassified. $sql[$key] as $d | (($d.databaseVersion? // "") as $v | if $v | startswith("POSTGRES_") then "database.postgresql" elif $v | startswith("MYSQL_") then "database.mysql" else "unclassified" end) as $category | $base + {category: $category, region: ($d.region // $base.region), capabilities: (if $category == "unclassified" then [] else [ "encryption-at-rest", cap("point-in-time-restore"; $d.settings.backupConfiguration.pointInTimeRecoveryEnabled == true or ($category == "database.mysql" and $d.settings.backupConfiguration.binaryLogEnabled == true)), cap("zone-high-availability"; $d.settings.availabilityType == "REGIONAL"), cap("read-replicas"; ($d.replicaNames // []) | length > 0) ] end), # Only a custom tier names its vCPU and memory; a single-node # (ZONAL) instance is one instance, one with a standby gets no count. size: (if $category == "unclassified" then null else (($d.settings.tier? // "") | capture("^db-custom-(?[0-9]+)-(?[0-9]+)$")? // null) as $t | size_of({ vcpus: (if $t == null then null else $t.c | tonumber end), memoryGiB: (if $t == null then null else ($t.m | tonumber) / 1024 end), storageGiB: ($d.settings.dataDiskSizeGb? // null | if . == null then null else tonumber end), count: (if $d.settings.availabilityType? == "ZONAL" then 1 else null end) }) end)} elif .assetType == "container.googleapis.com/Cluster" then $clusters[$key] as $d | (.location // "") as $location | $base + {category: "kubernetes.managed", capabilities: [ cap("zone-high-availability"; ($location | is_zone | not) and $location != ""), cap("node-high-availability"; ($d.currentNodeCount // 0) >= 2), cap("autoscaling"; $d.autopilot.enabled? == true or any($d.nodePools[]?; .autoscaling.enabled == true)) ]} elif .assetType == "cloudfunctions.googleapis.com/Function" or .assetType == "cloudfunctions.googleapis.com/CloudFunction" then $base + {category: "serverless.function"} elif .assetType == "run.googleapis.com/Service" then # A 2nd gen Cloud Function runs on a Cloud Run service of its own, the # one its serviceConfig.service names: the function stands for it. Any # other Cloud Run service is a container the provider runs and scales. select($key | IN($functionservices[]) | not) | $base + {category: "serverless.container"} elif .assetType == "pubsub.googleapis.com/Topic" then # A topic copies each message to every subscription; Google Cloud # encrypts it at rest. A dead-letter topic is set on a subscription, # never on a topic, so the subscription carries dead-letter-queue. $base + {category: "messaging.topic", capabilities: ["encryption-at-rest"]} elif .assetType == "pubsub.googleapis.com/Subscription" then $base + {category: "messaging.queue", capabilities: [ cap("dead-letter-queue"; $subscriptions[$key].deadLetterPolicy.deadLetterTopic? != null) ]} elif .assetType == "redis.googleapis.com/Instance" then # Memorystore for Redis: STANDARD_HA has a replica that takes over, and # its nodes in two or more zones, or an alternativeLocationId other than # its locationId, either one, make it zone redundant. Each node holds # the whole data set. $redis[$key] as $d | ($d.tier? == "STANDARD_HA") as $ha | $base + {category: "cache.redis", capabilities: [ "encryption-at-rest", cap("node-high-availability"; $ha), cap("zone-high-availability"; $ha and (([$d.nodes[]?.zone] | unique | length) >= 2 or ($d.alternativeLocationId? != null and $d.alternativeLocationId != $d.locationId))), cap("snapshots"; $d.persistenceConfig.persistenceMode? == "RDB") ], size: (if $d == null then null else size_of({ memoryGiB: $d.memorySizeGb, count: ((($d.nodes // []) | length) as $n | if $n > 0 then $n elif $d.tier == "BASIC" then 1 # A STANDARD_HA instance that lists no nodes: the primary and # its replicas. elif $d.tier == "STANDARD_HA" and $d.replicaCount != null then $d.replicaCount + 1 else null end) }) end)} elif .assetType == "redis.googleapis.com/Cluster" or .assetType == "memorystore.googleapis.com/Instance" then # Memorystore for Redis Cluster and for Valkey: a replica per shard # takes over, and with one the cluster survives a zone unless all of it # is in one zone (MULTI_ZONE is the default). A Redis cluster is # sharded; a listed Valkey instance is unless its mode is # CLUSTER_DISABLED or its deprecated spelling STANDALONE; an unset or # MODE_UNSPECIFIED mode means CLUSTER. (.assetType == "redis.googleapis.com/Cluster") as $cluster | (if $cluster then $redisclusters[$key] else $valkey[$key] end) as $d | (($d.replicaCount? // 0) >= 1) as $replicas | $base + {category: "cache.redis", capabilities: [ "encryption-at-rest", cap("node-high-availability"; $replicas), cap("zone-high-availability"; $replicas and ($d.zoneDistributionConfig.mode? // "MULTI_ZONE") != "SINGLE_ZONE"), cap("sharding"; $cluster or ($d != null and ($d.mode? | IN("CLUSTER_DISABLED", "STANDALONE") | not))), cap("snapshots"; $d.persistenceConfig.mode? == "RDB") ], size: (if $d == null then null else size_of({ memoryGiB: (if $cluster then null else $d.nodeConfig.sizeGb? end), count: (if $d.shardCount == null then null else $d.shardCount * (($d.replicaCount // 0) + 1) end) }) end)} elif .assetType == "artifactregistry.googleapis.com/Repository" then # A Docker repository is a container registry. A remote repository only # pulls through from an upstream and a virtual one only aggregates # others: neither stores an image of its own, so both are left out. # Without the repositories list the format is unknown: unclassified. $repositories[$key] as $d | select($d.mode? | IN("REMOTE_REPOSITORY", "VIRTUAL_REPOSITORY") | not) | if $d.format? == "DOCKER" then $base + {category: "registry.container", capabilities: ["encryption-at-rest"]} else $base + {category: "unclassified"} end elif .assetType == "file.googleapis.com/Instance" then # Filestore is NFS. The REGIONAL and ENTERPRISE tiers keep serving # through the loss of a zone. $filestore[$key] as $d | $base + {category: "storage.file", capabilities: [ "encryption-at-rest", cap("zone-high-availability"; $d.tier? | IN("REGIONAL", "ENTERPRISE")), cap("snapshots"; $key | IN($filesnapshotted[])) ], size: (if $d == null then null else size_of({storageGiB: ([$d.fileShares[]?.capacityGb | number] | if . == [] then null else add end)}) end)} elif .assetType == "managedkafka.googleapis.com/Cluster" then # Managed Service for Apache Kafka: Google runs every cluster in three # zones, its replicas spread across them, and encrypts it at rest. Its # capacity is the cluster's total over its brokers, so each broker gets # an equal share of it. A cluster the list does not hold gets no size. # A Kafka Connect cluster (ConnectCluster) is an integration runtime, # not a cluster to move: it stays unclassified, below. $kafka[$key].capacityConfig as $c | $base + {category: "messaging.kafka", capabilities: [ "encryption-at-rest", "node-high-availability", "zone-high-availability" ], size: (if $c.vcpuCount? == null then null else ($c.vcpuCount | number) as $vcpus | ([3, ($vcpus / 15 | ceil)] | max) as $brokers | size_of({ vcpus: ($vcpus / $brokers), memoryGiB: ($c.memoryBytes | number | if . == null then null else . / 1073741824 / $brokers end), count: $brokers }) end)} elif .assetType == "dns.googleapis.com/ManagedZone" then # A public zone is network.dns, with no region; a private one, or one the # managed-zones list does not hold, stays unclassified. The capabilities # are read for a public zone only. A joined zone's ID is its managed # zone's name, an unjoined one keeps the asset row's number. $dns.zones[$key] as $d | ($base + (if ($d.name? | type) == "string" then {id: $d.name} else {} end)) as $zone | if $d.visibility? == "public" then ($dns.routed[$key].routedRecordSets? // 0) as $n # The type check guards a hand-edited file: a count that is no # number gives no dns-routing. | $zone + {category: "network.dns", region: null, capabilities: [ cap("dnssec"; $d.dnssecConfig.state? | IN("on", "transfer")), cap("dns-routing"; ($n | type) == "number" and $n > 0) ]} else $zone + {category: "unclassified"} end elif .assetType | test("^compute\\.googleapis\\.com/(Region)?(UrlMap|BackendService|TargetPool|TargetInstance|Target[A-Za-z]*Proxy|(Global)?ForwardingRule)$") then # A load balancer comes from the compute lists, below; its frontends are # left out. empty elif .assetType == "compute.googleapis.com/Snapshot" or .assetType == "compute.googleapis.com/Autoscaler" or .assetType == "file.googleapis.com/Snapshot" or .assetType == "file.googleapis.com/Backup" then # Part of a disk's, a group's or a file share's capabilities, not a # resource to move. A Filestore backup adds no capability. empty else $base + {category: "unclassified"} end ] + [ # One network.loadbalancer per URL map, backend service no URL map names # and target pool. A regional or global load balancer is zone redundant # within a region. It forwards UDP when one of its backend services or a # forwarding rule that reaches it is UDP. It is ipv6 when an IPv6 forwarding # rule names a passthrough backend service (scheme EXTERNAL or INTERNAL) # directly in backendService: a passthrough load balancer delivers IPv6 to # dual-stack or IPv6-only backends and has no IP selection policy. A proxy # (an IPv6 rule through a target proxy, or scheme EXTERNAL_MANAGED or # INTERNAL_MANAGED) is ipv6 only when one of its backend services also # sends to IPv6 backends (IPV6_ONLY or PREFER_IPV6; absent is IPV4_ONLY). # A target pool has no protocol and takes IPv4 only. Every one is node # highly available: Cloud Load Balancing is a distributed, managed service, # not an instance (issue #707; the guide cites the page and says when to # remove it by hand). $loadbalancers[] as $lb | [$frontends[] | select(any(reaches($proxies); . == $lb.key))] as $fronts | { id: ($lb.link | split("/") | last), rawType: $lb.rawType, category: "network.loadbalancer", region: ($lb.link | link_region), capabilities: [ "zone-high-availability", "node-high-availability", cap("udp"; any($lb.services[]; $backends[.].protocol? == "UDP") or any($fronts[]; .IPProtocol? == "UDP")), cap("ipv6"; any($fronts[]; .ipVersion? == "IPV6" and .backendService != null and ($backends[.backendService | key].loadBalancingScheme? | IN("EXTERNAL", "INTERNAL"))) or (any($fronts[]; .ipVersion? == "IPV6") and any($lb.services[]; $backends[.].ipAddressSelectionPolicy? | IN("IPV6_ONLY", "PREFER_IPV6")))) ] } ] | inventory("gcp") SHIFT2EU_JQ_PROGRAM then build_failed "cannot write the embedded gcp.jq to $program" fi # Build into the temporary directory, then write the inventory from there # through a staged file beside it in --out (0600 under umask 077), renamed into # place: a failed build or write leaves an earlier inventory as it was, a # rename replaces the inventory's path instead of following it, and the path is # checked again just before the rename, since mv would move the staged file # into a directory, and once more after it, for a directory or a link to one # planted in between: the staged file the rename moved into it is removed. The # EXIT trap removes a staged file left behind. say "building $inventory with the embedded gcp.jq" if ! jq -n -f "$program" "$raw"/*.json > "$built"; then build_failed "the build failed" fi if [ -L "$inventory" ] || { [ -e "$inventory" ] && [ ! -f "$inventory" ]; }; then build_failed "$inventory exists and is no regular file: move it away" fi if ! staged=$(mktemp "$out_dir/.gcp.inventory.json.XXXXXX"); then staged= build_failed "cannot create a staged file for the inventory in $out_dir" fi if ! cat -- "$built" > "$staged"; then build_failed "cannot write the staged inventory $staged" fi if [ -L "$inventory" ] || { [ -e "$inventory" ] && [ ! -f "$inventory" ]; }; then build_failed "$inventory exists and is no regular file: move it away" fi if ! mv -f -- "$staged" "$inventory"; then build_failed "cannot rename $staged to $inventory" fi if [ -L "$inventory" ] || [ ! -f "$inventory" ]; then moved="$inventory/${staged##*/}" if [ -f "$moved" ] && [ ! -L "$moved" ]; then rm -f -- "$moved" fi build_failed "$inventory is no regular file after the rename (a directory or a link was put there meanwhile): move it away" fi staged= # Clean up. if [ "$keep_raw" = 1 ]; then say "kept the raw output in $raw (--keep-raw): it holds your provider's own answers, so delete it once you are done" else remove_raw say "deleted $removed" fi # Summary. report_steps resources=$(jq '.resources | length' "$inventory") unclassified=$(jq '[.resources[] | select(.category == "unclassified")] | length' "$inventory") printf 'Inventory: %s\n' "$inventory" printf 'Resources: %s, of which %s unclassified.\n' "$resources" "$unclassified" printf 'Review %s before you share it: it names your resources and how they are set up.\n' "$inventory" printf 'Add workload and monthlyCost by hand if you want them (the guide'\''s "What you add by hand").\n' if [ -n "$failed" ]; then exit 1 fi