Home > database >  Add a list of IP as Source IP in Security Group
Add a list of IP as Source IP in Security Group

Time:12-07

I have a list of IP addresses. I want to allow tcp/22 traffic from them and block any other IP address. The list is long and contains about 50-60 IP addresses. How can I add this to a Security Group without manually adding them one by one.

Thankyou!

Solution:

I found a way using aws cli

For allowing SSH to a range of cidrs

bash# for ip in {csv_list_of_cidrs}
> do
> aws ec2 authorize-security-group-ingress --group-id <sg_ig_here> --protocol tcp --port 22 --cidr $ip
> done

eg:

for ip in {1.1.1.1/8,2.2.2.2/16,3.2.3.12/29}
do
aws ec2 authorize-security-group-ingress --group-id sg-xxxxxxxxx --protocol tcp --port 22 --cidr $ip
done

For solution usingboto3 refer to the answer below

CodePudding user response:

This is a boto3 script that you could use:

    ec2_client = boto3.client('ec2')
    ec2_client.authorize_security_group_ingress(
        GroupId=group_id,
        IpPermissions=[
            {
                'IpProtocol': 'tcp',
                'FromPort': 22,
                'ToPort': 22,
                'IpRanges': [ip_list_here]
            }
        ])
  • Related