code-dumps/aws/add-sg.sh

23 lines
1006 B
Bash
Executable File

#!/usr/bin/env bash
#
# script to add 1 SG to all instances.
# this scripts takes 2 arguments, first is the aws profile name, second is the SG to add.
# e.g. ./add-sg.sh acme sg-1234567
#
# you will need awscli for this script to work, and an aws profile
# associated with an IAM user with the AmazonEC2FullAccess policy
AWSPROFILE=$1
aws --profile=$AWSPROFILE ec2 describe-instances --output json \
| jq ".[][].Instances[].InstanceId" -r | while read l; do
SG=$(aws --profile=$AWSPROFILE ec2 describe-instances --instance-ids $l --output json | jq ".[][].Instances[].SecurityGroups[].GroupId" -r | xargs)
echo "Existing SGs on $l: $SG"
if [[ $SG == *$2* ]]; then
echo "$2 already associated, do nothing"
continue
fi
aws --profile=$AWSPROFILE ec2 modify-instance-attribute --instance-id $l --groups $SG $2
echo "New SGs on $l: $(aws --profile=$AWSPROFILE ec2 describe-instances --instance-ids $l --output json | jq ".[][].Instances[].SecurityGroups[].GroupId" -r | xargs)"
done