[英]AWS CDK - SecurityGroup creation Typescript
我正在尝试使用 typescript 将以下 CloudFormation 资源迁移到 CDK:
ALBSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
VpcId: !Ref VPCId
GroupDescription: !Sub "${Application}-${Environment}-alb-sg"
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 443
ToPort: 443
CidrIp: !Ref SecurityGroupIngressCidr
我试过这个(我不知道如何创建必要的属性):
const albSecurityGroup = new SecurityGroup(this, "ALBSecurityGroup", {
vpc: Vpc.fromLookup(this, id, {
vpcId: props.vpcId.stringValue
}),
description: appEnv + "-alb-sg"
})
并像这样使用 Cfn 构造函数(我不知道如何使用 CfnSecurityGroupIngress 加入 CfnSecurityGroup):
const x = new CfnSecurityGroupIngress(this, id, {
ipProtocol: "tcp",
fromPort: 443,
toPort: 443,
cidrIp: props.securityGroupIngressCidr
});
const albSecurityGroupCfn = new CfnSecurityGroup(this, id, {
vpcId: props.vpcId.stringValue,
groupDescription: appEnv + "-alb-sg"
});
我感谢您的帮助。
通过使用CfnSecurityGroup
,您的答案看起来更清晰,但只是为了完整性,并展示使用更高阶构造SecurityGroup
实现相同目标的方法如下:
import { SecurityGroup, Peer, Port, Vpc } from '@aws-cdk/aws-ec2';
....
const vpc = Vpc.fromLookup(this, id, {
vpcId: props.vpcId.stringValue
});
const albSecurityGroup = new SecurityGroup(this, 'MyALBSG', {
vpc,
description: appEnv + "-alb-sg",
allowAllOutbound: true
});
albSecurityGroup.addIngressRule(
Peer.ipv4(props.securityGroupIngressCidr),
Port.tcp(443),
"Allow HTTPS traffic from CIDR IPs"
);
....
我强烈建议您阅读您计划在 CDK 中使用的任何服务模块的概述部分。 这是aws-ec2
的一个,它展示了如何编写SecurityGroup
。
您不妨直接使用loadBalancer.connections.allowFrom()
而不是为您的 ALB 显式创建安全组。 假设您的 ALB 构造被命名为loadBalancer
,这将类似于:
loadBalancer.connections.allowFrom(
Peer.ipv4(props.securityGroupIngressCidr),
Port.tcp(443),
'Allow inbound HTTPS from CIDR IPs'
);
今天我意识到这是一个简单的解决方案。
const albSecurityGroupCfn = new CfnSecurityGroup(this, id, {
vpcId: props.vpcId.stringValue,
groupDescription: appEnv + "-alb-sg",
securityGroupIngress: [
new CfnSecurityGroupIngress(this, id, {
ipProtocol: "tcp",
fromPort: 443,
toPort: 443,
cidrIp: props.securityGroupIngressCidr
})
]
});
谢谢!
更新:(dmahapatro)
使用上述方法,您会收到一个编译时错误,表明您需要合适的类型。 这是对上述解决方案的一个小调整:
const albSecurityGroupCfn = new CfnSecurityGroup(this, id, {
vpcId: props.vpcId.stringValue,
groupDescription: appEnv + "-alb-sg",
securityGroupIngress: [{
ipProtocol: "tcp",
fromPort: 443,
toPort: 443,
cidrIp: props.securityGroupIngressCidr
}]
});
securityGroupIngress
需要以下类型:
Type: Array<CfnSecurityGroup.IngressProperty | cdk.IResolvable> | cdk.IResolvable
当您提供CfnSecurityGroupIngress
数组时,它不会解析为任何这些类型。 处理它的更好方法是使用对象数组,默认情况下会强制转换为Array<CfnSecurityGroup.IngressProperty>
。 最新的答案表明您不需要为securityGroupIngress
实例化CfnSecurityGroupIngress
。
附带说明一下,如果 VS Code 用作 CDK 的 IDE,它会预先捕获这些编译时错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.