Skip to content

Instantly share code, notes, and snippets.

@nqbao
Created November 8, 2017 07:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nqbao/62fc03ab46131e86d3d57568670d7048 to your computer and use it in GitHub Desktop.
Save nqbao/62fc03ab46131e86d3d57568670d7048 to your computer and use it in GitHub Desktop.
Copy AMI across accounts
#!/bin/bash
raw=$1
ami_id=$(echo "$raw" | cut -d"," -f1)
image_name=$(echo "$raw" | cut -d"," -f2)
echo "Copying $image_name ($ami_id)"
aws ec2 modify-image-attribute --image-id $ami_id --launch-permission "{\"Add\":[{\"UserId\":\"$TO_ACCOUNT\"}]}" --profile $FROM_PROFILE
aws ec2 copy-image --name "$image_name" --source-image-id $ami_id --source-region $SOURCE_REGION --profile $TO_PROFILE
#!/bin/bash
# fill this with your value
export FROM_PROFILE=xxx
export FROM_ACCOUNT=xxx
export TO_ACCOUNT=xxx
export TO_PROFILE=xxx
export SOURCE_REGION=us-east-1
copy-image-by-grep() {
kw=$1
images=$(aws ec2 describe-images --owner $FROM_ACCOUNT --profile $FROM_PROFILE | jq -r ".Images[] | \"\(.ImageId),\(.Name)\"" | grep $kw)
snapshots=$(echo "$images" | cut -d',' -f1 | xargs -n 5 -I{} bash -c "aws ec2 describe-images --image-ids {} | jq -r \".Images[] | .BlockDeviceMappings[] | .Ebs.SnapshotId \"" | grep -v null)
read -r -d '' share_snapshot << EOM
echo "Sharing {}"
aws ec2 modify-snapshot-attribute --snapshot-id {} --attribute createVolumePermission --operation-type add --user-ids $TO_ACCOUNT --profile $FROM_PROFILE
EOM
echo "$snapshots" | xargs -I {} -n1 bash -c "$share_snapshot"
echo "$images" | xargs -I %% -n1 bash -c "./copy-snapshot.sh %%"
}
copy-image-by-grep $1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment