#!/usr/bin/env bash # shift2eu-inventory-aws.sh builds a shift2eu inventory of an AWS account. # # Generated by ci/inventoryscripts (make inventory-scripts) from the inventory # guide, docs/guide/inventory.md (its sections "Collect from AWS" and "Build # the AWS inventory"), with the program docs/guide/inventory/aws.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 aws CLI only lists, describes, gets or # queries. It reads no credential: the aws CLI signs in through its own # default credential chain. 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-aws.sh guide=https://github.com/timothymamo/shift2eu/blob/main/docs/guide/inventory.md usage() { cat <<'USAGE' Usage: shift2eu-inventory-aws.sh [--region ]... [--out ] [--keep-raw] [--with-optional] Builds a shift2eu inventory of an AWS account. It runs the read-only commands of the inventory guide's "Collect from AWS" section once per region, builds /aws.inventory.json with the guide's program aws.jq, embedded in this script, and deletes the raw output unless --keep-raw is given. Every command it runs with the aws CLI only lists, describes, gets or queries: it creates, changes, deletes or tags nothing in your account. Options: --region A region to collect, repeatable; "all" for every region enabled in the account. Default: AWS_REGION, then AWS_DEFAULT_REGION, then the region your CLI is configured with. --out Where the raw output and the inventory go; default inventories. The raw output goes to /aws//. --keep-raw Keep the raw output, /aws/, after the build. --with-optional Also run the commands the guide marks optional: the Route 53 routed record sets (dns-routing) and AWS Config. --help Print this help. It needs the aws CLI version 2, signed in as you normally sign in, and jq. AWS CloudShell has both, signed in: the easy route. On Windows, run it in WSL. The permissions its commands need, and a minimal policy, are in the guide: https://github.com/timothymamo/shift2eu/blob/main/docs/guide/inventory.md#aws-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, or the regions read for --region all); 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 } # region_name reports whether its argument is a region's name: never empty, # never an option. region_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 "$AWS_REGION: $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 "$AWS_REGION: failed: $2" failed="$failed $AWS_REGION: $2" elif [ -n "$step_err" ]; then say "$AWS_REGION: warned: $2" warned="$warned $AWS_REGION: $2" fi } # The collect steps: the commands of the guide's "Collect from AWS" section, # in its order, one function each, run once per region with AWS_REGION 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. # Writes ec2-instances.json. # shellcheck disable=SC2016 # a JMESPath literal in a single-quoted --query, for the CLI, not the shell step_1() { aws ec2 describe-instances --output json --query '{Reservations: Reservations[].{Instances: Instances[].{ InstanceId: InstanceId, InstanceType: InstanceType, State: {Name: State.Name}, Placement: {AvailabilityZone: Placement.AvailabilityZone}, BlockDeviceMappings: BlockDeviceMappings[].{Ebs: {VolumeId: Ebs.VolumeId}}, NetworkInterfaces: NetworkInterfaces[].{Ipv6AddressCount: length(Ipv6Addresses || `[]`)}, Tags: Tags[].{Key: Key}}}}' > "$out/ec2-instances.json" } # Writes opensearch-domain-names.json. step_2() { aws opensearch list-domain-names --output json \ --query '{DomainNames: DomainNames[].{DomainName: DomainName}}' > "$out/opensearch-domain-names.json" jq -r '.DomainNames[].DomainName' "$out/opensearch-domain-names.json" | xargs -r -n 5 aws opensearch describe-domains --output json --query '{DomainStatusList: DomainStatusList[].{ DomainName: DomainName, ARN: ARN, EngineVersion: EngineVersion, Deleted: Deleted, ClusterConfig: {InstanceType: ClusterConfig.InstanceType, InstanceCount: ClusterConfig.InstanceCount, ZoneAwarenessEnabled: ClusterConfig.ZoneAwarenessEnabled, MultiAZWithStandbyEnabled: ClusterConfig.MultiAZWithStandbyEnabled}, EBSOptions: {EBSEnabled: EBSOptions.EBSEnabled, VolumeSize: EBSOptions.VolumeSize}, EncryptionAtRestOptions: {Enabled: EncryptionAtRestOptions.Enabled}}}' --domain-names \ > "$out/opensearch-domains.json" } # Writes opensearchserverless-collections.json. step_3() { f="$out/opensearchserverless-collections.json" : > "$f" 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 ! page=$(in_assignment; aws opensearchserverless list-collections --output json --max-results 100 \ ${token:+--next-token} ${token:+"$token"} \ --query '{collectionSummaries: collectionSummaries[].{id: id, name: name}, nextToken: nextToken}'); then if [ -n "$token" ]; then echo "list-collections failed: $f is incomplete; collect $out again" >&2 else echo "list-collections failed on its first page: $f is empty;" \ "if the region runs OpenSearch Serverless, collect $out again" >&2 fi break fi printf '%s\n' "$page" >> "$f" last=$token token=$(in_assignment; printf '%s' "$page" | jq -r '.nextToken // empty') if [ -z "$token" ]; then break fi if [ "$token" = "$last" ]; then echo "list-collections repeated its nextToken: $f may be incomplete; collect $out again" >&2 break fi done : ) jq -r '.collectionSummaries[]?.id' "$f" | xargs -r -n 100 aws opensearchserverless batch-get-collection --output json --query '{collectionDetails: collectionDetails[].{name: name, arn: arn, type: type, standbyReplicas: standbyReplicas, status: status}}' --ids \ > "$out/opensearchserverless-batch-collections.json" } # Writes kafka-clusters-v2.json. step_4() { aws kafka list-clusters-v2 --output json --query '{ClusterInfoList: ClusterInfoList[].{ ClusterName: ClusterName, ClusterType: ClusterType, ClusterArn: ClusterArn, State: State, Provisioned: Provisioned.{NumberOfBrokerNodes: NumberOfBrokerNodes, BrokerNodeGroupInfo: BrokerNodeGroupInfo.{InstanceType: InstanceType, ClientSubnets: ClientSubnets, StorageInfo: {EbsStorageInfo: {VolumeSize: StorageInfo.EbsStorageInfo.VolumeSize}}}}}}' \ > "$out/kafka-clusters-v2.json" } # The vCPU and memory of the instance types in use. # A search domain's and a Kafka broker's instance type is built on an EC2 type # (r6g.large.search and kafka.m5.large are r6g.large and m5.large), asked for one # at a time: a type with no EC2 twin fails alone and its resource stays unsized. step_5() { { jq -r '[.Reservations[].Instances[].InstanceType] | unique[]' "$out/ec2-instances.json" | xargs -r -n 100 aws ec2 describe-instance-types --output json --query '{InstanceTypes: InstanceTypes[].{ InstanceType: InstanceType, VCpuInfo: {DefaultVCpus: VCpuInfo.DefaultVCpus}, MemoryInfo: {SizeInMiB: MemoryInfo.SizeInMiB}}}' --instance-types jq -rn '[inputs | (.DomainStatusList[]?.ClusterConfig.InstanceType // empty | select(endswith(".search")) | sub("\\.search$"; "")), (.ClusterInfoList[]?.Provisioned.BrokerNodeGroupInfo.InstanceType // empty | select(startswith("kafka.")) | sub("^kafka\\."; ""))] | unique[] | select(test("^o[a-z][0-9]") | not)' \ "$out/opensearch-domains.json" "$out/kafka-clusters-v2.json" | xargs -r -n 1 aws ec2 describe-instance-types --output json --query '{InstanceTypes: InstanceTypes[].{ InstanceType: InstanceType, VCpuInfo: {DefaultVCpus: VCpuInfo.DefaultVCpus}, MemoryInfo: {SizeInMiB: MemoryInfo.SizeInMiB}}}' --instance-types } > "$out/ec2-instance-types.json" } # Writes ec2-volumes.json. step_6() { aws ec2 describe-volumes --output json --query '{Volumes: Volumes[].{ VolumeId: VolumeId, AvailabilityZone: AvailabilityZone, Encrypted: Encrypted, Size: Size, Attachments: Attachments[].{InstanceId: InstanceId, DeleteOnTermination: DeleteOnTermination}}}' \ > "$out/ec2-volumes.json" } # Writes ec2-snapshots.json. step_7() { aws ec2 describe-snapshots --owner-ids self --output json \ --query '{Snapshots: Snapshots[].{VolumeId: VolumeId}}' > "$out/ec2-snapshots.json" } # Writes autoscaling-groups.json. step_8() { aws autoscaling describe-auto-scaling-groups --output json --query '{AutoScalingGroups: AutoScalingGroups[].{ AutoScalingGroupName: AutoScalingGroupName, AutoScalingGroupARN: AutoScalingGroupARN, MinSize: MinSize, MaxSize: MaxSize, AvailabilityZones: AvailabilityZones, Tags: Tags[].{Key: Key}}}' > "$out/autoscaling-groups.json" } # Writes s3-buckets.json. step_9() { aws s3api list-buckets --output json \ --query '{Buckets: Buckets[].{Name: Name, BucketRegion: BucketRegion}}' > "$out/s3-buckets.json" jq -r '.Buckets[].Name' "$out/s3-buckets.json" | while read -r bucket; do aws s3api get-bucket-versioning --bucket "$bucket" --output json --query '{Status: Status}' | jq --arg bucket "$bucket" '{Bucket: $bucket, Versioning: .}' done > "$out/s3-versioning.json" } # Writes rds-instances.json. step_10() { aws rds describe-db-instances --output json --query '{DBInstances: DBInstances[].{ DBInstanceIdentifier: DBInstanceIdentifier, DBInstanceArn: DBInstanceArn, DBClusterIdentifier: DBClusterIdentifier, Engine: Engine, AllocatedStorage: AllocatedStorage, AvailabilityZone: AvailabilityZone, BackupRetentionPeriod: BackupRetentionPeriod, MultiAZ: MultiAZ, StorageEncrypted: StorageEncrypted, ReadReplicaDBInstanceIdentifiers: ReadReplicaDBInstanceIdentifiers}}' > "$out/rds-instances.json" } # Writes elasticache-replication-groups.json. step_11() { aws elasticache describe-replication-groups --output json --query '{ReplicationGroups: ReplicationGroups[].{ ReplicationGroupId: ReplicationGroupId, ARN: ARN, Engine: Engine, AutomaticFailover: AutomaticFailover, MultiAZ: MultiAZ, ClusterEnabled: ClusterEnabled, SnapshotRetentionLimit: SnapshotRetentionLimit, AtRestEncryptionEnabled: AtRestEncryptionEnabled, StorageEncryptionType: StorageEncryptionType, MemberClusters: MemberClusters, NodeGroups: NodeGroups[].{ NodeGroupMembers: NodeGroupMembers[].{CacheClusterId: CacheClusterId}}, CacheNodeType: CacheNodeType}}' > "$out/elasticache-replication-groups.json" } # Writes elasticache-cache-clusters.json. step_12() { aws elasticache describe-cache-clusters --output json --query '{CacheClusters: CacheClusters[].{ CacheClusterId: CacheClusterId, ARN: ARN, ReplicationGroupId: ReplicationGroupId, Engine: Engine, NumCacheNodes: NumCacheNodes, SnapshotRetentionLimit: SnapshotRetentionLimit, AtRestEncryptionEnabled: AtRestEncryptionEnabled, CacheNodeType: CacheNodeType}}' > "$out/elasticache-cache-clusters.json" } # Writes elasticache-serverless-caches.json. step_13() { aws elasticache describe-serverless-caches --output json --query '{ServerlessCaches: ServerlessCaches[].{ ServerlessCacheName: ServerlessCacheName, ARN: ARN, Engine: Engine, SnapshotRetentionLimit: SnapshotRetentionLimit}}' \ > "$out/elasticache-serverless-caches.json" } # Writes elbv2-load-balancers.json. step_14() { aws elbv2 describe-load-balancers --output json --query '{LoadBalancers: LoadBalancers[].{ LoadBalancerName: LoadBalancerName, LoadBalancerArn: LoadBalancerArn, Type: Type, IpAddressType: IpAddressType, AvailabilityZones: AvailabilityZones[].{ZoneName: ZoneName}}}' \ > "$out/elbv2-load-balancers.json" jq -r '.LoadBalancers[].LoadBalancerArn' "$out/elbv2-load-balancers.json" | while read -r lb; do aws elbv2 describe-listeners --load-balancer-arn "$lb" --output json --query '{Listeners: Listeners[].{ ListenerArn: ListenerArn, LoadBalancerArn: LoadBalancerArn, Protocol: Protocol, Port: Port}}' done > "$out/elbv2-listeners.json" } # Writes elbv2-target-groups.json. step_15() { aws elbv2 describe-target-groups --output json --query '{TargetGroups: TargetGroups[].{ TargetGroupArn: TargetGroupArn, IpAddressType: IpAddressType, LoadBalancerArns: LoadBalancerArns}}' \ > "$out/elbv2-target-groups.json" } # The tag keys of the load balancers, to leave out those a Kubernetes cluster created. step_16() { jq -r '.LoadBalancers[].LoadBalancerArn' "$out/elbv2-load-balancers.json" | xargs -r -n 20 aws elbv2 describe-tags --output json --query '{TagDescriptions: TagDescriptions[].{ ResourceArn: ResourceArn, Tags: Tags[].{Key: Key}}}' --resource-arns > "$out/elbv2-tags.json" } # Writes elb-load-balancers.json. step_17() { aws elb describe-load-balancers --output json --query '{LoadBalancerDescriptions: LoadBalancerDescriptions[].{ LoadBalancerName: LoadBalancerName, AvailabilityZones: AvailabilityZones}}' \ > "$out/elb-load-balancers.json" } # Writes efs-file-systems.json. step_18() { aws efs describe-file-systems --output json --query '{FileSystems: FileSystems[].{ FileSystemId: FileSystemId, FileSystemArn: FileSystemArn, Encrypted: Encrypted, AvailabilityZoneName: AvailabilityZoneName, SizeInBytes: {Value: SizeInBytes.Value}}}' \ > "$out/efs-file-systems.json" } # Writes eks.json. step_19() { aws eks list-clusters --output json | jq -r '.clusters[]' | while read -r cluster; do aws eks describe-cluster --name "$cluster" --output json \ --query '{cluster: {name: cluster.name, arn: cluster.arn}}' aws eks list-nodegroups --cluster-name "$cluster" --output json | jq -r '.nodegroups[]' | while read -r nodegroup; do aws eks describe-nodegroup --cluster-name "$cluster" --nodegroup-name "$nodegroup" \ --output json --query '{nodegroup: {clusterName: nodegroup.clusterName, nodegroupArn: nodegroup.nodegroupArn, scalingConfig: nodegroup.scalingConfig, resources: {autoScalingGroups: nodegroup.resources.autoScalingGroups}}}' done done > "$out/eks.json" } # Writes lambda-functions.json. step_20() { aws lambda list-functions --output json \ --query '{Functions: Functions[].{FunctionName: FunctionName, FunctionArn: FunctionArn}}' \ > "$out/lambda-functions.json" } # Writes sqs-queues.json. step_21() { aws sqs list-queues --output json | jq -r '.QueueUrls[]?' | while read -r queue; do aws sqs get-queue-attributes --queue-url "$queue" --output json \ --attribute-names QueueArn RedrivePolicy SqsManagedSseEnabled KmsMasterKeyId done > "$out/sqs-queues.json" } # Writes sns-topics.json. step_22() { aws sns list-topics --output json | jq -r '.Topics[]?.TopicArn' | while read -r topic; do aws sns get-topic-attributes --topic-arn "$topic" --output json --query '{Attributes: { TopicArn: Attributes.TopicArn, KmsMasterKeyId: Attributes.KmsMasterKeyId}}' done > "$out/sns-topics.json" } # Route 53 hosted zones: each zone's ID, name and whether it is private. step_23() { aws route53 list-hosted-zones --output json \ --query 'HostedZones[].{Id: Id, Name: Name, PrivateZone: Config.PrivateZone}' \ > "$out/route53-hosted-zones.json" } # Whether each public zone is signed with DNSSEC: its signed state alone, never its keys. # The zone's ID is passed without the /hostedzone/ prefix the list writes. step_24() { jq -r '.[] | select(.PrivateZone == false) | .Id | ltrimstr("/hostedzone/")' \ "$out/route53-hosted-zones.json" | while IFS= read -r id; do aws route53 get-dnssec --hosted-zone-id "$id" --output json --query 'Status.ServeSignature' | jq --arg hz "$id" '{Id: ("/hostedzone/" + $hz), ServeSignature: .}' done | jq -s . > "$out/route53-dnssec.json" } # Optional, for dns-routing only (needs route53:ListResourceRecordSets, see "AWS permissions"): # how many record sets of each public zone route by client or by health, a count and no record. step_25() { jq -r '.[] | select(.PrivateZone == false) | .Id | ltrimstr("/hostedzone/")' \ "$out/route53-hosted-zones.json" | while IFS= read -r id; do aws route53 list-resource-record-sets --hosted-zone-id "$id" --output json \ --query 'length(ResourceRecordSets[?SetIdentifier || HealthCheckId || MultiValueAnswer || TrafficPolicyInstanceId])' | jq --arg hz "$id" '{Id: ("/hostedzone/" + $hz), RoutedRecordSets: .}' done | jq -s . > "$out/route53-routed-record-sets.json" } # Optional: everything else, from AWS Config (see "Everything else on AWS"). step_26() { aws configservice select-resource-config \ --expression "SELECT resourceId, resourceName, resourceType, awsRegion" \ --output json > "$out/config.json" } # The options. out_dir=inventories keep_raw=0 with_optional=0 all_regions=0 regions= while [ "$#" -gt 0 ]; do case $1 in --region) if [ "$#" -lt 2 ]; then usage_error "--region needs a value" fi case $2 in all) all_regions=1 ;; *) if has_control "$2"; then usage_error "--region holds a control character: pass the region's name alone" fi if ! region_name "$2"; then usage_error "--region $2 is no region name" fi case "$regions " in *" $2 "*) ;; *) regions="$regions $2" ;; esac ;; esac 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 if [ "$all_regions" = 1 ] && [ -n "$regions" ]; then usage_error "--region all takes no other --region" fi # --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/aws" inventory="$out_dir/aws.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 aws 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="aws" if ! command -v "$cli" > /dev/null 2>&1; then say "the aws CLI is not on PATH: install the AWS CLI version 2, as the guide's Before you start asks ($guide#before-you-start)" exit 3 fi # The output directories: /aws/ 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 created_regions= tmp_dir= staged= # remove_raw removes the raw output this run wrote: /aws/ when the run # created it, otherwise only the region directories it created there. remove_raw() { if [ "$raw_created" = 1 ]; then rm -r -- "$raw" raw_created=0 removed="the raw output in $raw" else removed= for region in $created_regions; do rm -r -- "${raw:?}/${region:?}" removed="$removed $region" done removed="the region directories$removed from $raw, which this run did not create and keeps" fi created_regions= } 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 regions: --region, or the region the CLI is configured with. A value # holding a control character is refused before any message echoes it, naming # where it came from (has_control). region_source= configured_region() { if [ -n "${AWS_REGION:-}" ]; then region_source=AWS_REGION region=$AWS_REGION elif [ -n "${AWS_DEFAULT_REGION:-}" ]; then region_source=AWS_DEFAULT_REGION region=$AWS_DEFAULT_REGION else region_source="aws configure get region" region=$(aws configure get region 2> /dev/null) || region= fi } if [ "$all_regions" = 1 ]; then configured_region home_region=$region if ! region_name "$home_region"; then home_region=us-east-1 fi elif [ -z "$regions" ]; then configured_region home_region=$region if [ -z "$home_region" ]; then usage_error "no region: pass --region , or set AWS_REGION" fi if has_control "$home_region"; then usage_error "the region from $region_source holds a control character: pass --region " fi if ! region_name "$home_region"; then usage_error "the configured region $home_region is no region name: pass --region " fi regions=" $home_region" else home_region=${regions# } home_region=${home_region%% *} fi export AWS_REGION="$home_region" # Sign-in. say "checking the sign-in with aws sts get-caller-identity, its answer discarded" if ! aws sts get-caller-identity --output json > /dev/null; then say "the aws CLI is not signed in, or may not call sts get-caller-identity: sign in as you normally do; the permissions are at $guide#aws-permissions" exit 4 fi if [ "$all_regions" = 1 ]; then say "reading the regions enabled in the account with aws ec2 describe-regions" if ! regions_json=$(aws ec2 describe-regions --output json --query '{Regions: Regions[].{RegionName: RegionName}}'); then say "aws ec2 describe-regions failed: the guide's policy grants ec2:DescribeRegions, see $guide#aws-permissions" exit 4 fi # A name holding a control character (C0, DEL or C1, U+0080-U+009F) is # refused while it is still JSON: once jq -r prints it, a line break in it # reads as two names. if ! regions_control=$(printf '%s\n' "$regions_json" | jq '[.Regions[].RegionName | strings | explode | any(. < 32 or . == 127 or (. > 127 and . < 160))] | any'); then say "aws ec2 describe-regions failed: its answer is no list of regions" exit 4 fi if [ "$regions_control" = true ]; then say "aws ec2 describe-regions named a region holding a control character" exit 4 fi if ! regions=$(printf '%s\n' "$regions_json" | jq -r '.Regions[].RegionName'); then say "aws ec2 describe-regions failed: its answer is no list of regions" exit 4 fi if [ -z "$regions" ]; then say "aws ec2 describe-regions named no region" exit 4 fi for region in $regions; do if ! region_name "$region"; then say "aws ec2 describe-regions named a region that is no region name" exit 4 fi done fi # Collect. if [ "$with_optional" = 0 ]; then step_skipped 'Optional, for dns-routing only (needs route53:ListResourceRecordSets, see "AWS permissions"): how many record sets of each public zone route by client or by health, a count and no record.' step_skipped 'Optional: everything else, from AWS Config (see "Everything else on AWS").' fi say "collecting into $raw, region by region:$regions" for region in $regions; do export AWS_REGION="$region" out="$raw/$region" mkdir -- "$out" created_regions="$created_regions $region" run_step step_1 'ec2-instances.json' run_step step_2 'opensearch-domain-names.json' run_step step_3 'opensearchserverless-collections.json' run_step step_4 'kafka-clusters-v2.json' run_step step_5 'The vCPU and memory of the instance types in use.' run_step step_6 'ec2-volumes.json' run_step step_7 'ec2-snapshots.json' run_step step_8 'autoscaling-groups.json' run_step step_9 's3-buckets.json' run_step step_10 'rds-instances.json' run_step step_11 'elasticache-replication-groups.json' run_step step_12 'elasticache-cache-clusters.json' run_step step_13 'elasticache-serverless-caches.json' run_step step_14 'elbv2-load-balancers.json' run_step step_15 'elbv2-target-groups.json' run_step step_16 'The tag keys of the load balancers, to leave out those a Kubernetes cluster created.' run_step step_17 'elb-load-balancers.json' run_step step_18 'efs-file-systems.json' run_step step_19 'eks.json' run_step step_20 'lambda-functions.json' run_step step_21 'sqs-queues.json' run_step step_22 'sns-topics.json' run_step step_23 'Route 53 hosted zones: each zone'\''s ID, name and whether it is private.' run_step step_24 'Whether each public zone is signed with DNSSEC: its signed state alone, never its keys.' if [ "$with_optional" = 1 ]; then run_step step_25 'Optional, for dns-routing only (needs route53:ListResourceRecordSets, see "AWS permissions"):' fi if [ "$with_optional" = 1 ]; then run_step step_26 'Optional: everything else, from AWS Config (see "Everything else on AWS").' fi done 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, aws.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 aws.jq (TMPDIR=${TMPDIR:-/tmp})" fi program="$tmp_dir/aws.jq" built="$tmp_dir/inventory.json" if ! cat > "$program" <<'SHIFT2EU_JQ_PROGRAM' # aws.jq turns the output of the read-only aws CLI 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, from one region or several: # # jq -n -f docs/guide/inventory/aws.jq inventories/aws/*/*.json > inventories/aws.inventory.json # # It recognises each input by its shape, not by its file name, and a file may hold # several JSON values one after the other. The guide's --query projections keep # only the fields read here; the full, unprojected output is read the same way: # # {"Reservations": ...} ec2 describe-instances # {"InstanceTypes": ...} ec2 describe-instance-types # {"Volumes": ...} ec2 describe-volumes # {"Snapshots": ...} ec2 describe-snapshots --owner-ids self # {"AutoScalingGroups": ...} autoscaling describe-auto-scaling-groups # {"Buckets": ...} s3api list-buckets # {"Bucket": ..., "Versioning"} s3api get-bucket-versioning, wrapped by the guide # {"DBInstances": ...} rds describe-db-instances # {"cluster": ...} eks describe-cluster # {"nodegroup": ...} eks describe-nodegroup # {"Functions": ...} lambda list-functions # {"Attributes": {"QueueArn"}} sqs get-queue-attributes # {"Attributes": {"TopicArn"}} sns get-topic-attributes # {"ReplicationGroups": ...} elasticache describe-replication-groups # {"CacheClusters": ...} elasticache describe-cache-clusters # {"ServerlessCaches": ...} elasticache describe-serverless-caches # {"LoadBalancers": ...} elbv2 describe-load-balancers # {"Listeners": ...} elbv2 describe-listeners # {"TargetGroups": ...} elbv2 describe-target-groups # {"TagDescriptions": ...} elbv2 describe-tags # {"LoadBalancerDescriptions"} elb describe-load-balancers (Classic) # {"FileSystems": ...} efs describe-file-systems # {"DomainStatusList": ...} opensearch describe-domains # {"collectionDetails": ...} opensearchserverless batch-get-collection # {"ClusterInfoList": ...} kafka list-clusters-v2 # {"Results": [...]} configservice select-resource-config (optional; # one value per page if you page by hand) # {"HostedZones": ...} route53 list-hosted-zones, unprojected # # Three inputs are arrays of objects, one object per hosted zone, which the # guide's Route 53 commands write: # # [{"Id", "Name", "PrivateZone"}] route53 list-hosted-zones # [{"Id", "ServeSignature"}] route53 get-dnssec, per public zone # [{"Id", "RoutedRecordSets"}] route53 list-resource-record-sets, per public # zone, reduced to a count (optional) # # The outputs of opensearch list-domain-names and opensearchserverless # list-collections only feed the calls that describe them; the program reads # neither. # # Resource IDs are short (an instance ID, a bucket or queue name), never an ARN, # which would carry the account ID. Anything it cannot classify is "unclassified" # with its rawType (a CloudFormation type), so it shows up as a blocker. # # The nodes of an EKS cluster are left out, the cluster stands for them: the Auto # Scaling groups of its managed node groups, and instances and Auto Scaling groups # tagged eks:cluster-name or kubernetes.io/cluster/. A load balancer tagged # elbv2.k8s.aws/cluster (the AWS Load Balancer Controller made it) is left out # with its cluster too. An instance an Auto Scaling group launched is left out, # the group stands for it. The volumes deleted with an instance left out go with # it (a persistent volume, which outlives its instance, stays). The member # clusters of an ElastiCache replication group are left out, the group stands # for them, and so are the instances of a DocumentDB cluster, which is one # resource. # # The size comes from the calls too: an instance's vCPU and memory from its # instance type (ec2 describe-instance-types), a volume's GiB (Size), a DB # instance's allocated storage (AllocatedStorage; none for an instance in a DB # cluster, Aurora or an RDS Multi-AZ DB cluster, whose storage belongs to the # cluster), a single-node DB instance's count of 1 (MultiAZ not true; an # instance with a standby gets no count, how many nodes a target bills for a # standby is the target's to say), an EKS cluster's node count (the desired # sizes of its managed node groups), a cache's node count (a replication # group's member clusters, a standalone cluster's NumCacheNodes), a DocumentDB # cluster's instance count, an EFS file system's metered size, and a search # domain's or a Kafka cluster's data nodes or brokers (their count, their # per-node volume, and the vCPU and memory of the EC2 type their instance type # is built on: r6g.large.search and kafka.m5.large are r6g.large and m5.large, # which ec2 describe-instance-types sizes). 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 CloudFormation types the service calls above cover. AWS Config lists them # too; those entries are dropped, so a resource is not listed twice. An Aurora # cluster (AWS::RDS::DBCluster) is covered by its instances, which # rds describe-db-instances lists; AWS Config records a DocumentDB cluster as # AWS::RDS::DBCluster too, and its instances stand for it the same way. # ElastiCache is not in this list: AWS Config records no AWS::ElastiCache::* # type (its developer guide's "Supported Resource Types" reference, checked # 2026-11-25), so the elasticache calls are the only source of caches and none # is listed twice. A Route 53 hosted zone is covered by route53 # list-hosted-zones, public and private alike, and a zone's DNSSEC configuration # (AWS::Route53::DNSSEC) by get-dnssec, which reads its signed state into the # zone's dnssec: a signed zone is listed once. def covered_types: [ "AWS::EC2::Instance", "AWS::EC2::Volume", "AWS::AutoScaling::AutoScalingGroup", "AWS::S3::Bucket", "AWS::RDS::DBInstance", "AWS::RDS::DBCluster", "AWS::EKS::Cluster", "AWS::Lambda::Function", "AWS::SQS::Queue", "AWS::SNS::Topic", "AWS::EFS::FileSystem", "AWS::ElasticLoadBalancingV2::LoadBalancer", "AWS::ElasticLoadBalancing::LoadBalancer", "AWS::OpenSearch::Domain", "AWS::Elasticsearch::Domain", "AWS::Route53::HostedZone", "AWS::Route53::DNSSEC" ]; # AWS Config records an OpenSearch Service domain as AWS::OpenSearch::Domain, or # the legacy AWS::Elasticsearch::Domain, not as its CloudFormation type # AWS::OpenSearchService::Domain (its developer guide's "Supported Resource # Types" reference, checked 2026-11-26): both are in covered_types above, since # opensearch describe-domains lists every domain. An MSK cluster and an # OpenSearch Serverless collection are recorded under their CloudFormation # types; their Config rows are dropped when the service call lists a resource # of that type and region with the same name or ID ($listed below): Config may # record a collection by its ID alone, and a cluster by its ARN alone. def listed_by_call_types: ["AWS::MSK::Cluster", "AWS::MSK::ServerlessCluster", "AWS::OpenSearchServerless::Collection"]; # The parts and settings of a classified resource that AWS Config records as # types of their own: a load balancer's listeners, rules and target groups, an # EFS file system's access points, an ECR registry's settings and repository # creation templates, an MSK cluster's configurations, policy, SCRAM secrets and # VPC connections, and an OpenSearch Serverless collection's access, security, # lifecycle and encryption policies, security configurations and VPC endpoints. # The resource stands for them, so they are dropped, not listed as # unclassified. def part_types: [ "AWS::ElasticLoadBalancingV2::Listener", "AWS::ElasticLoadBalancingV2::ListenerRule", "AWS::ElasticLoadBalancingV2::TargetGroup", "AWS::EFS::AccessPoint", "AWS::ECR::RegistryPolicy", "AWS::ECR::ReplicationConfiguration", "AWS::ECR::PullThroughCacheRule", "AWS::ECR::RepositoryCreationTemplate", "AWS::MSK::Configuration", "AWS::MSK::ClusterPolicy", "AWS::MSK::BatchScramSecret", "AWS::MSK::VpcConnection", "AWS::OpenSearchServerless::AccessPolicy", "AWS::OpenSearchServerless::SecurityPolicy", "AWS::OpenSearchServerless::SecurityConfig", "AWS::OpenSearchServerless::LifecyclePolicy", "AWS::OpenSearchServerless::VpcEndpoint" ]; # The category of an AWS Config type that needs no service call: the type is # enough. Any other type is unclassified. def config_category: if . == "AWS::AppRunner::Service" then "serverless.container" elif . == "AWS::ECR::Repository" then "registry.container" else "unclassified" end; # True for an ElastiCache engine that speaks the Redis protocol. def is_redis: . == "redis" or . == "valkey"; # True for an OpenSearch Service engine version that speaks the OpenSearch REST # API: OpenSearch, or Elasticsearch 7.x, from whose 7.10.2 OpenSearch was # forked. Elasticsearch before 7.0 still has mapping types, so a client of it # needs a change before it runs on OpenSearch. def is_opensearch_api: test("^OpenSearch_") or test("^Elasticsearch_7\\."); # The EC2 instance type a search or Kafka instance type is built on: # r6g.large.search -> r6g.large, kafka.m5.large -> m5.large. A type with no EC2 # twin (or1.large.search, express.m7g.large) is not in ec2 describe-instance-types, # so its lookup finds nothing and the resource stays unsized. def ec2_twin: if endswith(".search") then sub("\\.search$"; "") elif startswith("kafka.") then sub("^kafka\\."; "") else . end; # True for an instance or an Auto Scaling group that is a Kubernetes node, by its # tag keys. def is_node: any(.Tags[]?.Key // empty; . == "eks:cluster-name" or startswith("kubernetes.io/cluster/")); # A hosted zone's ID without the /hostedzone/ prefix list-hosted-zones writes, # so a zone matches its get-dnssec and record-set entries whichever form they # hold: /hostedzone/Z0123456789ABCDEFGHIJ -> Z0123456789ABCDEFGHIJ. def zone_id: ltrimstr("/hostedzone/"); # The region of an availability zone: eu-central-1a -> eu-central-1. def zone_region: if . == null or . == "" then null else sub("[a-z]$"; "") end; # The region field of an ARN: arn:aws:sqs:eu-central-1:123456789012:q -> eu-central-1. def arn_region: if . == null then null else split(":")[3] end; # A short ID: an ARN loses its partition, service, region and account and keeps # the last element of its resource part. def short_id: if startswith("arn:") then split(":")[5:] | join(":") | split("/") | last else . 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 (from two regions' global calls) 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: .}; [inputs] as $inputs | [$inputs[] | objects] as $docs | [$inputs[] | arrays | .[] | objects] as $items | ([$items[] | select(has("ServeSignature")) | select(.ServeSignature == "SIGNING") | .Id | strings | zone_id] | unique) as $signed | ([$items[] | select(has("RoutedRecordSets")) | select((.RoutedRecordSets // 0) > 0) | .Id | strings | zone_id] | unique) as $routed # Hosted zones, one per zone ID: each region's run lists the same zones. The # guide's projection writes an array of zones; the unprojected response holds # them under HostedZones, each zone's visibility in its Config. Only the ID, the # name and the visibility are kept, never CallerReference or the Config comment. | ([($items[] | select(has("PrivateZone") and has("Id") and has("Name")) | {Id, Name, PrivateZone}), ($docs[] | .HostedZones? // empty | arrays | .[] | objects | select(has("Id") and has("Name")) | {Id, Name, PrivateZone: .Config.PrivateZone?})] | map({zone: (.Id | zone_id), Name, PrivateZone}) | unique | group_by(.zone) | map(.[0])) as $zones # The names two or more distinct zones share (a public and a private zone of one # name, split-horizon DNS). | ([$zones[] | .Name] | group_by(.) | map(select(length > 1) | .[0])) as $sharedzonenames |([$docs[] | .Snapshots? // empty | .[] | .VolumeId] | unique) as $snapshotted | ([$docs[] | select(.Bucket? and has("Versioning")) | select(.Versioning.Status? == "Enabled") | .Bucket] | unique) as $versioned | ([$docs[] | .InstanceTypes? // empty | .[] | {key: .InstanceType, value: {vcpus: .VCpuInfo.DefaultVCpus, memoryGiB: (.MemoryInfo.SizeInMiB / 1024)}}] | from_entries) as $types | [$docs[] | .nodegroup? // empty] as $nodegroups | [$docs[] | .Reservations? // empty | .[].Instances[]? | select(is_node or ([.Tags[]?.Key] | index("aws:autoscaling:groupName"))) | .InstanceId] as $leftout | ([$nodegroups[] | .resources.autoScalingGroups[]?.name] + [$docs[] | .AutoScalingGroups? // empty | .[] | select(is_node) | .AutoScalingGroupName] | unique) as $nodegroupasgs | ([$docs[] | .TagDescriptions? // empty | .[] | select(any(.Tags[]?.Key // empty; . == "elbv2.k8s.aws/cluster")) | .ResourceArn] | unique) as $k8slbs | [$docs[] | .Listeners? // empty | .[]] as $listeners | [$docs[] | .TargetGroups? // empty | .[]] as $targetgroups | [$docs[] | .DBInstances? // empty | .[] | select(.Engine == "docdb") | . + {cluster: (.DBClusterIdentifier // .DBInstanceIdentifier), region: (.DBInstanceArn | arn_region)}] as $docdb | ([$docs[] | .ClusterInfoList? // empty | .[] | (if .ClusterType == "SERVERLESS" then "AWS::MSK::ServerlessCluster" else "AWS::MSK::Cluster" end) as $type | (.ClusterArn | arn_region) as $region | (.ClusterName, (.ClusterArn | short_id)) | [$type, ., $region]] + [$docs[] | .collectionDetails? // empty | .[] | (.arn | arn_region) as $region | (.name, (.arn | short_id)) | ["AWS::OpenSearchServerless::Collection", ., $region]] | unique) as $listed | [ # EC2 instances. One launched by an Auto Scaling group is left out: the group # stands for it. A Kubernetes node is left out: its cluster stands for it. # An instance of a bare-metal instance type (*.metal, or a sized # *.metal-* such as c7i.metal-24xl) is a dedicated physical server, # compute.baremetal (ADR 0023); any other is compute.vm. ($docs[] | .Reservations? // empty | .[].Instances[]? | select(.State.Name != "terminated" and .State.Name != "shutting-down") | select([.Tags[]?.Key] | index("aws:autoscaling:groupName") | not) | select(is_node | not) | { id: .InstanceId, rawType: "AWS::EC2::Instance", category: (if (.InstanceType // "") | test("\\.metal(-|$)") then "compute.baremetal" else "compute.vm" end), region: (.Placement.AvailabilityZone | zone_region), capabilities: [ cap("ipv6"; any(.NetworkInterfaces[]?; ((.Ipv6Addresses // []) | length > 0) or (.Ipv6AddressCount // 0) > 0)), cap("snapshots"; any(.BlockDeviceMappings[]?; .Ebs.VolumeId | IN($snapshotted[]))) ], size: size_of($types[.InstanceType // ""] // {}) }), # EBS volumes. A volume deleted with an instance left out (a Kubernetes # node or an Auto Scaling group member), such as its root volume, is left # out with it. ($docs[] | .Volumes? // empty | .[] | select(any(.Attachments[]?; .DeleteOnTermination == true and (.InstanceId | IN($leftout[]))) | not) | { id: .VolumeId, rawType: "AWS::EC2::Volume", category: "storage.block", region: (.AvailabilityZone | zone_region), capabilities: [ cap("encryption-at-rest"; .Encrypted == true), cap("snapshots"; .VolumeId | IN($snapshotted[])) ], size: size_of({storageGiB: .Size}) }), # Auto Scaling groups. The group of a managed node group, or one tagged as a # Kubernetes node group, is left out: its cluster stands for it. ($docs[] | .AutoScalingGroups? // empty | .[] | select(.AutoScalingGroupName | IN($nodegroupasgs[]) | not) | { id: .AutoScalingGroupName, rawType: "AWS::AutoScaling::AutoScalingGroup", category: "compute.vm", region: (.AutoScalingGroupARN | arn_region), capabilities: [ cap("autoscaling"; .MaxSize > .MinSize), cap("zone-high-availability"; (.AvailabilityZones // []) | length >= 2) ] }), # S3 buckets. S3 encrypts every object at rest (SSE-S3 by default since 2023). ($docs[] | .Buckets? // empty | .[] | { id: .Name, rawType: "AWS::S3::Bucket", category: "storage.object", region: .BucketRegion, capabilities: [ "encryption-at-rest", cap("object-versioning"; .Name | IN($versioned[])) ] }), # RDS DB instances: the engine decides the category; any other engine is # unclassified. An Aurora cluster is assessed per instance. An instance in # a DB cluster (DBClusterIdentifier set: Aurora, or an RDS Multi-AZ DB # cluster) gets no storage size: its storage belongs to the cluster, and # AllocatedStorage does not describe it. A single-node instance (MultiAZ # not true) is one instance; one with a standby gets no count, since how # many nodes a standby is depends on how a target prices it. A DocumentDB # instance is left out here: its cluster is listed below. ($docs[] | .DBInstances? // empty | .[] | select(.Engine != "docdb") | (if .Engine == "postgres" or .Engine == "aurora-postgresql" then "database.postgresql" elif .Engine == "mysql" or .Engine == "aurora-mysql" then "database.mysql" else "unclassified" end) as $category | { id: .DBInstanceIdentifier, rawType: "AWS::RDS::DBInstance", category: $category, region: (.DBInstanceArn | arn_region), capabilities: (if $category == "unclassified" then [] else [ cap("point-in-time-restore"; (.BackupRetentionPeriod // 0) > 0), cap("read-replicas"; (.ReadReplicaDBInstanceIdentifiers // []) | length > 0), cap("zone-high-availability"; .MultiAZ == true), cap("encryption-at-rest"; .StorageEncrypted == true) ] end), size: (if $category == "unclassified" or .DBClusterIdentifier != null then null else size_of({storageGiB: .AllocatedStorage, count: (if .MultiAZ == true then null else 1 end)}) end) }), # DocumentDB clusters, one resource each from the instances # rds describe-db-instances lists with engine docdb, grouped by cluster and # region. Backups and encryption are cluster settings; no page says an # instance reports its cluster's, so a capability holds only when every # instance reports it. The storage is the cluster volume, which # AllocatedStorage does not describe: no storageGiB. ($docdb | group_by([.region, .cluster])[] | { id: .[0].cluster, rawType: "AWS::DocDB::DBCluster", category: "database.mongodb", region: .[0].region, capabilities: [ cap("point-in-time-restore"; all(.[]; (.BackupRetentionPeriod // 0) > 0)), cap("encryption-at-rest"; all(.[]; .StorageEncrypted == true)), cap("read-replicas"; length >= 2), cap("node-high-availability"; length >= 2), cap("zone-high-availability"; [.[].AvailabilityZone // empty] | unique | length >= 2) ], size: {count: length} }), # ElastiCache replication groups: one cache each, its member clusters its # nodes. Failover is node high availability only when every shard has a # replica to promote (two or more NodeGroupMembers in each node group): a # cluster-mode group must turn failover on even with none, and a shard # with a primary only loses its data with its node. StorageEncryptionType # is the effective encryption state; AtRestEncryptionEnabled can be false # while it is on. ($docs[] | .ReplicationGroups? // empty | .[] | ((.Engine // "") | is_redis) as $redis | ((.MemberClusters // []) | length) as $nodes | { id: .ReplicationGroupId, rawType: "AWS::ElastiCache::ReplicationGroup", category: (if $redis then "cache.redis" else "unclassified" end), region: (.ARN | arn_region), capabilities: (if $redis then [ cap("node-high-availability"; .AutomaticFailover == "enabled" and ((.NodeGroups // []) | length >= 1 and all(.[]; (.NodeGroupMembers // []) | length >= 2))), cap("zone-high-availability"; .MultiAZ == "enabled"), cap("sharding"; .ClusterEnabled == true), cap("snapshots"; (.SnapshotRetentionLimit // 0) > 0), cap("encryption-at-rest"; if .StorageEncryptionType != null then .StorageEncryptionType == "sse-elasticache" or .StorageEncryptionType == "sse-kms" else .AtRestEncryptionEnabled == true end) ] else [] end), size: (if $redis and $nodes >= 1 then {count: $nodes} else null end) }), # ElastiCache clusters outside a replication group (a member cluster is # left out: its group stands for it). Memcached is not the Redis protocol. ($docs[] | .CacheClusters? // empty | .[] | select((.ReplicationGroupId // "") == "") | ((.Engine // "") | is_redis) as $redis | { id: .CacheClusterId, rawType: "AWS::ElastiCache::CacheCluster", category: (if $redis then "cache.redis" else "unclassified" end), region: (.ARN | arn_region), capabilities: (if $redis then [ cap("snapshots"; (.SnapshotRetentionLimit // 0) > 0), cap("encryption-at-rest"; .AtRestEncryptionEnabled == true) ] else [] end), size: (if $redis then size_of({count: .NumCacheNodes}) else null end) }), # ElastiCache Serverless caches: always replicated across three zones, # always encrypted at rest and always in cluster mode. No size: no node # type, and the data storage limit is a limit, not a size. ($docs[] | .ServerlessCaches? // empty | .[] | ((.Engine // "") | is_redis) as $redis | { id: .ServerlessCacheName, rawType: "AWS::ElastiCache::ServerlessCache", category: (if $redis then "cache.redis" else "unclassified" end), region: (.ARN | arn_region), capabilities: (if $redis then [ "node-high-availability", "zone-high-availability", "sharding", "encryption-at-rest", cap("snapshots"; (.SnapshotRetentionLimit // 0) > 0) ] else [] end) }), # Application and Network Load Balancers; a Gateway Load Balancer is # unclassified. One a Kubernetes cluster made is left out. ipv6 needs IPv6 # at both ends: a dualstack load balancer and an IPv6 target group of its # own. udp: a listener of a protocol that carries UDP (QUIC runs over UDP). ($docs[] | .LoadBalancers? // empty | .[] | select(.LoadBalancerArn | IN($k8slbs[]) | not) | .LoadBalancerArn as $arn | (.Type == "application" or .Type == "network") as $lb | { id: .LoadBalancerName, rawType: "AWS::ElasticLoadBalancingV2::LoadBalancer", category: (if $lb then "network.loadbalancer" else "unclassified" end), region: ($arn | arn_region), capabilities: (if $lb then [ cap("zone-high-availability"; [.AvailabilityZones[]?.ZoneName] | unique | length >= 2), cap("udp"; any($listeners[]; .LoadBalancerArn == $arn and (.Protocol | IN("UDP", "TCP_UDP", "QUIC", "TCP_QUIC")))), cap("ipv6"; (.IpAddressType | IN("dualstack", "dualstack-without-public-ipv4")) and any($targetgroups[]; .IpAddressType == "ipv6" and any(.LoadBalancerArns[]?; . == $arn))) ] else [] end) }), # Classic Load Balancers: no ARN, so the region comes from a zone; their # listeners are HTTP, HTTPS, TCP or SSL, and they have no IPv6 type. ($docs[] | .LoadBalancerDescriptions? // empty | .[] | { id: .LoadBalancerName, rawType: "AWS::ElasticLoadBalancing::LoadBalancer", category: "network.loadbalancer", region: (.AvailabilityZones[0]? | zone_region), capabilities: [ cap("zone-high-availability"; (.AvailabilityZones // []) | unique | length >= 2) ] }), # EFS file systems. A Regional one (no AvailabilityZoneName) stores data # across zones; a One Zone one does not. EFS has no provisioned size: the # size is the metered size of the data stored. ($docs[] | .FileSystems? // empty | .[] | { id: .FileSystemId, rawType: "AWS::EFS::FileSystem", category: "storage.file", region: (.FileSystemArn | arn_region), capabilities: [ cap("encryption-at-rest"; .Encrypted == true), cap("zone-high-availability"; (.AvailabilityZoneName // "") == "") ], size: size_of({storageGiB: (if .SizeInBytes.Value? == null then null else .SizeInBytes.Value / 1073741824 end)}) }), # EKS clusters, with their managed node groups. Cluster names are unique per # region only, so a node group matches by name and region. ($docs[] | .cluster? // empty | .name as $name | (.arn | arn_region) as $region | [$nodegroups[] | select(.clusterName == $name and (.nodegroupArn | arn_region) == $region)] as $groups | { id: .name, rawType: "AWS::EKS::Cluster", category: "kubernetes.managed", region: (.arn | arn_region), capabilities: [ cap("autoscaling"; any($groups[]; .scalingConfig.maxSize > .scalingConfig.minSize)), cap("node-high-availability"; ([$groups[].scalingConfig.desiredSize // 0] | add // 0) >= 2) ], size: size_of({count: ([$groups[].scalingConfig.desiredSize // 0] | add // 0 | if . >= 1 then . else null end)}) }), # Amazon OpenSearch Service domains. One on OpenSearch or Elasticsearch 7.x # is search.opensearch; one before 7.0 is unclassified, with no capability # and no size. Every domain takes automated snapshots (hourly on 5.3 and # later). Its data nodes are its size: InstanceCount nodes (the dedicated # masters are not data nodes) of the EC2 type its instance type is built # on, each with an EBS volume of VolumeSize GiB; a domain on instance # storage (EBSEnabled false) gets no storageGiB. A domain being deleted # (Deleted true) is left out, as a terminated EC2 instance is. ($docs[] | .DomainStatusList? // empty | .[] | select(.Deleted != true) | ((.EngineVersion // "") | is_opensearch_api) as $search | (.ClusterConfig // {}) as $cluster | { id: .DomainName, rawType: "AWS::OpenSearchService::Domain", category: (if $search then "search.opensearch" else "unclassified" end), region: (.ARN | arn_region), capabilities: (if $search then [ cap("node-high-availability"; ($cluster.InstanceCount // 0) >= 2), cap("zone-high-availability"; $cluster.ZoneAwarenessEnabled == true or $cluster.MultiAZWithStandbyEnabled == true), cap("encryption-at-rest"; .EncryptionAtRestOptions.Enabled == true), "snapshots" ] else [] end), size: (if $search then size_of(($types[$cluster.InstanceType // "" | ec2_twin] // {}) + { storageGiB: (if .EBSOptions.EBSEnabled == true then .EBSOptions.VolumeSize else null end), count: $cluster.InstanceCount}) else null end) }), # OpenSearch Serverless collections: always encrypted at rest, and # snapshotted every hour into restorable snapshots; standby replicas in # another zone are their node and zone high availability. No size: a # collection is billed by OCUs, not nodes. A collection being deleted or # that failed (status DELETING or FAILED) is left out. ($docs[] | .collectionDetails? // empty | .[] | select(.status != "DELETING" and .status != "FAILED") | { id: .name, rawType: "AWS::OpenSearchServerless::Collection", category: "search.opensearch", region: (.arn | arn_region), capabilities: [ "encryption-at-rest", "snapshots", cap("node-high-availability"; .standbyReplicas == "ENABLED"), cap("zone-high-availability"; .standbyReplicas == "ENABLED") ] }), # Amazon MSK clusters, provisioned and serverless. MSK always encrypts data # at rest. A provisioned cluster's brokers are spread evenly over the zones # of its client subnets, one subnet per zone (two or three); its size is # NumberOfBrokerNodes brokers of the EC2 type its broker type is built on, # each with an EBS volume of VolumeSize GiB (Express brokers have no EC2 # twin and no volume, so they stay unsized). A serverless cluster has no # broker to size and replicates across zones. A cluster being deleted or # that failed (State DELETING or FAILED) is left out. ($docs[] | .ClusterInfoList? // empty | .[] | select(.State != "DELETING" and .State != "FAILED") | if .ClusterType == "SERVERLESS" then { id: .ClusterName, rawType: "AWS::MSK::ServerlessCluster", category: "messaging.kafka", region: (.ClusterArn | arn_region), capabilities: ["node-high-availability", "zone-high-availability", "encryption-at-rest"] } else (.Provisioned // {}) as $cluster | ($cluster.BrokerNodeGroupInfo // {}) as $brokers | { id: .ClusterName, rawType: "AWS::MSK::Cluster", category: "messaging.kafka", region: (.ClusterArn | arn_region), capabilities: [ "encryption-at-rest", cap("node-high-availability"; ($cluster.NumberOfBrokerNodes // 0) >= 2), cap("zone-high-availability"; ($brokers.ClientSubnets // []) | length >= 2) ], size: size_of(($types[$brokers.InstanceType // "" | ec2_twin] // {}) + { storageGiB: $brokers.StorageInfo.EbsStorageInfo.VolumeSize, count: $cluster.NumberOfBrokerNodes}) } end), # Lambda functions. ($docs[] | .Functions? // empty | .[] | { id: .FunctionName, rawType: "AWS::Lambda::Function", category: "serverless.function", region: (.FunctionArn | arn_region) }), # SQS queues. ($docs[] | .Attributes? // empty | select(.QueueArn?) | { id: (.QueueArn | short_id), rawType: "AWS::SQS::Queue", category: "messaging.queue", region: (.QueueArn | arn_region), capabilities: [ cap("dead-letter-queue"; has("RedrivePolicy")), cap("encryption-at-rest"; .SqsManagedSseEnabled == "true" or has("KmsMasterKeyId")) ] }), # SNS topics. A dead-letter queue is set per subscription, which no topic # attribute says, so a topic never gets dead-letter-queue. ($docs[] | .Attributes? // empty | select(.TopicArn?) | { id: (.TopicArn | short_id), rawType: "AWS::SNS::Topic", category: "messaging.topic", region: (.TopicArn | arn_region), capabilities: [ cap("encryption-at-rest"; (.KmsMasterKeyId // "") != "") ] }), # Route 53 hosted zones, from list-hosted-zones, each zone once by its zone # ID ($zones). A zone's ID is its name; zones that share a name each get # their zone ID appended, "shop.example.com. (Z0123456789ABCDEFGHIJ)", so # two distinct zones never merge. A public zone is a public authoritative # DNS zone, network.dns, served by Route 53's name servers from no region # the user picks, so it has no region and no size. It is signed (dnssec) # when get-dnssec's ServeSignature is SIGNING, and routes by client or by # health (dns-routing) when it holds a routed record set: one with a set # identifier (weighted, latency, failover, geolocation, geoproximity, # IP-based or multivalue answer), a health check, a multivalue answer or a # traffic policy instance. A private zone answers only inside the VPCs it # is attached to: unclassified. ($zones[] | (.PrivateZone == false) as $public | .zone as $zone | { id: (if .Name | IN($sharedzonenames[]) then .Name + " (" + $zone + ")" else .Name end), rawType: "AWS::Route53::HostedZone", category: (if $public then "network.dns" else "unclassified" end), capabilities: (if $public then [ cap("dnssec"; $zone | IN($signed[])), cap("dns-routing"; $zone | IN($routed[])) ] else [] end) }), # Everything else AWS Config recorded. App Runner services and ECR # repositories need no call: the type is enough, and ECR encrypts every # repository at rest. The row of an MSK cluster or an OpenSearch Serverless # collection the service calls list, by type, region and either name or ID # (an ARN's last segment), is dropped. Any other type is unclassified. ($docs[] | .Results? // empty | .[] | if type == "string" then fromjson else . end | select(.resourceType | IN(covered_types[], part_types[]) | not) | select((.resourceType | IN(listed_by_call_types[])) and (. as $row | any((.resourceName, .resourceId) | strings | short_id; [$row.resourceType, ., $row.awsRegion] | IN($listed[]))) | not) | (.resourceType | config_category) as $category | { id: ((.resourceName // .resourceId) | short_id), rawType: .resourceType, category: $category, region: (if .awsRegion == "global" then null else .awsRegion end), capabilities: [cap("encryption-at-rest"; $category == "registry.container")] }) ] | inventory("aws") SHIFT2EU_JQ_PROGRAM then build_failed "cannot write the embedded aws.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 aws.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/.aws.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