在AWS CDK中使用Network Load Balancer(NLB)时,可以通过设置安全组(Security Group)来限制访问NLB的源IP地址。下面是一个使用AWS CDK创建NLB和安全组的示例代码:
from aws_cdk import core
from aws_cdk import aws_ec2 as ec2
from aws_cdk import aws_elasticloadbalancingv2 as elbv2
class NLBWithSecurityGroupStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
# 创建一个VPC
vpc = ec2.Vpc(self, 'MyVpc', max_azs=2)
# 创建安全组
security_group = ec2.SecurityGroup(
self,
'MySecurityGroup',
vpc=vpc,
allow_all_outbound=True
)
# 允许所有入站流量
security_group.add_ingress_rule(
peer=ec2.Peer.any_ipv4(),
connection=ec2.Port.all_tcp(),
description='Allow all inbound traffic'
)
# 创建NLB
nlb = elbv2.NetworkLoadBalancer(
self,
'MyNLB',
vpc=vpc,
internet_facing=True,
security_group=security_group
)
app = core.App()
NLBWithSecurityGroupStack(app, 'MyStack')
app.synth()
在示例代码中,首先创建了一个VPC和一个安全组。安全组允许所有出站流量,并添加了一个允许所有入站流量的规则。
然后,创建了一个NLB,并将安全组分配给NLB的security_group
属性。这样,NLB只会接受来自安全组规则中指定的源IP地址的流量。
请注意,示例代码中的NLB是公网可访问的,因此我们将internet_facing
属性设置为True
。如果你想创建一个私有的NLB,可以将internet_facing
属性设置为False
,并使用其他方法来限制访问。