Add Rule to Security Group From File In S3 Bucket
- Create a bucket with a unique name here we assume ‘s3nvbucket’ is name of bucket
- Create lambda function as follows
- Go to lambda from services menu of AWS console
- Click on create function button from lambda dashboard
- Choose Author from scratch option while creating function
- Give function name & select Runtime language as python 3.7
- Assign S3 permission to read file from s3 as soon as uploaded
-
-
-
- Select Create a role with AWS policy template
- Define Role name
- Choose Policy Template
-
-
-
- Assign EC2 Write permission (AmazonEc2FullAccess) to add inbound rule in Security Group
- Now click on button Create function
- Next you will have to configure the lambda function
- Click on button Add trigger
- Select a trigger (resource type) from list as s3
- Select Bucket. (‘s3nvbucket’)
- Select Event Type as PUT
- Type ‘IP’ in prefix
- Type ‘.TXT’ in suffix
- Click on ADD button
- Copy the function Code from here
import boto3
def sg_assign(ip):
ipt=ip
ec2 = boto3.resource(‘ec2′,’us-east-1’)
security_group = ec2.SecurityGroup(‘sg-019aecbdc639e126e’)
response = security_group.authorize_ingress(GroupId=’sg-019aecbdc639e126e’,IpPermissions=[{‘IpProtocol’: ‘tcp’,’FromPort’: 22,’ToPort’: 22,’IpRanges’:[{‘CidrIp’:ipt,’Description’: ‘added SSH inbound role from lambda’}]}])
print(response)
returndef lambda_handler(event, context):
# TODO implement
s3 = boto3.client(‘s3′)
obj = s3.get_object(Bucket=’s3nvbucket’,Key=’ip.txt’)
body = obj[‘Body’].read()
temp1=body.decode(‘utf-8’)
temp=temp1+”/32″
sg_assign(temp)
return
-
-
- Do some changes in code as required
- Type Proper region as per your resources location (at line 4)
- Type proper security group id : (at line 5 and 6)
- Type proper bucket name to read ip address (at line 13)
- Give proper indent as below
- Do some changes in code as required
-
- Now click on SAVE to save the function code and changes done in configuration
- Create a file with name ip.txt which contains IP address. (see following image)
- Upload ip.txt to created bucket (ie. s3nvbucket)
- Now your lambda function is executed and inbound rule is added under defined security group see out put as follows
- Thank you…