#!/usr/bin/env bash # shift2eu-inventory-azure.sh builds a shift2eu inventory of an Azure # subscription. # # Generated by ci/inventoryscripts (make inventory-scripts) from the inventory # guide, docs/guide/inventory.md (its sections "Collect from Azure" and "Build # the Azure inventory"), with the program docs/guide/inventory/azure.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 az CLI only lists, shows, gets or queries. It # reads no credential: the az CLI signs in through its own credentials. It # never changes the subscription the CLI is set to: it passes the one it # collects to every call that takes one. 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-azure.sh guide=https://github.com/timothymamo/shift2eu/blob/main/docs/guide/inventory.md usage() { cat <<'USAGE' Usage: shift2eu-inventory-azure.sh [--subscription ] [--out ] [--keep-raw] [--with-optional] Builds a shift2eu inventory of an Azure subscription. It runs the read-only commands of the inventory guide's "Collect from Azure" section, builds /azure.inventory.json with the guide's program azure.jq, embedded in this script, and deletes the raw output unless --keep-raw is given. Every command it runs with the az CLI only lists, shows, gets or queries: it creates, changes, deletes or tags nothing in your subscription, and it never changes the subscription your CLI is set to. Options: --subscription The subscription to collect, passed to every call that takes one. Default: the subscription your CLI is set to, which it prints. --out Where the raw output and the inventory go; default inventories. The raw output goes to /azure/. --keep-raw Keep the raw output, /azure/, after the build. --with-optional Accepted, and changes nothing: the guide marks no Azure command optional. --help Print this help. It needs the az CLI with its resource-graph extension, signed in as you normally sign in, and jq. Azure Cloud Shell (Bash) has them, 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#azure-permissions Exit status: 0 built; 1 built, but a step failed (stderr names it); 2 usage; 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 } # subscription_name reports whether its argument can name a subscription: # never empty, never an option. subscription_name() { case $1 in '' | -*) 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 Azure" section, # in its order, one function each, run with subscription 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. # Keep only the properties azure.jq reads, and only for the types it reads them from. # An HDInsight cluster has a branch of its own: its roles array is expanded and # only its kind, its state and the worker role's count, VM size and disks are # packed back, as each role # also carries its admin user, SSH key, script actions and network. step_1() { query="Resources | where type =~ 'microsoft.hdinsight/clusters' | mv-expand role = properties.computeProfile.roles | where role.name =~ 'workernode' | extend properties = bag_pack( 'clusterDefinition', bag_pack('kind', properties.clusterDefinition.kind), 'clusterState', properties.clusterState, 'computeProfile', bag_pack('roles', pack_array(bag_pack( 'name', role.name, 'targetInstanceCount', role.targetInstanceCount, 'hardwareProfile', bag_pack('vmSize', role.hardwareProfile.vmSize), 'dataDisksGroups', pack_array(bag_pack( 'disksPerNode', role.dataDisksGroups[0].disksPerNode, 'diskSizeGB', role.dataDisksGroups[0].diskSizeGB)))))) | union (Resources | where type !~ 'microsoft.hdinsight/clusters' | extend properties = case( type =~ 'microsoft.compute/virtualmachines', bag_pack( 'virtualMachineScaleSet', bag_pack('id', properties.virtualMachineScaleSet.id), 'storageProfile', bag_pack( 'osDisk', bag_pack('managedDisk', bag_pack('id', properties.storageProfile.osDisk.managedDisk.id)), 'dataDisks', properties.storageProfile.dataDisks), 'networkProfile', bag_pack('networkInterfaces', properties.networkProfile.networkInterfaces), 'hardwareProfile', bag_pack('vmSize', properties.hardwareProfile.vmSize)), type =~ 'microsoft.compute/disks', bag_pack('diskSizeGB', properties.diskSizeGB), type =~ 'microsoft.network/networkinterfaces', bag_pack('ipConfigurations', properties.ipConfigurations), type =~ 'microsoft.compute/snapshots', bag_pack('creationData', bag_pack('sourceResourceId', properties.creationData.sourceResourceId)), type =~ 'microsoft.insights/autoscalesettings', bag_pack('enabled', properties.enabled, 'targetResourceUri', properties.targetResourceUri), type in~ ('microsoft.dbforpostgresql/flexibleservers', 'microsoft.dbformysql/flexibleservers'), bag_pack('backup', bag_pack('backupRetentionDays', properties.backup.backupRetentionDays), 'highAvailability', bag_pack('mode', properties.highAvailability.mode), 'sourceServerResourceId', properties.sourceServerResourceId, 'storage', bag_pack('storageSizeGB', properties.storage.storageSizeGB)), type =~ 'microsoft.containerservice/managedclusters', bag_pack('nodeResourceGroup', properties.nodeResourceGroup, 'agentPoolProfiles', properties.agentPoolProfiles), type =~ 'microsoft.compute/virtualmachinescalesets', bag_pack('virtualMachineProfile', bag_pack('networkProfile', bag_pack('networkInterfaceConfigurations', properties.virtualMachineProfile.networkProfile.networkInterfaceConfigurations))), type =~ 'microsoft.cache/redis', bag_pack('sku', properties.sku, 'shardCount', properties.shardCount, 'replicasPerMaster', properties.replicasPerMaster, 'replicasPerPrimary', properties.replicasPerPrimary, 'zonalAllocationPolicy', properties.zonalAllocationPolicy, 'redisConfiguration', bag_pack('rdb-backup-enabled', properties.redisConfiguration['rdb-backup-enabled'])), type =~ 'microsoft.cache/redisenterprise', bag_pack('highAvailability', properties.highAvailability, 'redundancyMode', properties.redundancyMode), type =~ 'microsoft.documentdb/databaseaccounts', bag_pack('backupPolicy', bag_pack('type', properties.backupPolicy.type), 'locations', properties.locations), type =~ 'microsoft.documentdb/mongoclusters', bag_pack('highAvailability', bag_pack('targetMode', properties.highAvailability.targetMode), 'sharding', bag_pack('shardCount', properties.sharding.shardCount), 'storage', bag_pack('sizeGb', properties.storage.sizeGb), 'compute', bag_pack('tier', properties.compute.tier), 'replicaParameters', bag_pack('sourceResourceId', properties.replicaParameters.sourceResourceId)), type =~ 'microsoft.network/loadbalancers', bag_pack('frontendIPConfigurations', properties.frontendIPConfigurations, 'backendAddressPools', properties.backendAddressPools, 'loadBalancingRules', properties.loadBalancingRules), type =~ 'microsoft.network/publicipaddresses', bag_pack('publicIPAddressVersion', properties.publicIPAddressVersion), type =~ 'microsoft.fileshares/fileshares', bag_pack('protocol', properties.protocol, 'provisionedStorageGiB', properties.provisionedStorageGiB, 'redundancy', properties.redundancy), type =~ 'microsoft.network/dnszones', bag_pack('zoneType', properties.zoneType), dynamic(null))) | project id, name, type, kind, location, zones, sku, properties" page=1 token="" # 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. ( while :; do if [ -z "$token" ]; then az graph query --graph-query "$query" --subscriptions "$subscription" --first 1000 \ --output json > "$out/graph-$page.json" else az graph query --graph-query "$query" --subscriptions "$subscription" --first 1000 \ --skip-token "$token" --output json > "$out/graph-$page.json" fi token="$(in_assignment; jq -r '.skip_token // empty' "$out/graph-$page.json")" [ -n "$token" ] || break page=$((page + 1)) done : ) } # Writes servicebus.json. step_2() { az servicebus namespace list --subscription "$subscription" \ --query "[].[name, resourceGroup]" --output tsv | while read -r name group; do az servicebus queue list --subscription "$subscription" --namespace-name "$name" \ --resource-group "$group" --query "[].{id: id, name: name, type: type}" --output json az servicebus topic list --subscription "$subscription" --namespace-name "$name" \ --resource-group "$group" --query "[].{id: id, name: name, type: type}" --output json az servicebus topic list --subscription "$subscription" --namespace-name "$name" \ --resource-group "$group" --query "[].name" --output tsv | while read -r topic; do az servicebus topic subscription list --subscription "$subscription" \ --namespace-name "$name" --resource-group "$group" --topic-name "$topic" \ --query "[].{id: id, name: name, type: type}" --output json done done > "$out/servicebus.json" } # Writes storage-queues.json. step_3() { az storage account list --subscription "$subscription" \ --query "[?kind=='StorageV2' || kind=='Storage'].id" --output tsv | while read -r id; do case "$id" in *[?#@%\\[:space:][:cntrl:]]*) echo "skipped an id that is no resource ID" >&2; continue ;; /subscriptions/*) ;; *) echo "skipped an id that is no resource ID" >&2; continue ;; esac az rest --method get \ --url "https://management.azure.com${id}/queueServices/default/queues?api-version=2023-05-01" \ --query "value[].{id: id, name: name, type: type}" --output json done > "$out/storage-queues.json" } # Writes blob-services.json. step_4() { az storage account list --subscription "$subscription" \ --query "[].[name, resourceGroup]" --output tsv | while read -r name group; do az storage account blob-service-properties show --subscription "$subscription" \ --account-name "$name" --resource-group "$group" \ --query "{id: id, type: type, isVersioningEnabled: isVersioningEnabled}" --output json done > "$out/blob-services.json" } # The file shares of FileStorage accounts, the only ones with NFS shares, and their snapshots. step_5() { az storage account list --subscription "$subscription" \ --query "[?kind=='FileStorage'].id" --output tsv | while read -r id; do case "$id" in *[?#@%\\[:space:][:cntrl:]]*) echo "skipped an id that is no resource ID" >&2; continue ;; /subscriptions/*) ;; *) echo "skipped an id that is no resource ID" >&2; continue ;; esac az rest --method get \ --url "https://management.azure.com${id}/fileServices/default/shares?api-version=2023-05-01&\$expand=snapshots" \ --query "value[].{id: id, name: name, type: type, properties: {enabledProtocols: properties.enabledProtocols, shareQuota: properties.shareQuota, snapshotTime: properties.snapshotTime}}" \ --output json done > "$out/file-shares.json" } # The databases of every Azure Managed Redis (Redis Enterprise) cluster: clustering and persistence. step_6() { jq -r '.data[] | select(.type == "microsoft.cache/redisenterprise") | .id' "$out"/graph-*.json | while read -r id; do case "$id" in *[?#@%\\[:space:][:cntrl:]]*) echo "skipped an id that is no resource ID" >&2; continue ;; /subscriptions/*) ;; *) echo "skipped an id that is no resource ID" >&2; continue ;; esac az rest --method get --url "https://management.azure.com${id}/databases?api-version=2026-09-01" \ --query "value[].{id: id, name: name, type: type, properties: {clusteringPolicy: properties.clusteringPolicy, persistence: properties.persistence}}" \ --output json done > "$out/redis-databases.json" } # The vCPU and memory of every VM size, in each region with virtual machines, scale sets # or HDInsight clusters. step_7() { jq -r '[.data[] | select(.type == "microsoft.compute/virtualmachines" or .type == "microsoft.compute/virtualmachinescalesets" or .type == "microsoft.hdinsight/clusters") | .location] | unique[]' "$out"/graph-*.json | while read -r location; do az vm list-sizes --subscription "$subscription" --location "$location" --output json done > "$out/vm-sizes.json" } # Whether each public DNS zone is signed with DNSSEC: its provisioning state alone, never its keys. # An unsigned zone answers "(NotFound) DNSSEC is not enabled for DNS zone ...": that error is expected, # as is the warning that the dnssec-config command group is experimental. step_8() { jq -r '.data[] | select(.type == "microsoft.network/dnszones" and ((.properties.zoneType // "Public") | ascii_downcase) != "private") | [(.id | split("/")[4]), .name] | @tsv' "$out"/graph-*.json | while read -r rg zone; do az network dns dnssec-config show --subscription "$subscription" \ --resource-group="$rg" --zone-name="$zone" \ --query "{id: id, type: type, provisioningState: provisioningState || properties.provisioningState}" \ --output json || : done > "$out/dns-dnssec.json" } # The options. out_dir=inventories keep_raw=0 with_optional=0 subscription= while [ "$#" -gt 0 ]; do case $1 in --subscription) if [ "$#" -lt 2 ]; then usage_error "--subscription needs a value" fi if has_control "$2"; then usage_error "--subscription holds a control character: pass the subscription ID alone" fi if ! subscription_name "$2"; then usage_error "--subscription $2 is no subscription" fi subscription=$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/azure" inventory="$out_dir/azure.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 az 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="az" if ! command -v "$cli" > /dev/null 2>&1; then say "the az CLI is not on PATH: install the Azure CLI, as the guide's Before you start asks ($guide#before-you-start)" exit 3 fi # The output directories: /azure/ 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: /azure/ when the run # created it. A /azure/ 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 resource-graph extension, a local read and the first az call, made once # --out is in place, as every CLI call is. say "checking the resource-graph extension of the az CLI with az extension show" if ! az extension show --name resource-graph > /dev/null 2>&1; then say "the az CLI has no resource-graph extension: add it, as the guide's Before you start asks ($guide#before-you-start)" exit 3 fi # The subscription and the sign-in: --subscription, checked with # az account show, its answer discarded, or else the subscription the CLI is # set to, read as the guide reads it. Either way the CLI's own setting is left # as it is. if [ -z "$subscription" ]; then say "checking the sign-in and reading the subscription your CLI is set to with az account show" if ! subscription=$(az account show --query id --output tsv); then say "az account show failed: the CLI is not signed in; sign in as you normally do; the permissions are at $guide#azure-permissions" exit 4 fi if has_control "$subscription"; then say "az account show named a subscription holding a control character: pass --subscription " exit 4 fi if ! subscription_name "$subscription"; then say "az account show named no subscription: pass --subscription " exit 4 fi else say "checking the sign-in with az account show, its answer discarded" if ! az account show > /dev/null; then say "az account show failed: the CLI is not signed in; sign in as you normally do; the permissions are at $guide#azure-permissions" exit 4 fi fi say "the subscription: $subscription" # Collect. if [ "$with_optional" = 1 ]; then say "--with-optional changes nothing: the guide marks no Azure command optional" fi collect_steps() { run_step step_1 'Keep only the properties azure.jq reads, and only for the types it reads them from.' run_step step_2 'servicebus.json' run_step step_3 'storage-queues.json' run_step step_4 'blob-services.json' run_step step_5 'The file shares of FileStorage accounts, the only ones with NFS shares, and their snapshots.' run_step step_6 'The databases of every Azure Managed Redis (Redis Enterprise) cluster: clustering and persistence.' run_step step_7 'The vCPU and memory of every VM size, in each region with virtual machines, scale sets' run_step step_8 'Whether each public DNS zone is signed with DNSSEC: its provisioning state alone, never its keys.' } out="$raw" say "collecting the subscription $subscription 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, azure.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 azure.jq (TMPDIR=${TMPDIR:-/tmp})" fi program="$tmp_dir/azure.jq" built="$tmp_dir/inventory.json" if ! cat > "$program" <<'SHIFT2EU_JQ_PROGRAM' # azure.jq turns the output of the read-only az 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/azure.jq inventories/azure/*.json > inventories/azure.inventory.json # # The Resource Graph listing (az graph query, one file per page) is the list of # resources and holds most details; nine calls add what it lacks. Each element of # each input is recognised by its shape, not by its file name. The guide's queries # keep only the fields read here; the full output is read the same way: # # {"data": [...]} az graph query, one page # {"type": "Microsoft.ServiceBus/Namespaces/Queues"} az servicebus queue list # {"type": "Microsoft.ServiceBus/Namespaces/Topics"} az servicebus topic list # {"type": "Microsoft.ServiceBus/Namespaces/Topics/Subscriptions"} # az servicebus topic # subscription list # {"type": "Microsoft.Storage/storageAccounts/queueServices/queues"} # az rest --method get .../queues # {"type": "Microsoft.Storage/storageAccounts/blobServices"} # az storage account # blob-service-properties show # {"type": "Microsoft.Storage/storageAccounts/fileServices/shares"} # az rest --method get .../shares # (with their snapshots) # {"type": "Microsoft.Cache/redisEnterprise/databases"} # az rest --method get .../databases # {"type": "Microsoft.Network/dnszones/dnssecConfigs"} # az network dns dnssec-config show # (one per signed public zone) # [{"name": ..., "numberOfCores": ...}] az vm list-sizes # # Resource IDs are short (the resource's name, a topic subscription's # "/"), never the full Azure resource ID, which carries the # subscription. Anything it cannot classify is "unclassified" with its rawType # (an Azure Resource Manager type), so it shows up as a blocker. # # Everything in an AKS cluster's node resource group (its scale sets, load # balancers, public IP addresses, network interfaces, the Azure Files CSI # driver's FileStorage accounts) is left out, the cluster stands for it; its # managed disks and those accounts' shares, persistent volumes that hold data, # stay. So # are a FileStorage account whose shares are listed (they stand for it), share # snapshots (a capability of their share) and Redis Enterprise databases (their # cluster stands for them). # # The size comes from the calls too: a virtual machine's or a scale set's vCPU # and memory from its VM size (properties.hardwareProfile.vmSize or sku.name, # looked up in az vm list-sizes), a scale set's instance count (sku.capacity), a # managed disk's GiB (properties.diskSizeGB), a flexible server's storage # (properties.storage.storageSizeGB), a single-node flexible server's count of 1 # (properties.highAvailability.mode Disabled or unset; a server with a standby # gets no count, how many nodes a target bills for a standby is the target's to # say), an AKS cluster's node count (the counts of its agent pools), a cache's # node count (from its tier, replicas and shards, or an Azure Managed Redis # cluster's high availability or zones), an Azure DocumentDB cluster's node count and # storage (its shards, a standby each with high availability, and sizeGb per # shard), an NFS share's GiB (shareQuota, or provisionedStorageGiB) and an # HDInsight Kafka cluster's worker count, VM size and GiB per worker (its worker # role's targetInstanceCount, hardwareProfile.vmSize, and disksPerNode times # diskSizeGB). 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. # The Resource Manager type of a resource ID, in the casing of the ID (Resource # Graph writes types in lower case): # /subscriptions/s/resourceGroups/g/providers/Microsoft.ServiceBus/namespaces/n/queues/q # -> Microsoft.ServiceBus/namespaces/queues. def id_type: split("/providers/") | last | split("/") as $p | [$p[0]] + [range(1; $p | length; 2) as $i | $p[$i]] | join("/"); # 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; # The vCPU and memory of a VM size name, from az vm list-sizes ($vmsizes), or # null when the call did not list it. def vm_size($vmsizes): if . == null then null else $vmsizes[ascii_downcase] as $s | if $s == null then null else {vcpus: $s.numberOfCores, memoryGiB: (if $s.memoryInMb == null then null else $s.memoryInMb / 1024 end)} end 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: .}; def lower_type: (.type // "") | ascii_downcase; def lid: ascii_downcase; # The resource group of a resource ID, in lower case. def id_group: lid | split("/")[4] // ""; # The types the calls next to Resource Graph return. def child_types: "microsoft.servicebus/namespaces/queues", "microsoft.servicebus/namespaces/topics", "microsoft.servicebus/namespaces/topics/subscriptions", "microsoft.storage/storageaccounts/queueservices/queues", "microsoft.storage/storageaccounts/blobservices", "microsoft.storage/storageaccounts/fileservices/shares", "microsoft.cache/redisenterprise/databases", "microsoft.network/dnszones/dnssecconfigs"; # Whether the IP configuration ID names an IPv6 one, looked up in Resource Graph # ($byid): a network interface's (.../networkInterfaces//ipConfigurations/) # in its ipConfigurations, a scale set member's # (.../virtualMachineScaleSets//virtualMachines//networkInterfaces//ipConfigurations/) # in its scale set's network profile. def ipconfig_v6($byid): lid as $c | ([$c | capture("^(?.*/virtualmachinescalesets/[^/]+)/virtualmachines/[^/]+/networkinterfaces/(?[^/]+)/ipconfigurations/(?[^/]+)$")] | first) as $member | ([$c | capture("^(?.*/networkinterfaces/[^/]+)/ipconfigurations/(?[^/]+)$")] | first) as $nic | if $member != null then any($byid[$member.set].properties.virtualMachineProfile.networkProfile.networkInterfaceConfigurations[]? | select((.name // "" | ascii_downcase) == $member.nic) | .properties.ipConfigurations[]?; (.name // "" | ascii_downcase) == $member.ip and .properties.privateIPAddressVersion == "IPv6") elif $nic != null then any($byid[$nic.nic].properties.ipConfigurations[]?; (.name // "" | ascii_downcase) == $nic.ip and .properties.privateIPAddressVersion == "IPv6") else false end; # The number of zones a resource (or a frontend IP configuration) names. def zone_count: (.zones // []) | length; [inputs] as $inputs # The VM sizes az vm list-sizes lists: an array of sizes, no id or type. | ([$inputs[] | arrays | .[] | objects | select(has("numberOfCores") and (.name | type) == "string")] | INDEX(.name | ascii_downcase)) as $vmsizes | [$inputs[] | if type == "object" and (.data | type) == "array" then .data[] elif type == "object" and (.value | type) == "array" then .value[] elif type == "array" then .[] else . end | objects | select((.id? | type) == "string" and (.type? | type) == "string")] as $all | [$all[] | select(lower_type == "microsoft.servicebus/namespaces/queues")] as $queues | [$all[] | select(lower_type == "microsoft.servicebus/namespaces/topics")] as $topics | [$all[] | select(lower_type == "microsoft.servicebus/namespaces/topics/subscriptions")] as $subscriptions | [$all[] | select(lower_type == "microsoft.storage/storageaccounts/queueservices/queues")] as $storagequeues | [$all[] | select(lower_type == "microsoft.storage/storageaccounts/blobservices")] as $blobs # A share snapshot is listed with its share's ID and a snapshotTime. | [$all[] | select(lower_type == "microsoft.storage/storageaccounts/fileservices/shares")] as $shareelements | [$shareelements[] | select(.properties.snapshotTime? == null)] as $shares | ([$shareelements[] | select(.properties.snapshotTime? != null) | .id | lid] | unique) as $snapshottedshares | ([$shares[] | .id | lid | sub("/fileservices/.*$"; "")] | unique) as $shareaccounts | [$all[] | select(lower_type == "microsoft.cache/redisenterprise/databases")] as $redisdatabases # The public DNS zones signed with DNSSEC: their configuration's provisioning # state is Succeeded (any casing). Its ID is the zone's with /dnssecConfigs/default # appended, in its own casing (dnszones, where Resource Graph writes dnsZones). | ([$all[] | select(lower_type == "microsoft.network/dnszones/dnssecconfigs") | select((.provisioningState? // "" | ascii_downcase) == "succeeded") | .id | lid | sub("/dnssecconfigs/default$"; "")] | unique) as $signedzones | [$all[] | select(lower_type | IN(child_types) | not)] as $rows | ($rows | INDEX(.id | lid)) as $byid | ([$rows[] | select(lower_type == "microsoft.compute/snapshots") | .properties.creationData.sourceResourceId // empty | lid] | unique) as $snapshotted | ([$rows[] | select(lower_type == "microsoft.insights/autoscalesettings") | select(.properties.enabled != false) | .properties.targetResourceUri // empty | lid] | unique) as $autoscaled | ([$rows[] | .properties.sourceServerResourceId? // empty | lid] | unique) as $replicated | ([$rows[] | select(lower_type == "microsoft.documentdb/mongoclusters") | .properties.replicaParameters.sourceResourceId? // empty | lid] | unique) as $mongoreplicated | ([$blobs[] | select(.isVersioningEnabled == true) | .id | lid | sub("/blobservices/.*$"; "")]) as $versioned | ([$queues[], $topics[], $subscriptions[] | .id | lid | sub("/(queues|topics)/.*$"; "")] | unique) as $queuenamespaces | ([$rows[] | select(lower_type == "microsoft.containerservice/managedclusters") | .properties.nodeResourceGroup // empty | ascii_downcase] | unique) as $nodegroups # The OS disks of a scale set's virtual machines, and their data disks deleted with them: the # scale set stands for them. | ([$rows[] | select(lower_type == "microsoft.compute/virtualmachines") | select(.properties.virtualMachineScaleSet.id? != null) | .properties.storageProfile | (.osDisk.managedDisk.id?, (.dataDisks[]? | select((.deleteOption // "" | ascii_downcase) == "delete") | .managedDisk.id?)) | values | lid] | unique) as $scalesetdisks | [ # Service Bus queues. Every queue has a dead-letter subqueue. ($queues[] | (.id | lid | sub("/queues/.*$"; "")) as $ns | { id: .name, rawType: (.id | id_type), category: "messaging.queue", region: $byid[$ns].location, capabilities: ["dead-letter-queue"] }), # Service Bus topics: publish and subscribe. Topics exist only in the # Standard and Premium tiers, which encrypt all data at rest. ($topics[] | (.id | lid | sub("/topics/.*$"; "")) as $ns | { id: .name, rawType: (.id | id_type), category: "messaging.topic", region: $byid[$ns].location, capabilities: ["encryption-at-rest"] }), # Service Bus topic subscriptions: each is a queue of its topic's messages # with a dead-letter subqueue of its own. Named "/", as # the same subscription name recurs across topics. ($subscriptions[] | (.id | lid | sub("/topics/.*$"; "")) as $ns | { id: ((.id | capture("/topics/(?[^/]+)/subscriptions/"; "i").t) + "/" + .name), rawType: (.id | id_type), category: "messaging.queue", region: $byid[$ns].location, capabilities: ["dead-letter-queue"] }), # File shares of a FileStorage account (snapshots are left out above). An # NFS share is a file share a target can serve; an SMB share stays # unclassified. Azure Files encrypts every share at rest. ($shares[] | (.id | lid) as $id | ($id | sub("/fileservices/.*$"; "")) as $account | { id: .name, rawType: (.id | id_type), region: $byid[$account].location } as $base | if (.properties.enabledProtocols // "" | ascii_downcase) == "nfs" then $base + {category: "storage.file", capabilities: [ "encryption-at-rest", cap("snapshots"; $id | IN($snapshottedshares[])), cap("zone-high-availability"; $byid[$account].sku.name? // "" | ascii_downcase | endswith("_zrs")) ], size: size_of({storageGiB: .properties.shareQuota?})} else $base + {category: "unclassified"} end), # Storage queues. Azure encrypts every storage account at rest. ($storagequeues[] | (.id | lid | sub("/queueservices/.*$"; "")) as $account | { id: .name, rawType: (.id | id_type), category: "messaging.queue", region: $byid[$account].location, capabilities: ["encryption-at-rest"] }), ($rows[] | (.id | lid) as $id | lower_type as $t # Managed by AKS in a cluster's node resource group: the cluster stands # for it. A managed disk there is a persistent volume and stays. | select(($id | id_group | IN($nodegroups[])) and $t != "microsoft.compute/disks" | not) | { id: .name, rawType: (.id | id_type | if ascii_downcase == $t then . else $t end), region: (if .location == "global" then null else .location end) } as $base | if $t == "microsoft.compute/virtualmachines" then # A virtual machine of a scale set is left out: the scale set stands # for it. select(.properties.virtualMachineScaleSet.id? == null) | ([.properties.storageProfile.osDisk.managedDisk.id?, .properties.storageProfile.dataDisks[]?.managedDisk.id?] | map(select(.) | lid)) as $disks | $base + {category: "compute.vm", capabilities: [ cap("ipv6"; any(.properties.networkProfile.networkInterfaces[]?.id | lid; any($byid[.].properties.ipConfigurations[]?; .properties.privateIPAddressVersion == "IPv6"))), cap("snapshots"; any($disks[]; IN($snapshotted[]))) ], size: size_of(.properties.hardwareProfile.vmSize? | vm_size($vmsizes) // {})} elif $t == "microsoft.compute/virtualmachinescalesets" then $base + {category: "compute.vm", capabilities: [ cap("autoscaling"; $id | IN($autoscaled[])), cap("zone-high-availability"; (.zones // []) | length >= 2) ], size: size_of((.sku.name? | vm_size($vmsizes) // {}) + {count: (.sku.capacity? | if type == "number" and . >= 1 then . else null end)})} elif $t == "microsoft.baremetalinfrastructure/baremetalinstances" or $t == "microsoft.azurelargeinstance/azurelargeinstances" then # A BareMetal Infrastructure instance or a SAP HANA Large Instance: a # dedicated physical server (ADR 0023). $base + {category: "compute.baremetal"} elif $t == "microsoft.compute/disks" then # The OS disk of a scale set's virtual machine, and a data disk it # deletes with it, go with it. Azure encrypts every managed disk at # rest. select($id | IN($scalesetdisks[]) | not) | $base + {category: "storage.block", capabilities: [ "encryption-at-rest", cap("snapshots"; $id | IN($snapshotted[])) ], size: size_of({storageGiB: .properties.diskSizeGB?})} elif $t == "microsoft.storage/storageaccounts" then # A FileStorage account holds file shares only: its listed shares # stand for it, and one with none listed is unclassified. Azure # encrypts every storage account at rest. if .kind == "FileStorage" then if $id | IN($shareaccounts[]) then empty else $base + {category: "unclassified"} end else $base + {category: "storage.object", capabilities: [ "encryption-at-rest", cap("object-versioning"; $id | IN($versioned[])) ]} end elif $t == "microsoft.dbforpostgresql/flexibleservers" or $t == "microsoft.dbformysql/flexibleservers" then $base + { category: (if $t == "microsoft.dbforpostgresql/flexibleservers" then "database.postgresql" else "database.mysql" end), capabilities: [ "encryption-at-rest", cap("point-in-time-restore"; (.properties.backup.backupRetentionDays // 0) > 0), cap("zone-high-availability"; .properties.highAvailability.mode? == "ZoneRedundant"), cap("node-high-availability"; .properties.highAvailability.mode? == "SameZone"), cap("read-replicas"; $id | IN($replicated[])) ], # A single-node server is one instance; one with a standby gets no # count, how many nodes a standby is depends on how a target prices it. size: size_of({storageGiB: .properties.storage.storageSizeGB?, count: ((.properties.highAvailability.mode? // "Disabled") as $ha | if $ha == "Disabled" then 1 else null end)})} elif $t == "microsoft.containerservice/managedclusters" then [.properties.agentPoolProfiles[]?] as $pools | $base + {category: "kubernetes.managed", capabilities: [ cap("autoscaling"; any($pools[]; .enableAutoScaling == true)), cap("zone-high-availability"; any($pools[]; (.availabilityZones // []) | length >= 2)), cap("node-high-availability"; ([$pools[].count // 0] | add // 0) >= 2) ], size: size_of({count: ([$pools[].count // 0] | add // 0 | if . >= 1 then . else null end)})} elif $t == "microsoft.web/sites" then # A function app; a web app or a Logic App is unclassified. (.kind // "" | ascii_downcase | split(",")) as $kind | $base + {category: (if ($kind | index("functionapp")) and ($kind | index("workflowapp") | not) then "serverless.function" else "unclassified" end)} elif $t == "microsoft.app/containerapps" then # A container app of kind functionapp runs Azure Functions, one of # kind workflowapp a Logic App, which is unclassified. (.kind // "" | ascii_downcase | split(",")) as $kind | $base + {category: (if $kind | index("workflowapp") then "unclassified" elif $kind | index("functionapp") then "serverless.function" else "serverless.container" end)} elif $t == "microsoft.containerregistry/registries" then # Every registry encrypts its images at rest. $base + {category: "registry.container", capabilities: ["encryption-at-rest"]} elif $t == "microsoft.cache/redis" then # Azure Cache for Redis. Basic is one node; Standard a primary and a # replica; Premium adds shards (OSS clustering), more replicas and RDB # persistence. The C0 and C1 SKUs have no disk encryption. .properties as $p | ($p.sku.name? // "") as $tier | ([$p.shardCount? // 1, 1] | max) as $shards | $base + {category: "cache.redis", capabilities: [ cap("node-high-availability"; $tier | IN("Standard", "Premium")), cap("zone-high-availability"; ($tier | IN("Standard", "Premium")) and (zone_count >= 2 or $p.zonalAllocationPolicy? == "Automatic")), cap("sharding"; $tier == "Premium" and ($p.shardCount? // 0) >= 1), cap("snapshots"; $tier == "Premium" and ($p.redisConfiguration["rdb-backup-enabled"]? // "" | tostring | ascii_downcase) == "true"), cap("encryption-at-rest"; ($p.sku.family? == "C" and ($p.sku.capacity? | IN(0, 1))) | not) ], size: size_of({count: (if $tier == "Basic" then 1 elif $tier == "Standard" then 2 elif $tier == "Premium" then (1 + ($p.replicasPerPrimary? // $p.replicasPerMaster? // 1)) * $shards else null end)})} elif $t == "microsoft.cache/redisenterprise" then # Azure Managed Redis: a primary and a replica with high availability; # its zones never override highAvailability and redundancyMode. # Only a legacy Enterprise or Enterprise Flash cluster (an Enterprise* # SKU) names its zones in zones instead. Such a cluster always runs # a primary and a replica of every partition on different nodes, so # it is always highly available; its zones (two or more) decide only # zone high availability. Clustering and persistence are its # databases' settings, from the databases call; without it neither # is claimed. Disks are always encrypted. [$redisdatabases[] | select(.id | lid | startswith($id + "/databases/"))] as $dbs | ((.sku.name? // "") | ascii_downcase | startswith("enterprise")) as $legacy | ($legacy and zone_count >= 2) as $zonal | (.properties.highAvailability? == "Enabled" or (.properties.redundancyMode? | IN("LR", "ZR")) or $legacy) as $ha | $base + {category: "cache.redis", capabilities: [ "encryption-at-rest", cap("node-high-availability"; $ha), cap("zone-high-availability"; .properties.redundancyMode? == "ZR" or $zonal), cap("sharding"; any($dbs[]; .properties.clusteringPolicy? == "OSSCluster")), cap("snapshots"; any($dbs[]; .properties.persistence.rdbEnabled? == true)) ], size: size_of({count: (if $ha then 2 else 1 end)})} elif $t == "microsoft.documentdb/databaseaccounts" and .kind == "MongoDB" then # Azure Cosmos DB for MongoDB (RU): replicas in every region, other # regions serve reads, continuous backup restores to a point in time. [.properties.locations[]?] as $locations | $base + {category: "database.mongodb", capabilities: [ "encryption-at-rest", "node-high-availability", cap("point-in-time-restore"; .properties.backupPolicy.type? == "Continuous"), cap("zone-high-availability"; any($locations[]; .isZoneRedundant == true)), cap("read-replicas"; ($locations | length) >= 2) ]} elif $t == "microsoft.documentdb/mongoclusters" then # Azure DocumentDB (vCore): with high availability, a standby per # shard; zone redundant only with ZoneRedundantPreferred (SameZone # keeps the standby in the primary's zone). Backups restore to a # point in time, and data is always encrypted. (.properties.highAvailability.targetMode? // "Disabled") as $hamode | ([.properties.sharding.shardCount? // 1, 1] | max) as $shards | $base + {category: "database.mongodb", capabilities: [ "encryption-at-rest", "point-in-time-restore", cap("node-high-availability"; $hamode != "Disabled"), cap("zone-high-availability"; $hamode == "ZoneRedundantPreferred"), cap("read-replicas"; $id | IN($mongoreplicated[])) ], size: size_of({count: ($shards * (if $hamode == "Disabled" then 1 else 2 end)), storageGiB: (.properties.storage.sizeGb? | if type == "number" then . * $shards else null end)})} elif $t == "microsoft.network/loadbalancers" and (.sku.name? // "" | IN("Standard", "Basic")) then # A Standard or Basic load balancer (a Gateway one is unclassified). # IPv6 only end to end: a rule from an IPv6 frontend to a pool with an # IPv6 member. Zone redundant: a Standard one with a frontend, or its # public IP, in two or more zones. Node high availability on the same # condition alone (issue #707; the guide's "Capabilities the programs # derive" cites the page and says when to remove it by hand). [.properties.frontendIPConfigurations[]?] as $fe | [.properties.backendAddressPools[]?] as $pools | [.properties.loadBalancingRules[]?] as $rules | ([$fe[] | select(.properties.privateIPAddressVersion? == "IPv6" or $byid[.properties.publicIPAddress.id? // "" | lid].properties.publicIPAddressVersion? == "IPv6") | .id | lid]) as $v6fe | ([$pools[] | select(any(.properties.backendIPConfigurations[]?.id | values; ipconfig_v6($byid)) or any(.properties.loadBalancerBackendAddresses[]?.properties.ipAddress | strings; contains(":"))) | .id | lid]) as $v6pools | (.sku.name == "Standard" and any($fe[]; zone_count >= 2 or ($byid[.properties.publicIPAddress.id? // "" | lid] | zone_count) >= 2)) as $zr | $base + {category: "network.loadbalancer", capabilities: [ cap("zone-high-availability"; $zr), cap("node-high-availability"; $zr), cap("udp"; any($rules[]; .properties.protocol? | IN("Udp", "All", "Quic"))), cap("ipv6"; any($rules[]; (.properties.frontendIPConfiguration.id? // "" | lid | IN($v6fe[])) and any(.properties.backendAddressPool.id?, .properties.backendAddressPools[]?.id | values | lid; IN($v6pools[])))) ]} elif $t == "microsoft.network/applicationgateways" then # Layer 7, and no IPv6 backends: never ipv6 or udp. $base + {category: "network.loadbalancer", capabilities: [ cap("zone-high-availability"; zone_count >= 2) ]} elif $t == "microsoft.fileshares/fileshares" then # A Microsoft.FileShares share, NFS only. Azure Files encrypts every # share at rest. if (.properties.protocol? // "" | ascii_downcase) == "nfs" then $base + {category: "storage.file", capabilities: [ "encryption-at-rest", cap("zone-high-availability"; .properties.redundancy? == "Zone") ], size: size_of({storageGiB: .properties.provisionedStorageGiB?})} else $base + {category: "unclassified"} end elif $t == "microsoft.hdinsight/clusters" then # An HDInsight cluster of kind Kafka (any casing: Azure returns the kind # as it was written) is Kafka on virtual machines Azure runs; any other # kind stays unclassified. Sized by its worker role (the query packs it # alone): the count, the VM size and the disks of each worker. Azure # encrypts its managed disks at rest. Never zone highly available: a # cluster with zones set is zonal, every node in the one zone chosen, # and does not survive that zone's loss. A cluster being deleted, deleted or # that failed (clusterState Deleting, Deleted, DeleteQueued, # DeleteTimeout, DeleteError, Error, Aborted or Timeout, any casing) is # left out; every other state is kept. if (.properties.clusterState? // "" | ascii_downcase | IN("deleting", "deleted", "deletequeued", "deletetimeout", "deleteerror", "error", "aborted", "timeout")) then empty elif (.properties.clusterDefinition.kind? // "" | ascii_downcase) == "kafka" then (.properties.computeProfile.roles[0]? // {}) as $worker | ($worker.dataDisksGroups[0]? // {}) as $disks | $base + {category: "messaging.kafka", capabilities: [ "encryption-at-rest", cap("node-high-availability"; ($worker.targetInstanceCount | type == "number" and . >= 3)) ], size: size_of(($worker.hardwareProfile.vmSize? | vm_size($vmsizes) // {}) + {count: ($worker.targetInstanceCount | if type == "number" and . >= 1 then . else null end), storageGiB: (if ($disks.disksPerNode | type) == "number" and ($disks.diskSizeGB | type) == "number" then $disks.disksPerNode * $disks.diskSizeGB else null end)})} else $base + {category: "unclassified"} end elif $t == "microsoft.network/dnszones" then # An Azure DNS zone, global (no region): public when its zoneType is # Public or missing (the API's default); a legacy private zone stays # unclassified. No record set is read, so never dns-routing. if (.properties.zoneType? // "Public" | ascii_downcase) == "private" then $base + {category: "unclassified"} else $base + {category: "network.dns", capabilities: [ cap("dnssec"; $id | IN($signedzones[])) ]} end elif $t == "microsoft.compute/snapshots" or $t == "microsoft.insights/autoscalesettings" then # Part of a disk's or a scale set's capabilities, not a resource to move. empty elif $t == "microsoft.servicebus/namespaces" and ($id | IN($queuenamespaces[])) then # Its queues and topics stand for it. empty else $base + {category: "unclassified"} end) ] | inventory("azure") SHIFT2EU_JQ_PROGRAM then build_failed "cannot write the embedded azure.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 azure.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/.azure.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