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: 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 \
@ -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
expected_name="Copy of ${source_ami} from ${source_region}"
# ami-id "name" # ami-id "name"
local query="$(printf 'Images[?Name==`%s`]|[?Public==`true`].[ImageId,Name][]' "${expected_name}")" local query="$(printf 'Images[?Name==`%s`]|[?Public==`true`].[ImageId,Name][]' "${SOURCE_AMI_NAME}")"
mapfile -t res < <( mapfile -t res < <(
aws --profile resf-ami ec2 describe-images --region $region --owners $RESF_AMI_ACCOUNT_ID \ aws --profile resf-ami ec2 describe-images --region $region --owners $RESF_AMI_ACCOUNT_ID \
--query "${query}" 2>/dev/null \ --query "${query}" 2>/dev/null \
| jq -r '.|@sh'# | tr "'" '"' | jq -r '.|@sh'
) )
res=($res) res=($res)
if [[ ${#res[@]} -eq 0 ]]; then if [[ ${#res[@]} -eq 0 ]]; then
# Skip empty results # Skip empty results
continue return 1 #not found
fi fi
id=${res[0]//\"} id=${res[0]//\"}
name=${res[@]/$id} name=${res[@]/$id}
printf "Found public image: %s in %s with name '%s'\n" "$id" "$region" "${name//\"}" # printf "Found public image: %s in %s with name '%s'\n" "$id" "$region" "${name//\"}"
ami_ids[$region]=$id found_image_id=$id
done return 0 # found
} }
declare -A ami_ids declare -A ami_ids
copy copy
change_privacy Public # uses ami_ids #change_privacy Public # uses ami_ids