如何在AWS CloudFormation的安全组资源中为SecurityGroupIngress规则添加条件?
Conditional SecurityGroupIngress Rules in AWS CloudFormation
Perfect scenario for using CloudFormation's conditional logic! You can leverage the existing CreateProdResources condition along with the !If intrinsic function to only include the 443 port rule when your EnvType parameter is set to prod.
Here's the adjusted template that implements this logic:
AWSTemplateFormatVersion: 2010-09-09 Parameters: EnvType: Description: Environment type. Default: test Type: String AllowedValues: - prod - test ConstraintDescription: must specify prod or test. Conditions: CreateProdResources: !Equals - Ref: EnvType - prod Resources: WebSecurityGroup: Type: 'AWS::EC2::SecurityGroup' Properties: GroupDescription: Web server GroupName: web VpcId: vpc-abc01234 SecurityGroupIngress: # Always allow port 80, regardless of environment - IpProtocol: tcp FromPort: 80 ToPort: 80 CidrIp: 0.0.0.0/0 # Only allow port 443 if environment is prod - !If - CreateProdResources - IpProtocol: tcp FromPort: 443 ToPort: 443 CidrIp: 0.0.0.0/0 - !Ref AWS::NoValue
Key Details Explained:
- Unconditional 80 Port Rule: The first ingress rule is always included, so both
prodandtestenvironments will have port 80 open. - Conditional 443 Port Rule: We use the
!Iffunction to check theCreateProdResourcescondition:- When the condition evaluates to
true(i.e.,EnvTypeisprod), the full 443 ingress rule is added. - When the condition evaluates to
false(i.e.,EnvTypeistest), we return!Ref AWS::NoValue. CloudFormation automatically ignores any list item that resolves toAWS::NoValue, so the 443 rule won't be included in the security group.
- When the condition evaluates to
This approach keeps your template clean and adheres to CloudFormation's best practices for conditional resource configuration.
内容的提问来源于stack exchange,提问作者Ceripx
相关产品推荐
相关产品推荐

