iam.Carrot
iam.Carrot

Reputation: 5286

Add inbound rule to security group aws cdk

I am working with AWS Opensearch (Elasticsearch 6.8) and an AWS lambda. The lambda inserts records into Elasticsearch when an event is received. Below is how the elasticsearch is defined:

this.loggingES = new opensearch.Domain(this, 'LogsES', {
    version: opensearch.EngineVersion.ELASTICSEARCH_6_8,
    domainName: "app-logs-es",
    vpc: this.loggingVPC,
    zoneAwareness: {
        availabilityZoneCount: 3,
    },
    enforceHttps: true,
    nodeToNodeEncryption: true,
    encryptionAtRest: {
        enabled: true
    },
    capacity: {
        masterNodes: 3,
        dataNodes: 3,
    }
});

Now what happens is, two security groups get created under the same VPC, one for the ES and another for the lambda. The lambda is unable to connect to the Elasticsearch because the elasticsearch security group doesn't have an inbound rule setup that allows traffic from lambda security group.

Is there a way, I can either:

Upvotes: 0

Views: 4387

Answers (3)

iam.Carrot
iam.Carrot

Reputation: 5286

The answer by @gshpychka is spot on and very concise. Adding the code below for anyone looking for a TypeScript variant.

import {Port} from "@aws-cdk/aws-ec2"

// ... other imports and code

MyOpenSearchDomain.connections.allowFrom(myLambda, Port.allTraffic(), "Allows Lambda to connect to Opensearch.")

To allow connections from Lambda we need to specify Port.allTraffic() since a Lambda does not have a default port. Using allow_default_port_from would throw an error stating the same.

Upvotes: 1

Rshad Zhran
Rshad Zhran

Reputation: 636

In CDK it's possible to add ingress rule, as follows:

const mySecurityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', {
   vpc,
   description: 'Allow ssh access to ec2 instances',
   allowAllOutbound: true   // Can be set to false
});

mySecurityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(22), 
'allow ssh access from the world');

The example is taken from the official documentation page: https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.SecurityGroup.html#example.

Upvotes: 1

gshpychka
gshpychka

Reputation: 11588

Yup, CDK makes this very easy with the Connections class, which Domain exposes. Here's an example in Python:

my_domain.connections.allow_default_port_from(my_lambda)

And that's it. You don't have to think about security groups, they're abstracted away.

Upvotes: 5

Related Questions