0

I'm trying to write one lambda that automatically revokes ingress rules for '0.0.0.0/0' across all our AWS accounts. For the account the lambda exists in, it's pretty simple. The issue arises when I try to revoke ingress on a security group from another account. No combination of GroupId, SourceSecurityGroupOwnerId, Filter[{'Name': 'owner-id', 'Values': 'account#'}] and otherwise seems to work, I'm constantly hit with "That group doesn't exist". It's like the command doesn't look at the account I tell it to. Has anyone had experience with this?

Here's what I have so far (please ignore commented out lines, I'm still experimenting):

import json
import boto3

ec2 = boto3.client('ec2')
ec2_resources = boto3.resource('ec2')

def lambda_handler(event, context):
    ipPermissions = event['detail']['requestParameters']['ipPermissions']['items'][0]
    fromPort = ipPermissions['fromPort']
    ipProtocol = ipPermissions['ipProtocol']
    toPort = ipPermissions['toPort']
    IpPermissions = [{'FromPort': fromPort, 'IpProtocol': ipProtocol, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'Ipv6Ranges': [{'CidrIpv6': '::/0'}], 'PrefixListIds': [], 'ToPort': toPort, 'UserIdGroupPairs': []}]
    account = event['detail']['userIdentity']['accountId']
    groupId = event['detail']['requestParameters']['groupId']
    print(account)
    #response = ec2.revoke_security_group_ingress(GroupId=groupId,SourceSecurityGroupOwnerId=account)
    response = ec2.revoke_security_group_ingress(GroupId=groupId,IpPermissions=IpPermissions,SourceSecurityGroupOwnerId=account)
    #response = ec2.revoke_security_group_ingress(GroupId=groupId,CidrIp='0.0.0.0/0',SourceSecurityGroupOwnerId=security_group.owner_id)
    #print(response)
    print(json.dumps(event))
    return {
        'statusCode': 200,
        'body': json.dumps('Ingress revoked')
    }
2
  • 1
    Can you give an example of the lambda? Commented Mar 31, 2020 at 15:26
  • Added to original post @a-abramov Commented Mar 31, 2020 at 16:01

1 Answer 1

1

Figured it out, you need to access the account using creds:

app_dev=sts_client.assume_role(RoleArn="arn:aws:iam::123456789012:role/SecurityGroupMonitor", RoleSessionName="AssumeRole")
ACCESS_KEY = app_dev['Credentials']['AccessKeyId']
SECRET_KEY = app_dev['Credentials']['SecretAccessKey']
SESSION_TOKEN = app_dev['Credentials']['SessionToken']
ec2_client = boto3.client('ec2', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, aws_session_token=SESSION_TOKEN)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.