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

  • Dumping AWS Organization tree
  • Free is the most expensive
  • Terraform conditional resource and blocks
  • Upgrade Ubuntu 16.04 to latest release
  • Inspect and control network traffic on AWS
  • aws (8)
  • coffee (1)
  • headfi (1)
  • linux (7)
  • others (55)
  • security (2)
  • tech (36)
  • wordpress (2)

apache aws awscli azure backup cloud coffee coreos distributed filesystem docker ec2 EL8 elasticcache etckeeper featured heartbleed kernel linux mail meltdown mysql php pine python rdp rds Redhat Red Hat RHEL RHEL7 rpm Ryzen snapshot spectre SSL systemd tech terraform ubuntu ubuntu upgrade vector vpn wordpress xtreemfs yum

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