[英]Add inbound rule to security group aws cdk
I am working with AWS Opensearch (Elasticsearch 6.8)
and an AWS lambda.我正在使用
AWS Opensearch (Elasticsearch 6.8)
和 AWS lambda。 The lambda inserts records into Elasticsearch when an event is received. lambda 在收到事件时将记录插入 Elasticsearch。 Below is how the elasticsearch is defined:
以下是 elasticsearch 的定义方式:
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.现在发生的情况是,在同一个 VPC 下创建了两个安全组,一个用于 ES,另一个用于 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.
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.
Yup, CDK makes this very easy with the Connections
class, which Domain
exposes .是的,CDK 使用
Domain
公开的Connections
class 使这变得非常容易。 Here's an example in Python:这是 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:在 CDK 中可以添加入口规则,如下所示:
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 .示例取自官方文档页面: 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. @gshpychka 的答案很准确而且非常简洁。 Adding the code below for anyone looking for a
TypeScript
variant.为寻找
TypeScript
变体的任何人添加以下代码。
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.为了允许来自 Lambda 的连接,我们需要指定
Port.allTraffic()
因为 Lambda 没有默认端口。 Usingallow_default_port_from
would throw an error stating the same.使用
allow_default_port_from
会抛出一个错误,说明相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.