Menu
blog.headdesk.me
blog.headdesk.me

Add security group to all ec2 instances

Posted on 2018/09/282018/09/28

If you ever need to take over management of an AWS farm, it’s very likely you will need to attach SG to all instances. Be that for monitoring or access. Here is a bash script to add 1 SG to all instances.

You will need to first setup a profile on awscli. Then run the script with the profile name as first argument, and the SG id as the second.

Note: The script will not work on instances with multiple NICs

#!/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

export AWSPROFILE=$1
export ADDSG=$2

doit() {
    echo "Checking $1..."
    SG=$(aws --profile=$AWSPROFILE ec2 describe-instances --instance-ids $1 --output json | jq ".[][].Instances[].SecurityGroups[].GroupId" -r | xargs)
    echo "Existing SGs: $SG"
    if [[ $SG == *$ADDSG* ]]; then
        echo "$ADDSG already associated, do nothing"
    else
      aws --profile=$AWSPROFILE ec2 modify-instance-attribute --dry-run --instance-id $1 --groups $SG $ADDSG
      echo "New SGs: $(aws --profile=$AWSPROFILE ec2 describe-instances --instance-ids $1 --output json | jq ".[][].Instances[].SecurityGroups[].GroupId" -r | xargs)"
    fi
}

export -f doit

aws --profile=$AWSPROFILE ec2 describe-instances --output json \
| jq ".[][].Instances[].InstanceId" -r | parallel -j10 doit

Loading

Full text search

Recent Posts

  • Generate secure password
  • AWS Compute Savings Plans
  • AWS Zonal Shift
  • Coffee break…
  • Prevent private key from being committed to git
  • aws (14)
  • coffee (2)
  • headfi (1)
  • linux (9)
  • others (61)
  • security (2)
  • tech (41)
  • terraform (3)
  • wordpress (2)

Loading

apache aws awscli azure backup boot cloud coffee docker ec2 EL8 ElasticBeanstalk espresso featured git kernel lelit linux lvm meltdown MFA nat gateway php power proliant python rdp Redhat RHEL rpm Ryzen scp security smartarray smart switch snapshot spectre tech terraform ubuntu ubuntu upgrade vpn windows wordpress workspace

©2026 blog.headdesk.me | Powered by SuperbThemes