aws-cdk-lib.aws_ec2.SecurityGroup

class SecurityGroup (construct)

LanguageType name
.NETAmazon.CDK.AWS.EC2.SecurityGroup
Gogithub.com/aws/aws-cdk-go/awscdk/v2/awsec2#SecurityGroup
Javasoftware.amazon.awscdk.services.ec2.SecurityGroup
Pythonaws_cdk.aws_ec2.SecurityGroup
TypeScript (source)aws-cdk-lib » aws_ec2 » SecurityGroup

Implements IConstruct, IDependable, IResource, ISecurityGroup, IConnectable, IPeer

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

declare const vpc: ec2.Vpc;

const template = new ec2.LaunchTemplate(this, 'LaunchTemplate', {
  machineImage: ec2.MachineImage.latestAmazonLinux2022(),
  securityGroup: new ec2.SecurityGroup(this, 'LaunchTemplateSG', {
    vpc: vpc,
  }),
});

Initializer

new SecurityGroup(scope: Construct, id: string, props: SecurityGroupProps)

Parameters

  • scope Construct
  • id string
  • props SecurityGroupProps

Construct Props

NameTypeDescription
vpcIVpcThe VPC in which to create the security group.
allowAllIpv6Outbound?booleanWhether to allow all outbound ipv6 traffic by default.
allowAllOutbound?booleanWhether to allow all outbound traffic by default.
description?stringA description of the security group.
disableInlineRules?booleanWhether to disable inline ingress and egress rule optimization.
securityGroupName?stringThe name of the security group.

vpc

Type: IVpc

The VPC in which to create the security group.


allowAllIpv6Outbound?

Type: boolean (optional, default: false)

Whether to allow all outbound ipv6 traffic by default.

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


allowAllOutbound?

Type: boolean (optional, default: true)

Whether to allow all outbound traffic by default.

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


description?

Type: string (optional, default: The default name will be the construct's CDK path.)

A description of the security group.


disableInlineRules?

Type: boolean (optional, default: false)

Whether to disable inline ingress and egress rule optimization.

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 overriden globally by setting the context variable '@aws-cdk/aws-ec2.securityGroupDisableInlineRules'.


securityGroupName?

Type: string (optional, default: If you don't specify a GroupName, AWS CloudFormation generates a unique physical ID and uses that ID for the group name.)

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.

Properties

NameTypeDescription
allowAllIpv6OutboundbooleanWhether the SecurityGroup has been configured to allow all outbound ipv6 traffic.
allowAllOutboundbooleanWhether the SecurityGroup has been configured to allow all outbound traffic.
canInlineRulebooleanWhether the rule can be inlined into a SecurityGroup or not.
connectionsConnectionsThe network connections associated with this resource.
envResourceEnvironmentThe environment this resource belongs to.
nodeNodeThe tree node.
securityGroupIdstringThe ID of the security group.
securityGroupVpcIdstringThe VPC ID this security group is part of.
stackStackThe stack in which this resource is defined.
uniqueIdstringA unique identifier for this connection peer.
defaultPort?Port

allowAllIpv6Outbound

Type: boolean

Whether the SecurityGroup has been configured to allow all outbound ipv6 traffic.


allowAllOutbound

Type: boolean

Whether the SecurityGroup has been configured to allow all outbound traffic.


canInlineRule

Type: boolean

Whether the rule can be inlined into a SecurityGroup or not.


connections

Type: Connections

The network connections associated with this resource.


env

Type: ResourceEnvironment

The environment this resource belongs to.

For resources that are created and managed by the CDK (generally, those created by creating new class instances like Role, Bucket, etc.), this is always the same as the environment of the stack they belong to; however, for imported resources (those obtained from static methods like fromRoleArn, fromBucketName, etc.), that might be different than the stack they were imported into.


node

Type: Node

The tree node.


securityGroupId

Type: string

The ID of the security group.


securityGroupVpcId

Type: string

The VPC ID this security group is part of.


stack

Type: Stack

The stack in which this resource is defined.


uniqueId

Type: string

A unique identifier for this connection peer.


defaultPort?

Type: Port (optional)

Methods

NameDescription
addEgressRule(peer, connection, description?, remoteRule?)Add an egress rule for the current security group.
addIngressRule(peer, connection, description?, remoteRule?)Add an ingress rule for the current security group.
applyRemovalPolicy(policy)Apply the given removal policy to this resource.
toEgressRuleConfig()Produce the egress rule JSON for the given connection.
toIngressRuleConfig()Produce the ingress rule JSON for the given connection.
toString()Returns a string representation of this construct.
protected determineRuleScope(peer, connection, fromTo, remoteRule?)Determine where to parent a new ingress/egress rule.
static fromLookupById(scope, id, securityGroupId)Look up a security group by id.
static fromLookupByName(scope, id, securityGroupName, vpc)Look up a security group by name.
static fromSecurityGroupId(scope, id, securityGroupId, options?)Import an existing security group into this app.
static isSecurityGroup(x)Return whether the indicated object is a security group.

addEgressRule(peer, connection, description?, remoteRule?)

public addEgressRule(peer: IPeer, connection: Port, description?: string, remoteRule?: boolean): void

Parameters

  • peer IPeer
  • connection Port
  • description string
  • remoteRule boolean

Add an egress rule for the current security group.

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, connection, description?, remoteRule?)

public addIngressRule(peer: IPeer, connection: Port, description?: string, remoteRule?: boolean): void

Parameters

  • peer IPeer
  • connection Port
  • description string
  • remoteRule boolean

Add an ingress rule for the current security group.

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.


applyRemovalPolicy(policy)

public applyRemovalPolicy(policy: RemovalPolicy): void

Parameters

  • policy RemovalPolicy

Apply the given removal policy to this resource.

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).


toEgressRuleConfig()

public toEgressRuleConfig(): any

Returns

  • any

Produce the egress rule JSON for the given connection.


toIngressRuleConfig()

public toIngressRuleConfig(): any

Returns

  • any

Produce the ingress rule JSON for the given connection.


toString()

public toString(): string

Returns

  • string

Returns a string representation of this construct.


protected determineRuleScope(peer, connection, fromTo, remoteRule?)

protected determineRuleScope(peer: IPeer, connection: Port, fromTo: string, remoteRule?: boolean): RuleScope

Parameters

  • peer IPeer
  • connection Port
  • fromTo string
  • remoteRule boolean

Returns

  • RuleScope

Determine where to parent a new ingress/egress rule.

A SecurityGroup rule is parented under the group it's related to, UNLESS we're in a cross-stack scenario with another Security Group. In that case, we respect the 'remoteRule' flag and will parent under the other security group.

This is necessary to avoid cyclic dependencies between stacks, since both ingress and egress rules will reference both security groups, and a naive parenting will lead to the following situation:

╔════════════════════╗ ╔════════════════════╗ ║ ┌───────────┐ ║ ║ ┌───────────┐ ║ ║ │ GroupA │◀────╬─┐ ┌───╬───▶│ GroupB │ ║ ║ └───────────┘ ║ │ │ ║ └───────────┘ ║ ║ ▲ ║ │ │ ║ ▲ ║ ║ │ ║ │ │ ║ │ ║ ║ │ ║ │ │ ║ │ ║ ║ ┌───────────┐ ║ └───┼───╬────┌───────────┐ ║ ║ │ EgressA │─────╬─────┘ ║ │ IngressB │ ║ ║ └───────────┘ ║ ║ └───────────┘ ║ ║ ║ ║ ║ ╚════════════════════╝ ╚════════════════════╝

By having the ability to switch the parent, we avoid the cyclic reference by keeping all rules in a single stack.

If this happens, we also have to change the construct ID, because otherwise we might have two objects with the same ID if we have multiple reversed security group relationships.

╔═══════════════════════════════════╗ ║┌───────────┐ ║ ║│ GroupB │ ║ ║└───────────┘ ║ ║ ▲ ║ ║ │ ┌───────────┐ ║ ║ ├────"from A"──│ IngressB │ ║ ║ │ └───────────┘ ║ ║ │ ┌───────────┐ ║ ║ ├─────"to B"───│ EgressA │ ║ ║ │ └───────────┘ ║ ║ │ ┌───────────┐ ║ ║ └─────"to B"───│ EgressC │ ║ <-- oops ║ └───────────┘ ║ ╚═══════════════════════════════════╝


static fromLookupById(scope, id, securityGroupId)

public static fromLookupById(scope: Construct, id: string, securityGroupId: string): ISecurityGroup

Parameters

  • scope Construct
  • id string
  • securityGroupId string

Returns

  • ISecurityGroup

Look up a security group by id.


static fromLookupByName(scope, id, securityGroupName, vpc)

public static fromLookupByName(scope: Construct, id: string, securityGroupName: string, vpc: IVpc): ISecurityGroup

Parameters

  • scope Construct
  • id string
  • securityGroupName string
  • vpc IVpc

Returns

  • ISecurityGroup

Look up a security group by name.


static fromSecurityGroupId(scope, id, securityGroupId, options?)

public static fromSecurityGroupId(scope: Construct, id: string, securityGroupId: string, options?: SecurityGroupImportOptions): ISecurityGroup

Parameters

  • scope Construct
  • id string
  • securityGroupId string
  • options SecurityGroupImportOptions

Returns

  • ISecurityGroup

Import an existing security group into this app.

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.


static isSecurityGroup(x)

public static isSecurityGroup(x: any): boolean

Parameters

  • x any

Returns

  • boolean

Return whether the indicated object is a security group.