Advertisement

Showing posts with label Lambda. Show all posts
Showing posts with label Lambda. Show all posts

Thursday, December 5, 2019

AWS : Lambda: Remove IP to Security Group Using Boto3

In this blog I discuss on how to remove an IP from Security Group using Boto3



import boto3
ec2 = boto3.resource('ec2')
s_group = ec2.SecurityGroup('sg-<ID>')
response = s_group.revoke_ingress(IpProtocol="tcp", CidrIp=strIP, FromPort=22, ToPort=22)
print (response)

Here strIP : IP Range - Example 10.24.25.0/24
From Port and To Port are port Ranges 


With the above you can revoke an IP address rule

AWS : Lambda: Add IP to Security Group Using Boto3

In this blog I am going to show example on adding an IP address to AWS security group using Boto3.

The way is simple, just create your own Lambda and add the below Code. 
You can have trigger of SQS and put an example IP in the Body . 


import json
import boto3

ec2 = boto3.resource('ec2')
s_group = ec2.SecurityGroup('sg-0308cd0e895d42ac2')
# This is your Security group unique ID


def lambda_handler(event, context):
    failed = False;
    
    try:
      print ("The value IS " + s_group.group_id)
      for record in event['Records']:
        ip = record["body"]
        print (str(ip))
        response = s_group.authorize_ingress(IpProtocol="tcp", CidrIp=str(ip),FromPort=80,ToPort=80)
    except Exception:
      logger.exception("Failed to Add IP")
      # Add your failure function 
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }


Sample Event to Use

{
  "Records": [
    {
      "messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78",
      "receiptHandle": "MessageReceiptHandle",
      "body": "10.2.3.0/32",
      "attributes": {
        "ApproximateReceiveCount": "1",
        "SentTimestamp": "1523232000000",
        "SenderId": "123456789012",
        "ApproximateFirstReceiveTimestamp": "1523232000001"
      },
      "messageAttributes": {},
      "md5OfBody": "7b270e59b47ff90a553787216d55d91d",
      "eventSource": "aws:sqs",
      "eventSourceARN": "arn:aws:sqs:us-east-1:123456789012:MyQueue",
      "awsRegion": "us-east-1"
    }
  ]
}

Reference: https://docs.aws.amazon.com/code-samples/latest/catalog/python-ec2-create_security_group.py.html