Skip to content
v2.274.0

SecurityGroup L2 construct ​

Creates an Amazon EC2 security group within a VPC.

Security Groups act like a firewall with a set of rules, and are associated with any AWS resource that has or creates Elastic Network Interfaces (ENIs). A typical example of a resource that has a security group is an Instance (or Auto Scaling Group of instances)

If you are defining new infrastructure in CDK, there is a good chance you won't have to interact with this class at all. Like IAM Roles, Security Groups need to exist to control access between AWS resources, but CDK will automatically generate and populate them with least-privilege permissions for you so you can concentrate on your business logic.

All Constructs that require Security Groups will create one for you if you don't specify one at construction. After construction, you can selectively allow connections to and between constructs via--for example-- the instance.connections object. Think of it as "allowing connections to your instance", rather than "adding ingress rules a security group". See the Allowing Connections section in the library documentation for examples.

Direct manipulation of the Security Group through addIngressRule and addEgressRule is possible, but mutation through the .connections object is recommended. If you peer two constructs with security groups this way, appropriate rules will be created in both.

If you have an existing security group you want to use in your CDK application, you would import it like this:

ts
const securityGroup = ec2.SecurityGroup.fromSecurityGroupId(this, 'SG', 'sg-12345', {
  mutable: false
});

Example ​

ts
const vpc = ec2.Vpc.fromLookup(this, 'ExistingVPC', { vpcId: 'vpc-12345678' });
const bucket = new s3.Bucket(this, 'MyBucket');

const securityGroup = new ec2.SecurityGroup(this, 'CustomSG', {
    vpc: vpc,
    description: 'Allow HTTPS outbound access',
    allowAllOutbound: false,
});

securityGroup.addEgressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(443), 'Allow HTTPS traffic');

new s3deploy.BucketDeployment(this, 'DeployWithSecurityGroup', {
    destinationBucket: bucket,
    vpc: vpc,
    securityGroups: [securityGroup],
    sources: [s3deploy.Source.asset('./website')],
});
python
vpc = ec2.Vpc.from_lookup(self, "ExistingVPC", vpc_id="vpc-12345678")
bucket = s3.Bucket(self, "MyBucket")

security_group = ec2.SecurityGroup(self, "CustomSG",
    vpc=vpc,
    description="Allow HTTPS outbound access",
    allow_all_outbound=False
)

security_group.add_egress_rule(ec2.Peer.any_ipv4(), ec2.Port.tcp(443), "Allow HTTPS traffic")

s3deploy.BucketDeployment(self, "DeployWithSecurityGroup",
    destination_bucket=bucket,
    vpc=vpc,
    security_groups=[security_group],
    sources=[s3deploy.Source.asset("./website")]
)
java
IVpc vpc = Vpc.fromLookup(this, "ExistingVPC", VpcLookupOptions.builder().vpcId("vpc-12345678").build());
Bucket bucket = new Bucket(this, "MyBucket");

SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "CustomSG")
        .vpc(vpc)
        .description("Allow HTTPS outbound access")
        .allowAllOutbound(false)
        .build();

securityGroup.addEgressRule(Peer.anyIpv4(), Port.tcp(443), "Allow HTTPS traffic");

BucketDeployment.Builder.create(this, "DeployWithSecurityGroup")
        .destinationBucket(bucket)
        .vpc(vpc)
        .securityGroups(List.of(securityGroup))
        .sources(List.of(Source.asset("./website")))
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
var vpc = Vpc.FromLookup(this, "ExistingVPC", new VpcLookupOptions { VpcId = "vpc-12345678" });
var bucket = new Bucket(this, "MyBucket");

var securityGroup = new SecurityGroup(this, "CustomSG", new SecurityGroupProps {
    Vpc = vpc,
    Description = "Allow HTTPS outbound access",
    AllowAllOutbound = false
});

securityGroup.AddEgressRule(Peer.AnyIpv4(), Port.Tcp(443), "Allow HTTPS traffic");

new BucketDeployment(this, "DeployWithSecurityGroup", new BucketDeploymentProps {
    DestinationBucket = bucket,
    Vpc = vpc,
    SecurityGroups = new [] { securityGroup },
    Sources = new [] { Source.Asset("./website") }
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
vpc := ec2.Vpc_FromLookup(this, jsii.String("ExistingVPC"), &VpcLookupOptions{
	VpcId: jsii.String("vpc-12345678"),
})
bucket := s3.NewBucket(this, jsii.String("MyBucket"))

securityGroup := ec2.NewSecurityGroup(this, jsii.String("CustomSG"), &SecurityGroupProps{
	Vpc: vpc,
	Description: jsii.String("Allow HTTPS outbound access"),
	AllowAllOutbound: jsii.Boolean(false),
})

securityGroup.AddEgressRule(ec2.Peer_AnyIpv4(), ec2.Port_Tcp(jsii.Number(443)), jsii.String("Allow HTTPS traffic"))

s3deploy.NewBucketDeployment(this, jsii.String("DeployWithSecurityGroup"), &BucketDeploymentProps{
	DestinationBucket: bucket,
	Vpc: vpc,
	SecurityGroups: []ISecurityGroup{
		securityGroup,
	},
	Sources: []ISource{
		s3deploy.Source_Asset(jsii.String("./website")),
	},
})

Initializer ​

ts
new SecurityGroup(scope: Construct, id: string, props: SecurityGroupProps)
python
SecurityGroup(scope: Construct, id: str, props: SecurityGroupProps)
java
new SecurityGroup(Construct scope, String id, SecurityGroupProps props)
csharp
new SecurityGroup(Construct scope, string id, SecurityGroupProps props)
go
NewSecurityGroup(Scope Construct, Id *string, Props SecurityGroupProps)

Construct Props ​

allowAllIpv6Outboundbooleanallow_all_ipv6_outboundboolallowAllIpv6OutboundBooleanAllowAllIpv6OutboundboolAllowAllIpv6Outbound*bool= false#
Whether to allow all outbound ipv6 traffic by default.
notes

If this is set to true, there will only be a single egress rule which allows all outbound ipv6 traffic. If this is set to false, no outbound traffic will be allowed by default and all egress ipv6 traffic must be explicitly authorized.

To allow all ipv4 traffic use allowAllOutbound

allowAllOutboundbooleanallow_all_outboundboolallowAllOutboundBooleanAllowAllOutboundboolAllowAllOutbound*bool= true#
Whether to allow all outbound traffic by default.
notes

If this is set to true, there will only be a single egress rule which allows all outbound traffic. If this is set to false, no outbound traffic will be allowed by default and all egress traffic must be explicitly authorized.

To allow all ipv6 traffic use allowAllIpv6Outbound

descriptionstringdescriptionstrdescriptionStringDescriptionstringDescription*string= The default name will be the con…#
A description of the security group.
default

Default: The default name will be the construct's CDK path.

disableInlineRulesbooleandisable_inline_rulesbooldisableInlineRulesBooleanDisableInlineRulesboolDisableInlineRules*bool= false#
Whether to disable inline ingress and egress rule optimization.
notes

If this is set to true, ingress and egress rules will not be declared under the SecurityGroup in cloudformation, but will be separate elements.

Inlining rules is an optimization for producing smaller stack templates. Sometimes this is not desirable, for example when security group access is managed via tags.

The default value can be overridden globally by setting the context variable '@aws-cdk/aws-ec2.securityGroupDisableInlineRules'.

securityGroupNamestringsecurity_group_namestrsecurityGroupNameStringSecurityGroupNamestringSecurityGroupName*string= If you don't specify a GroupName…#
The name of the security group.

For valid values, see the GroupName parameter of the CreateSecurityGroup action in the Amazon EC2 API Reference.

It is not recommended to use an explicit group name.

default

Default: If you don't specify a GroupName, AWS CloudFormation generates a unique physical ID and uses that ID for the group name.

vpcIVpcvpcIVpcvpcIVpcVpcIVpcVpcIVpcrequired#
The VPC in which to create the security group.

Properties ​

allowAllIpv6Outboundbooleanallow_all_ipv6_outboundboolallowAllIpv6OutboundBooleanAllowAllIpv6OutboundboolAllowAllIpv6Outbound*boolrequired#
Whether the SecurityGroup has been configured to allow all outbound ipv6 traffic.
allowAllOutboundbooleanallow_all_outboundboolallowAllOutboundBooleanAllowAllOutboundboolAllowAllOutbound*boolrequired#
Whether the SecurityGroup has been configured to allow all outbound traffic.
canInlineRulebooleancan_inline_ruleboolcanInlineRuleBooleanCanInlineRuleboolCanInlineRule*boolrequired#
Whether the rule can be inlined into a SecurityGroup or not.
connectionsConnectionsconnectionsConnectionsconnectionsConnectionsConnectionsConnectionsConnectionsConnectionsrequired#
The network connections associated with this resource.
defaultPortPortdefault_portPortdefaultPortPortDefaultPortPortDefaultPortPort#
The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
securityGroupIdstringsecurity_group_idstrsecurityGroupIdStringSecurityGroupIdstringSecurityGroupId*stringrequired#
The ID of the security group.
securityGroupRefSecurityGroupReferencesecurity_group_refSecurityGroupReferencesecurityGroupRefSecurityGroupReferenceSecurityGroupRefSecurityGroupReferenceSecurityGroupRefSecurityGroupReferencerequired#
A reference to a SecurityGroup resource.
securityGroupVpcIdstringsecurity_group_vpc_idstrsecurityGroupVpcIdStringSecurityGroupVpcIdstringSecurityGroupVpcId*stringrequired#
The VPC ID this security group is part of.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.
uniqueIdstringunique_idstruniqueIdStringUniqueIdstringUniqueId*stringrequired#
A unique identifier for this connection peer.

Methods ​

addEgressRule(peer: IPeer, connection: Port, description?: string, remoteRule?: boolean): voiddef add_egress_rule(self, peer: IPeer, connection: Port, description: typing.Optional[str] = None, remote_rule: typing.Optional[bool] = None) -> Nonepublic void addEgressRule(IPeer peer, Port connection, String description, Boolean remoteRule)public void AddEgressRule(IPeer peer, Port connection, string? description = null, bool? remoteRule = null)func AddEgressRule(Peer IPeer, Connection Port, Description *string, RemoteRule *bool)#
Add an egress rule for the current security group.
notes

remoteRule controls where the Rule object is created if the peer is also a securityGroup and they are in different stack. If false (default) the rule object is created under the current SecurityGroup object. If true and the peer is also a SecurityGroup, the rule object is created under the remote SecurityGroup object.

addIngressRule(peer: IPeer, connection: Port, description?: string, remoteRule?: boolean): voiddef add_ingress_rule(self, peer: IPeer, connection: Port, description: typing.Optional[str] = None, remote_rule: typing.Optional[bool] = None) -> Nonepublic void addIngressRule(IPeer peer, Port connection, String description, Boolean remoteRule)public void AddIngressRule(IPeer peer, Port connection, string? description = null, bool? remoteRule = null)func AddIngressRule(Peer IPeer, Connection Port, Description *string, RemoteRule *bool)#
Add an ingress rule for the current security group.
notes

remoteRule controls where the Rule object is created if the peer is also a securityGroup and they are in different stack. If false (default) the rule object is created under the current SecurityGroup object. If true and the peer is also a SecurityGroup, the rule object is created under the remote SecurityGroup object.

applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

fromLookupById(scope: Construct, id: string, securityGroupId: string): ISecurityGroup@staticmethod def from_lookup_by_id(scope: Construct, id: str, security_group_id: str) -> ISecurityGrouppublic static ISecurityGroup fromLookupById(Construct scope, String id, String securityGroupId)public static ISecurityGroup FromLookupById(Construct scope, string id, string securityGroupId)func FromLookupById(Scope Construct, Id *string, SecurityGroupId *string) ISecurityGroupstatic#
Look up a security group by id.
fromLookupByName(scope: Construct, id: string, securityGroupName: string, vpc: IVpc): ISecurityGroup@staticmethod def from_lookup_by_name(scope: Construct, id: str, security_group_name: str, vpc: IVpc) -> ISecurityGrouppublic static ISecurityGroup fromLookupByName(Construct scope, String id, String securityGroupName, IVpc vpc)public static ISecurityGroup FromLookupByName(Construct scope, string id, string securityGroupName, IVpc vpc)func FromLookupByName(Scope Construct, Id *string, SecurityGroupName *string, Vpc IVpc) ISecurityGroupstatic#
Look up a security group by name.
fromSecurityGroupId(scope: Construct, id: string, securityGroupId: string, options?: SecurityGroupImportOptions): ISecurityGroup@staticmethod def from_security_group_id(scope: Construct, id: str, security_group_id: str, options: typing.Optional[SecurityGroupImportOptions] = None) -> ISecurityGrouppublic static ISecurityGroup fromSecurityGroupId(Construct scope, String id, String securityGroupId, SecurityGroupImportOptions options)public static ISecurityGroup FromSecurityGroupId(Construct scope, string id, string securityGroupId, SecurityGroupImportOptions? options = null)func FromSecurityGroupId(Scope Construct, Id *string, SecurityGroupId *string, Options SecurityGroupImportOptions) ISecurityGroupstatic#
Import an existing security group into this app.
notes

This method will assume that the Security Group has a rule in it which allows all outbound traffic, and so will not add egress rules to the imported Security Group (only ingress rules).

If your existing Security Group needs to have egress rules added, pass the allowAllOutbound: false option on import.

isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
isSecurityGroup(x: any): boolean@staticmethod def is_security_group(x: Any) -> boolpublic static Boolean isSecurityGroup(Object x)public static bool IsSecurityGroup(object x)func IsSecurityGroup(X interface{}) *boolstatic#
Return whether the indicated object is a security group.
toEgressRuleConfig(): EgressRuleConfigdef to_egress_rule_config(self, ) -> EgressRuleConfigpublic EgressRuleConfig toEgressRuleConfig()public EgressRuleConfig ToEgressRuleConfig()func ToEgressRuleConfig() EgressRuleConfig#
Produce the egress rule JSON for the given connection.
toIngressRuleConfig(): IngressRuleConfigdef to_ingress_rule_config(self, ) -> IngressRuleConfigpublic IngressRuleConfig toIngressRuleConfig()public IngressRuleConfig ToIngressRuleConfig()func ToIngressRuleConfig() IngressRuleConfig#
Produce the ingress rule JSON for the given connection.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.