You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 prod and test environments will have port 80 open.
  • Conditional 443 Port Rule: We use the !If function to check the CreateProdResources condition:
    • When the condition evaluates to true (i.e., EnvType is prod), the full 443 ingress rule is added.
    • When the condition evaluates to false (i.e., EnvType is test), we return !Ref AWS::NoValue. CloudFormation automatically ignores any list item that resolves to AWS::NoValue, so the 443 rule won't be included in the security group.

This approach keeps your template clean and adheres to CloudFormation's best practices for conditional resource configuration.

内容的提问来源于stack exchange,提问作者Ceripx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 19:27:48