class SecurityGroup (construct)
Language | Type name |
---|---|
.NET | Amazon.CDK.AWS.EC2.SecurityGroup |
Go | github.com/aws/aws-cdk-go/awscdk/v2/awsec2#SecurityGroup |
Java | software.amazon.awscdk.services.ec2.SecurityGroup |
Python | aws_cdk.aws_ec2.SecurityGroup |
TypeScript (source) | aws-cdk-lib » aws_ec2 » SecurityGroup |
Implements
IConstruct
, IDependable
, IResource
, ISecurity
, 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 mySecurityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', { vpc });
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
machineImage: ec2.MachineImage.latestAmazonLinux2(),
securityGroup: mySecurityGroup,
});
Initializer
new SecurityGroup(scope: Construct, id: string, props: SecurityGroupProps)
Parameters
- scope
Construct
- id
string
- props
Security
Group Props
Construct Props
Name | Type | Description |
---|---|---|
vpc | IVpc | The VPC in which to create the security group. |
allow | boolean | Whether to allow all outbound ipv6 traffic by default. |
allow | boolean | Whether to allow all outbound traffic by default. |
description? | string | A description of the security group. |
disable | boolean | Whether to disable inline ingress and egress rule optimization. |
security | string | The 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
Name | Type | Description |
---|---|---|
allow | boolean | Whether the SecurityGroup has been configured to allow all outbound ipv6 traffic. |
allow | boolean | Whether the SecurityGroup has been configured to allow all outbound traffic. |
can | boolean | Whether the rule can be inlined into a SecurityGroup or not. |
connections | Connections | The network connections associated with this resource. |
env | Resource | The environment this resource belongs to. |
node | Node | The tree node. |
security | string | The ID of the security group. |
security | string | The VPC ID this security group is part of. |
stack | Stack | The stack in which this resource is defined. |
unique | string | A unique identifier for this connection peer. |
default | 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:
Resource
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
Name | Description |
---|---|
add | Add an egress rule for the current security group. |
add | Add an ingress rule for the current security group. |
apply | Apply the given removal policy to this resource. |
to | Produce the egress rule JSON for the given connection. |
to | Produce the ingress rule JSON for the given connection. |
to | Returns a string representation of this construct. |
protected determine | Determine where to parent a new ingress/egress rule. |
static from | Look up a security group by id. |
static from | Look up a security group by name. |
static from | Import an existing security group into this app. |
static is | 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
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
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
Removal
Policy
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
Returns
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
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
Returns
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
Security
Group Import Options
Returns
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.