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:
const securityGroup = ec2.SecurityGroup.fromSecurityGroupId(this, 'SG', 'sg-12345', {
mutable: false
});
Example
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')],
});
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")]
)
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();
// 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") }
});
// 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
new SecurityGroup(scope: Construct, id: string, props: SecurityGroupProps)
SecurityGroup(scope: Construct, id: str, props: SecurityGroupProps)
new SecurityGroup(Construct scope, String id, SecurityGroupProps props)
new SecurityGroup(Construct scope, string id, SecurityGroupProps props)
NewSecurityGroup(Scope Construct, Id *string, Props SecurityGroupProps)
Construct Props
allowAllIpv6Outboundbooleanallow_all_ipv6_outboundboolallowAllIpv6OutboundBooleanAllowAllIpv6OutboundboolAllowAllIpv6Outbound*bool= false#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#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…#default
Default: The default name will be the construct's CDK path.
disableInlineRulesbooleandisable_inline_rulesbooldisableInlineRulesBooleanDisableInlineRulesboolDisableInlineRules*bool= false#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…#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.
Properties
allowAllIpv6Outboundbooleanallow_all_ipv6_outboundboolallowAllIpv6OutboundBooleanAllowAllIpv6OutboundboolAllowAllIpv6Outbound*boolrequired#allowAllOutboundbooleanallow_all_outboundboolallowAllOutboundBooleanAllowAllOutboundboolAllowAllOutbound*boolrequired#canInlineRulebooleancan_inline_ruleboolcanInlineRuleBooleanCanInlineRuleboolCanInlineRule*boolrequired#connectionsConnectionsconnectionsConnectionsconnectionsConnectionsConnectionsConnectionsConnectionsConnectionsrequired#envResourceEnvironmentenvResourceEnvironmentenvResourceEnvironmentEnvResourceEnvironmentEnvResourceEnvironmentrequired#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.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#securityGroupIdstringsecurity_group_idstrsecurityGroupIdStringSecurityGroupIdstringSecurityGroupId*stringrequired#securityGroupRefSecurityGroupReferencesecurity_group_refSecurityGroupReferencesecurityGroupRefSecurityGroupReferenceSecurityGroupRefSecurityGroupReferenceSecurityGroupRefSecurityGroupReferencerequired#securityGroupVpcIdstringsecurity_group_vpc_idstrsecurityGroupVpcIdStringSecurityGroupVpcIdstringSecurityGroupVpcId*stringrequired#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)#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)#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)#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)#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#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#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#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#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#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#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#toEgressRuleConfig(): EgressRuleConfigdef to_egress_rule_config(self, ) -> EgressRuleConfigpublic EgressRuleConfig toEgressRuleConfig()public EgressRuleConfig ToEgressRuleConfig()func ToEgressRuleConfig() EgressRuleConfig#toIngressRuleConfig(): IngressRuleConfigdef to_ingress_rule_config(self, ) -> IngressRuleConfigpublic IngressRuleConfig toIngressRuleConfig()public IngressRuleConfig ToIngressRuleConfig()func ToIngressRuleConfig() IngressRuleConfig#toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#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.