# SecurityGroup

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](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cdk-lib.aws_ec2-readme.html#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
});
```

Extends: Construct › Resource › SecurityGroup
Implements: IResource, IConnectable, IPeer, ISecurityGroup, IEnvironmentAware, ISecurityGroupRef, IConstruct, IDependable

- CloudFormation: [`AWS::EC2::SecurityGroup`](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-securitygroup.html)
- L1 type: [`CfnSecurityGroup`](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.CfnSecurityGroup.html)
- Source: [`aws-ec2/lib/security-group.ts`](https://github.com/aws/aws-cdk/blob/v2.274.0/packages/aws-cdk-lib/aws-ec2/lib/security-group.ts#L391)
- Type last changed: v2.256.0 · 20 May 2026

## 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')],
});
```

## Initializer

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

## Construct Props

- `allowAllIpv6Outbound`: boolean = 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`: boolean = 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`: string — A description of the security group.

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

- `disableInlineRules`: boolean = 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 overridden globally by setting the context variable
  '@aws-cdk/aws-ec2.securityGroupDisableInlineRules'.

- `securityGroupName`: string — The name of the security group.

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

  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.

- `vpc`: [IVpc](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.IVpc.html) (required) — The VPC in which to create the security group.

## Properties

- `allowAllIpv6Outbound`: boolean (required) — Whether the SecurityGroup has been configured to allow all outbound ipv6 traffic.

- `allowAllOutbound`: boolean (required) — Whether the SecurityGroup has been configured to allow all outbound traffic.

- `canInlineRule`: boolean (required) — Whether the rule can be inlined into a SecurityGroup or not.

- `connections`: [Connections](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Connections.html) (required) — The network connections associated with this resource.

- `defaultPort`: [Port](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Port.html)

- `env`: [ResourceEnvironment](/cdk/api/v2/docs/aws-cdk-lib.interfaces.ResourceEnvironment.html) (required) — The environment this resource belongs to.

  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.

- `node`: [Node](/cdk/api/v2/docs/constructs.Node.html) (required) — The tree node.

- `PROPERTY_INJECTION_ID`: string (required) (static) — Uniquely identifies this class.

- `securityGroupId`: string (required) — The ID of the security group.

- `securityGroupRef`: [SecurityGroupReference](/cdk/api/v2/docs/aws-cdk-lib.interfaces.aws_ec2.SecurityGroupReference.html) (required) — A reference to a SecurityGroup resource.

- `securityGroupVpcId`: string (required) — The VPC ID this security group is part of.

- `stack`: [Stack](/cdk/api/v2/docs/aws-cdk-lib.Stack.html) (required) — The stack in which this resource is defined.

- `uniqueId`: string (required) — A unique identifier for this connection peer.

## Methods

- `addEgressRule(peer: IPeer, connection: Port, description?: string, remoteRule?: boolean): void` — 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: IPeer, connection: Port, description?: string, remoteRule?: boolean): void` — 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.

- `applyCrossStackReferenceStrength(strength: ReferenceStrength): void` — Override the cross-stack reference strength for this resource.

  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**

  - `strength` — - The reference strength to use for this resource.

- `applyRemovalPolicy(policy: RemovalPolicy): void` — 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`).

- `fromLookupById(scope: Construct, id: string, securityGroupId: string): ISecurityGroup` (static) — Look up a security group by id.

- `fromLookupByName(scope: Construct, id: string, securityGroupName: string, vpc: IVpc): ISecurityGroup` (static) — Look up a security group by name.

- `fromSecurityGroupId(scope: Construct, id: string, securityGroupId: string, options?: SecurityGroupImportOptions): ISecurityGroup` (static) — 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.

- `isConstruct(x: any): boolean` (static) — Checks if `x` is a construct.

  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**

  - `x` — Any object.

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

- `isOwnedResource(construct: IConstruct): boolean` (static) — Returns true if the construct was created by CDK, and false otherwise.

- `isResource(construct: IConstruct): boolean` (static) — Check whether the given construct is a Resource.

- `isSecurityGroup(x: any): boolean` (static) — Return whether the indicated object is a security group.

- `toEgressRuleConfig(): EgressRuleConfig` — Produce the egress rule JSON for the given connection.

- `toIngressRuleConfig(): IngressRuleConfig` — Produce the ingress rule JSON for the given connection.

- `toString(): string` — Returns a string representation of this construct.

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