Below is an example Bash script that uses the AWS CLI to retrieve all your Amazon ECR repositories and then sets the image tag mutability of each repository to MUTABLE. Before running the script, ensure you have the AWS CLI installed and configured with appropriate permissions.
#!/bin/bash
# This script fetches all Amazon ECR repositories and sets their image tag mutability to MUTABLE.
# Fetch all repository names from ECR.
repositories=$(aws ecr describe-repositories --query "repositories[].repositoryName" --output text)
# Check if any repositories were found.
if [ -z "$repositories" ]; then
echo "No ECR repositories found."
exit 1
fi
# Loop over each repository and update its image tag mutability.
for repo in $repositories; do
echo "Setting image tag mutability to MUTABLE for repository: $repo"
aws ecr put-image-tag-mutability --repository-name "$repo" --image-tag-mutability MUTABLE | tee
if [ $? -eq 0 ]; then
echo "Successfully updated $repo"
else
echo "Failed to update $repo"
fi
done
Explanation
- Fetching repositories:
The script starts by runningaws ecr describe-repositories
to retrieve a list of repository names using a JMESPath query. The--output text
option formats the output as plain text. - Check for no repositories:
It checks if the$repositories
variable is empty. If no repositories are found, it exits with a message. - Loop and update mutability:
For each repository name, the script callsaws ecr put-image-tag-mutability
setting the--image-tag-mutability
flag toMUTABLE
.
A success or failure message is printed based on the exit status of each command. - Permissions and AWS CLI configuration:
Make sure your AWS CLI is correctly configured (for example, viaaws configure
) with credentials that have permissions to performdescribe-repositories
andput-image-tag-mutability
actions in ECR.
This script automates the process of ensuring all repositories are mutable when it comes to image tags, making future updates or tagging changes possible.