Advertisement

Tuesday, January 7, 2020

AWS : Lambda: Add IP to Security Group Using Boto3 - Complete Code

IN this blog I am going to show how to add an IP using Lambda.
You can create a sample-SQS trigger event with an IP address in body to create an SQS event emulation for testing..

Now, 
  • lamda_handler is the default handler for lambda
  • It checks if the IP is not already part of the rule
  • it then calls updateIP and refreshes the timestamp if yes or adds new with new timestamp if no
  • the revoke is to temporarily revoke and add the IP.

import boto3
from datetime import datetime

ec2 = boto3.resource('ec2')
s_group = ec2.SecurityGroup('sg-85d42ac2')
dt = datetime.now()
date_format = "%m-%d-%Y %H:%M"str_dt = dt.strftime(date_format)
ssh_port = 22code = 200max_minutes = 5

def lambda_handler(event, context):
    for record in event['Records']:
        ip = record["body"]
        if (str(ip) == 'sweep'):
            sweepIP()
        else:
            verifyAddIP(str(ip))

def verifyAddIP(strIP):
    m_strIP = strIP + '/32'
    ip_permission = s_group.ip_permissions[0]
    ip_range = ip_permission['IpRanges']

    for cidr in ip_range:
        if (cidr['CidrIp'] == m_strIP):
            updateRule(strIP + '/32', True)
        else:
            updateRule(strIP + '/32', False)


def updateRule(strIP, update_p):
    if update_p:
        response = s_group.revoke_ingress(IpProtocol="tcp", CidrIp=strIP, FromPort=ssh_port, ToPort=ssh_port)
        response = s_group.authorize_ingress(IpPermissions=[
            {'IpProtocol': 'tcp',
             'FromPort': ssh_port,
             'ToPort': ssh_port,
             'IpRanges': [{'CidrIp': strIP, 'Description': str_dt}]
             }
        ]
        )
        print ('Update IP Address Time in Ingress Rule - ' + strIP)
    else:
        response = s_group.authorize_ingress(IpPermissions=[
            {'IpProtocol': 'tcp',
             'FromPort': ssh_port,
             'ToPort': ssh_port,
             'IpRanges': [{'CidrIp': strIP, 'Description': str_dt}]
             }
        ]
        )
        print ('Added IP Address to Ingress Rule - ' + strIP)

No comments:
Write comments