将入站规则添加到安全组 aws cdk

Add inbound rule to security group aws cdk

我正在使用 AWS Opensearch (Elasticsearch 6.8) 和 AWS lambda。当接收到事件时,lambda 将记录插入 Elasticsearch。以下是 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,
    }
});

现在发生的事情是,在同一个 VPC 下创建了两个安全组,一个用于 ES,另一个用于 lambda。 lambda 无法连接到 Elasticsearch,因为 elasticsearch 安全组没有允许来自 lambda 安全组的流量的入站规则设置。

有没有办法,我可以:

是的,CDK 使用 Connections class, which Domain exposes 使这变得非常容易。这是 Python 中的示例:

my_domain.connections.allow_default_port_from(my_lambda)

就是这样。您不必考虑安全组,它们是抽象的。

在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');

示例取自官方文档页面: https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ec2.SecurityGroup.html#example.

@gshpychka 的回答很准确而且非常简洁。为寻找 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. Using allow_default_port_from would throw an error stating the same.