How to add inbound rules to an existing security group using Lambda function python3

0 votes

I'm trying to update AWS security group with one inbound rules using lambda function Python 3.7. For ex: i would like to add my public IP with 8443 Port in existing security group. I have below code.

import boto3
import hashlib
import json
import copy
import urllib2

# ID of the security group we want to update
SECURITY_GROUP_ID = "sg-XXXX"

# Description of the security rule we want to replace
SECURITY_RULE_DESCR = "My Home IP"

def lambda_handler(event, context):
new_ip_address = list(event.values())[0]
result = update_security_group(new_ip_address)
return result

def update_security_group(new_ip_address):
client = boto3.client('ec2')
response = client.describe_security_groups(GroupIds=[SECURITY_GROUP_ID])
group = response['SecurityGroups'][0]
for permission in group['IpPermissions']:
    new_permission = copy.deepcopy(permission)
    ip_ranges = new_permission['IpRanges']
    for ip_range in ip_ranges:
        if ip_range['Description'] == 'My Home IP':
            ip_range['CidrIp'] = "%s/32" % new_ip_address
    client.revoke_security_group_ingress(GroupId=group['GroupId'], IpPermissions= 
    [permission])
    client.authorize_security_group_ingress(GroupId=group['GroupId'], IpPermissions= 
    [new_permission])
    
    return ""
When i run the lambda function then its not added any port and IP. Can any one please check this code and correct my code?
I would like to add Port with my local public IP to an existing security group. 
Aug 16, 2021 in AWS by Lakshminarayanan

edited Mar 4, 2025 362 views

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP