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

facebookShare on Facebook
TwitterTweet

Full text search

Recent Posts

  • Terraform and segregated permissions
  • LVM Compression and Deduplication
  • Edit gpg encrypted file with vim
  • Lelit Elizabeth PL92T Pressure Tuning
  • jq transformation
  • aws (8)
  • coffee (1)
  • headfi (1)
  • linux (6)
  • others (58)
  • security (2)
  • tech (36)
  • wordpress (2)

apache aws awscli azure backup clearlinux cloud coffee docker DOCP ec2 EL8 epyc espresso featured gpg jenkins kernel lelit linux lvm meltdown memory MFA mikrotik php python rdp Redhat RHEL roasting rpm Ryzen site-to-site snapshot spectre tech terraform tuning ubuntu ubuntu upgrade vim vpn wordpress xdotool

©2023 blog.headdesk.me | Powered by SuperbThemes & WordPress