How to copy AMI permissions
I recently had to copy an AMI across 2 regions and the image was shared with a considerable amount of accounts. Unfortunately, moving the AMI does not also copy its permissions so I set out to see how I could automate copying permissions as well.
Well here is the PowerShell code:
$sourceAMI = "ami-12345678"
$destinationAMI = "ami-87654321"
$destinationRegion = "eu-central-1" # if different from source region
# Get current permissions
$UserIds = Get-EC2ImageAttribute -ImageId $sourceAMI -Attribute LaunchPermission | Select-Object -ExpandProperty Launchpermissions
# Copy launch permissions to new image
foreach($id in $UserIds)
{
Edit-EC2ImageAttribute -ImageId $destinationAMI -Attribute launchPermission -OperationType add -UserId $id.UserId -Region $destinationRegion
}
To do the same in the AWS CLI run:
aws ec2 describe-image-attribute --image-id ami-12345678 --attribute launchPermission --query "LaunchPermissions[]" --output text > UserIds
FOR /f %i IN (UserIds) DO aws ec2 modify-image-attribute --image-id ami-87654321 --launch-permission "{\"Add\": [{\"UserId\":\"%i\"}]}"
Note
I have only tested the CLI commands on Windows