Support copying to additional regions without duplication

This commit is contained in:
Neil Hanlon 2022-05-23 13:32:39 -04:00
parent d845b95e80
commit dca415c01e
Signed by untrusted user: neil
GPG Key ID: 705BC21EC3C70F34

View File

@ -28,6 +28,10 @@ fi
function copy(){ function copy(){
for region in $REGIONS; do for region in $REGIONS; do
if find_image_by_name $region; then
echo "Found copy of $source_ami in $region - $found_image_id - Skipping"
continue
fi
echo -n "Creating copy job for $region..." echo -n "Creating copy job for $region..."
ami_id=$(aws --profile resf-ami ec2 copy-image \ ami_id=$(aws --profile resf-ami ec2 copy-image \
--region $region \ --region $region \
@ -36,7 +40,7 @@ function copy(){
--source-region "${source_region}" \ --source-region "${source_region}" \
--output text 2>&1) --output text 2>&1)
if [[ $? -eq 0 ]]; then if [[ $? -eq 0 ]]; then
unset ami_ids[$region] unset ami_ids[$region]
echo ". $ami_id" echo ". $ami_id"
if [[ ! -z "$ami_id" ]]; then if [[ ! -z "$ami_id" ]]; then
ami_ids[$region]="$ami_id" ami_ids[$region]="$ami_id"
@ -93,28 +97,26 @@ function change_privacy(){
} }
function find_image_by_name(){ function find_image_by_name(){
# ami_ids[region]=ami_id # found_ami_ids[region]=ami_id
for region in $REGIONS; do # ami-id "name"
expected_name="Copy of ${source_ami} from ${source_region}" local query="$(printf 'Images[?Name==`%s`]|[?Public==`true`].[ImageId,Name][]' "${SOURCE_AMI_NAME}")"
# ami-id "name" mapfile -t res < <(
local query="$(printf 'Images[?Name==`%s`]|[?Public==`true`].[ImageId,Name][]' "${expected_name}")" aws --profile resf-ami ec2 describe-images --region $region --owners $RESF_AMI_ACCOUNT_ID \
mapfile -t res < <( --query "${query}" 2>/dev/null \
aws --profile resf-ami ec2 describe-images --region $region --owners $RESF_AMI_ACCOUNT_ID \ | jq -r '.|@sh'
--query "${query}" 2>/dev/null \ )
| jq -r '.|@sh'# | tr "'" '"' res=($res)
) if [[ ${#res[@]} -eq 0 ]]; then
res=($res) # Skip empty results
if [[ ${#res[@]} -eq 0 ]]; then return 1 #not found
# Skip empty results fi
continue id=${res[0]//\"}
fi name=${res[@]/$id}
id=${res[0]//\"} # printf "Found public image: %s in %s with name '%s'\n" "$id" "$region" "${name//\"}"
name=${res[@]/$id} found_image_id=$id
printf "Found public image: %s in %s with name '%s'\n" "$id" "$region" "${name//\"}" return 0 # found
ami_ids[$region]=$id
done
} }
declare -A ami_ids declare -A ami_ids
copy copy
change_privacy Public # uses ami_ids #change_privacy Public # uses ami_ids