Adding custom cidr to ingress security group using Lambda without default vpc

0

Hello all! I have been searching the internet for this but I didn't exactly find a solution.

Basically I am trying to add custom cidr ips to a security group via lambda function. I have given all the appropriate permissions (as far as i can tell) . I even tried attaching the vpc (which is non-default) to the lambda function to access the security group but the error was the same so i removed it from lambda function.

But I am getting "An error occurred (VPCIdNotSpecified) when calling the AuthorizeSecurityGroupIngress operation: No default VPC for this user"

Below is the Policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ec2:RevokeSecurityGroupIngress",
                "ec2:CreateNetworkInterface",
                "ec2:AuthorizeSecurityGroupIngress",
                "ec2:DescribeNetworkInterfaces",
                "ec2:DescribeVpcs",
                "ec2:DeleteNetworkInterface",
                "ec2:DescribeSubnets",
                "ec2:DescribeSecurityGroups"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:CreateLogGroup"
            ],
            "Resource":  "arn:aws:logs:us-west-2:xxxx:log-group:xxx:log-stream:*"
        }
    ]
}

Lambda function:

#!/usr/bin/python3.9
import boto3
ec2 = boto3.client('ec2')
def lambda_handler(event, context):
    response = ec2.authorize_security_group_ingress(
    GroupId='sg-xxxxxxx'
    IpPermissions=[
        { 
            'FromPort': 443,
            'IpProtocol': 'tcp',
            'IpRanges': [
                {
                    'CidrIp': '1x.1x.x.1x/32',
                    'Description': 'adding test cidr using lambda'
                },
            ],
            'ToPort': 443
        }
        ],
        DryRun=True
    )
    return response

Could someone point me to the right direction? VPC is non-defaul. All I need is to add ingress rule to an existing security group within a non-default vpc.

The error log:

Test Event Name
snstest

Response
{
  "errorMessage": "An error occurred (VPCIdNotSpecified) when calling the AuthorizeSecurityGroupIngress operation: No default VPC for this user",
  "errorType": "ClientError",
  "requestId": "7de9dce1-f2f9-4609-897e-b75ef751544e",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 21, in lambda_handler\n    response = ec2.authorize_security_group_ingress(\n",
    "  File \"/var/runtime/botocore/client.py\", line 391, in _api_call\n    return self._make_api_call(operation_name, kwargs)\n",
    "  File \"/var/runtime/botocore/client.py\", line 719, in _make_api_call\n    raise error_class(parsed_response, operation_name)\n"
  ]
}

Function Logs
START RequestId: 7de9dce1-f2f9-4609-897e-b75ef751544e Version: $LATEST
[ERROR] ClientError: An error occurred (VPCIdNotSpecified) when calling the AuthorizeSecurityGroupIngress operation: No default VPC for this user
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 21, in lambda_handler
    response = ec2.authorize_security_group_ingress(
  File "/var/runtime/botocore/client.py", line 391, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/var/runtime/botocore/client.py", line 719, in _make_api_call
    raise error_class(parsed_response, operation_name)END RequestId: 7de9dce1-f2f9-4609-897e-b75ef751544e
REPORT RequestId: 7de9dce1-f2f9-4609-897e-b75ef751544e	Duration: 213.81 ms	Billed Duration: 214 ms	Memory Size: 128 MB	Max Memory Used: 77 MB

Request ID
7de9dce1-f2f9-4609-897e-b75ef751544e
asked 2 years ago1007 views
3 Answers
0
Accepted Answer

It was syntax error, plus I added VPC to the configuration which was not required for this purpose. For anyone having the same issue (only want to update security group with the cidr): below is the correct function and permissions (function isnt complete as u may want to delete old rules too):

Lambda function:

#!/usr/bin/python3.9
import boto3
ec2 = boto3.client('ec2')
def lambda_handler(event, context):
    response = ec2.authorize_security_group_ingress(
        DryRun=False,
        GroupId='sg-0123456789',
        IpPermissions=[
            { 
                'FromPort': 443,
                'IpProtocol': 'tcp',
                'IpRanges': [
                    {
                        'CidrIp': '1x.2x.3x.4x/32',
                        'Description': 'Security group updated via lambda'
                    }
                ],
                'ToPort': 443
            }
        ]
    )
    return response

IAM Policy on lambda execution role:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ec2:AuthorizeSecurityGroupIngress",
                "ec2:ModifySecurityGroupRules",
                "ec2:UpdateSecurityGroupRuleDescriptionsIngress"
            ],
            "Resource": "arn or all"
        }
    ]
}
answered 2 years ago
profile picture
EXPERT
reviewed 15 days ago
0

That code is fine. The error message is giving you the information that you need: There is no default VPC in the region that you're using. Yes, you're probably not using a default VPC but there are a few API calls that rely on having one even if you're not using it.

Try recreating your default VPC and see how you go: https://aws.amazon.com/premiumsupport/knowledge-center/deleted-default-vpc/

profile pictureAWS
EXPERT
answered 2 years ago
  • Wow Brettski I had no idea there are API calls relying on the default VPC. We delete default VPCs as a standard new account preparation process! Is that actually bad practice? Thanks.

  • "Bad practice" is probably going a bit far but as you've experienced there are a few sharp edges where not having a default VPC (and default subnets in that VPC) can be an issue. The VPC doesn't have to have an Internet Gateway (as it is created by default) so even if someone deploys something to it connectivity will be limited. And you could create a Config Rule that detects when things are deploy into the default VPC.

  • Thank you Brettski! Echoing skinsman, I didn't know there are API call relying on the default VPC. Is there no way to specify which VPC to use? Issue is we delete the default VPC to keep network private. I am not even sure if creating default VPC would pass the security team. If there is no way of doing it via lambda without the default VPC, will restricting the default VPC to not have anything public be an issue for Lambda to update the security groups? Also, the security groups will not be under default vpc. I appreciate your help

  • Just to update: I manage to get it working. It was indentation between response and (. I guess whilst trying and adding vpc to lambda configuration, the error was misleading. Thanks for your help. Default VPC is not needed in this case

  • I gotta admit - I didn't copy/paste your code; I wrote something fresh which worked; but also didn't test it in an account/region with no default VPC. Glad to see that it isn't required in this particular situation; bear in mind you may trip across other places where it is required.

0

Hello

I copied your Script and tested it works pretty good without DryRun flag , I think you need to check permissions of Lambda,

Policy Used for the Lambda Function:

  • Basic Lambda Execution Policy and
  • Custom Policy below
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ec2:AuthorizeSecurityGroupIngress",
                "ec2:ModifySecurityGroupRules",
                "ec2:UpdateSecurityGroupRuleDescriptionsIngress"
            ],
            "Resource": "*"
        }
    ]
}

Please check the Role and attach the permission, Thank You

profile picture
GK
answered 2 years ago
  • Thank you GK. I tried it but i am getting the same error. Could it be because we have a non-default VPC? were you able to test it with the default VPC or custom VPC?

  • I have tested with Custom Vpc however the VPC can be anything, Can you please share the full logs ?

  • I have added the error log to the questioons as it was more than 600 char.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions