简体   繁体   中英

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:

  • Define a VPC that only has a single security group and all components inside the VPC can access each other?
  • Or in the CDK itself, I can setup an inbound rule in Elasticsearch SG to allow traffic from lambda SG.

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM