我正在尝试将我的 lambda 放入给定环境的适当 VPC 中。鉴于我在给定环境的单独嵌套堆栈中构建 VPC,如何实现这一目标?
使用 Github 操作和
sam deploy
(如果重要的话)。
Parameters:
environment:
Type: String
devLambdaSubnetIds:
Type: String
Default: !Join [',', subnet-[devVpcA], subnet-[devVpcB]]
prodLambdaSubnetIds:
Type: String
Default: !Join [',', subnet-[prodVpcA], subnet-[prodVpcB]]
...
Resources:
HealthCheckFunction:
Type: AWS::Serverless::Function
Properties:
...
VpcConfig:
Ipv6AllowedForDualStack: false
SecurityGroupIds:
- !Ref genericSecurityGroup
SubnetIds: HERE THIS NEEDS TO BE !Ref devLambdaSubnetIds or !Ref prodLambdaSubnetIds depending on the environment (which is either 'dev' or 'prod')
您可以使用映射并为映射中的每个环境保留配置。
在下面的示例中,需要将子网 ID 更改为真实的子网 ID。
Parameters:
env:
Type: String
Description: Specify an account/environment
AllowedValues:
- dev
- prod
Mappings:
environments:
dev:
sb1: subnet-a
sb2: subnet-b
prod:
sb1: subnet-c
sb2: subnet-d
Resources:
HealthCheckFunction:
Type: AWS::Serverless::Function
Properties:
...
VpcConfig:
Ipv6AllowedForDualStack: false
SecurityGroupIds:
- !Ref genericSecurityGroup
SubnetIds:
- !FindInMap [environments, !Ref env, sb1]
- !FindInMap [environments, !Ref env, sb2]
您也可以将子网 ID 存储在参数存储中,路径如下:
/myapp/dev/subnet1
/myapp/dev/subnet2
/myapp/prod/subnet1
/myapp/prod/subnet2
然后,像这样在模板中引用它们;
- !Sub '{{resolve:ssm:/myapp/${env}/subnet1}}'
- !Sub '{{resolve:ssm:/myapp/${env}/subnet2}}'
您也可以使用条件。
Conditions:
IsDevEnvironment: !Equals [!Ref env, 'dev']
然后将条件添加到资源中。不过,您将需要两种不同的资源,一种用于开发,一种用于产品。
HealthCheckFunction:
Type: AWS::Serverless::Function
Condition: IsDevEnvironment
Properties:
...
VpcConfig:
Ipv6AllowedForDualStack: false
SecurityGroupIds:
- !Ref genericSecurityGroup
SubnetIds:
- subnet1-harcoded
- subnet2-harcoded