diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/SgLookupTestDefaultTestDeployAssert9466B7BF.assets.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/SgLookupTestDefaultTestDeployAssert9466B7BF.assets.json new file mode 100644 index 0000000000000..e67d33537caf4 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/SgLookupTestDefaultTestDeployAssert9466B7BF.assets.json @@ -0,0 +1,19 @@ +{ + "version": "37.0.0", + "files": { + "21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22": { + "source": { + "path": "SgLookupTestDefaultTestDeployAssert9466B7BF.template.json", + "packaging": "file" + }, + "destinations": { + "current_account-current_region": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22.json", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + } + }, + "dockerImages": {} +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/SgLookupTestDefaultTestDeployAssert9466B7BF.template.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/SgLookupTestDefaultTestDeployAssert9466B7BF.template.json new file mode 100644 index 0000000000000..ad9d0fb73d1dd --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/SgLookupTestDefaultTestDeployAssert9466B7BF.template.json @@ -0,0 +1,36 @@ +{ + "Parameters": { + "BootstrapVersion": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "/cdk-bootstrap/hnb659fds/version", + "Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]" + } + }, + "Rules": { + "CheckBootstrapVersion": { + "Assertions": [ + { + "Assert": { + "Fn::Not": [ + { + "Fn::Contains": [ + [ + "1", + "2", + "3", + "4", + "5" + ], + { + "Ref": "BootstrapVersion" + } + ] + } + ] + }, + "AssertDescription": "CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI." + } + ] + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/StackWithSg.assets.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/StackWithSg.assets.json new file mode 100644 index 0000000000000..968cb0d68e94f --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/StackWithSg.assets.json @@ -0,0 +1,20 @@ +{ + "version": "37.0.0", + "files": { + "17ef89703212f1690fb87b6d1e83ab3015c62289c86a8abc3f7c420400a1c6fb": { + "source": { + "path": "StackWithSg.template.json", + "packaging": "file" + }, + "destinations": { + "current_account-current_region": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "17ef89703212f1690fb87b6d1e83ab3015c62289c86a8abc3f7c420400a1c6fb.json", + "region": "us-east-1", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + } + }, + "dockerImages": {} +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/StackWithSg.template.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/StackWithSg.template.json new file mode 100644 index 0000000000000..fb18b78a7a72e --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/StackWithSg.template.json @@ -0,0 +1,91 @@ +{ + "Resources": { + "MyVpcF9F0CA6F": { + "Type": "AWS::EC2::VPC", + "Properties": { + "CidrBlock": "10.0.0.0/16", + "EnableDnsHostnames": true, + "EnableDnsSupport": true, + "InstanceTenancy": "default", + "Tags": [ + { + "Key": "Name", + "Value": "my-vpc-name" + } + ] + } + }, + "MySgAFDC270F2": { + "Type": "AWS::EC2::SecurityGroup", + "Properties": { + "GroupDescription": "my-description", + "SecurityGroupEgress": [ + { + "CidrIp": "0.0.0.0/0", + "Description": "Allow all outbound traffic by default", + "IpProtocol": "-1" + } + ], + "Tags": [ + { + "Key": "myTag", + "Value": "my-value" + } + ], + "VpcId": { + "Ref": "MyVpcF9F0CA6F" + } + } + }, + "MySgB343D3C61": { + "Type": "AWS::EC2::SecurityGroup", + "Properties": { + "GroupDescription": "my-description", + "SecurityGroupEgress": [ + { + "CidrIp": "0.0.0.0/0", + "Description": "Allow all outbound traffic by default", + "IpProtocol": "-1" + } + ], + "VpcId": { + "Ref": "MyVpcF9F0CA6F" + } + } + } + }, + "Parameters": { + "BootstrapVersion": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "/cdk-bootstrap/hnb659fds/version", + "Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]" + } + }, + "Rules": { + "CheckBootstrapVersion": { + "Assertions": [ + { + "Assert": { + "Fn::Not": [ + { + "Fn::Contains": [ + [ + "1", + "2", + "3", + "4", + "5" + ], + { + "Ref": "BootstrapVersion" + } + ] + } + ] + }, + "AssertDescription": "CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI." + } + ] + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/cdk.out b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/cdk.out new file mode 100644 index 0000000000000..079dd58c72d69 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/cdk.out @@ -0,0 +1 @@ +{"version":"37.0.0"} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/integ.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/integ.json new file mode 100644 index 0000000000000..f6922a69f5315 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/integ.json @@ -0,0 +1,12 @@ +{ + "version": "37.0.0", + "testCases": { + "SgLookupTest/DefaultTest": { + "stacks": [ + "StackWithSg" + ], + "assertionStack": "SgLookupTest/DefaultTest/DeployAssert", + "assertionStackName": "SgLookupTestDefaultTestDeployAssert9466B7BF" + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/manifest.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/manifest.json new file mode 100644 index 0000000000000..c1cbce4a4a3cb --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/manifest.json @@ -0,0 +1,125 @@ +{ + "version": "37.0.0", + "artifacts": { + "StackWithSg.assets": { + "type": "cdk:asset-manifest", + "properties": { + "file": "StackWithSg.assets.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "StackWithSg": { + "type": "aws:cloudformation:stack", + "environment": "aws://unknown-account/unknown-region", + "properties": { + "templateFile": "StackWithSg.template.json", + "terminationProtection": false, + "validateOnSynth": false, + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", + "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/17ef89703212f1690fb87b6d1e83ab3015c62289c86a8abc3f7c420400a1c6fb.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", + "additionalDependencies": [ + "StackWithSg.assets" + ], + "lookupRole": { + "arn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-lookup-role-${AWS::AccountId}-${AWS::Region}", + "requiresBootstrapStackVersion": 8, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "dependencies": [ + "StackWithSg.assets" + ], + "metadata": { + "/StackWithSg/MyVpc/Resource": [ + { + "type": "aws:cdk:logicalId", + "data": "MyVpcF9F0CA6F" + } + ], + "/StackWithSg/MySgA/Resource": [ + { + "type": "aws:cdk:logicalId", + "data": "MySgAFDC270F2" + } + ], + "/StackWithSg/MySgB/Resource": [ + { + "type": "aws:cdk:logicalId", + "data": "MySgB343D3C61" + } + ], + "/StackWithSg/BootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "BootstrapVersion" + } + ], + "/StackWithSg/CheckBootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "CheckBootstrapVersion" + } + ] + }, + "displayName": "StackWithSg" + }, + "SgLookupTestDefaultTestDeployAssert9466B7BF.assets": { + "type": "cdk:asset-manifest", + "properties": { + "file": "SgLookupTestDefaultTestDeployAssert9466B7BF.assets.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "SgLookupTestDefaultTestDeployAssert9466B7BF": { + "type": "aws:cloudformation:stack", + "environment": "aws://unknown-account/unknown-region", + "properties": { + "templateFile": "SgLookupTestDefaultTestDeployAssert9466B7BF.template.json", + "terminationProtection": false, + "validateOnSynth": false, + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", + "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", + "additionalDependencies": [ + "SgLookupTestDefaultTestDeployAssert9466B7BF.assets" + ], + "lookupRole": { + "arn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-lookup-role-${AWS::AccountId}-${AWS::Region}", + "requiresBootstrapStackVersion": 8, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "dependencies": [ + "SgLookupTestDefaultTestDeployAssert9466B7BF.assets" + ], + "metadata": { + "/SgLookupTest/DefaultTest/DeployAssert/BootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "BootstrapVersion" + } + ], + "/SgLookupTest/DefaultTest/DeployAssert/CheckBootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "CheckBootstrapVersion" + } + ] + }, + "displayName": "SgLookupTest/DefaultTest/DeployAssert" + }, + "Tree": { + "type": "cdk:tree", + "properties": { + "file": "tree.json" + } + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/tree.json b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/tree.json new file mode 100644 index 0000000000000..e3187ef01e0bd --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.js.snapshot/tree.json @@ -0,0 +1,216 @@ +{ + "version": "tree-0.1", + "tree": { + "id": "App", + "path": "", + "children": { + "StackWithSg": { + "id": "StackWithSg", + "path": "StackWithSg", + "children": { + "MyVpc": { + "id": "MyVpc", + "path": "StackWithSg/MyVpc", + "children": { + "Resource": { + "id": "Resource", + "path": "StackWithSg/MyVpc/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::EC2::VPC", + "aws:cdk:cloudformation:props": { + "cidrBlock": "10.0.0.0/16", + "enableDnsHostnames": true, + "enableDnsSupport": true, + "instanceTenancy": "default", + "tags": [ + { + "key": "Name", + "value": "my-vpc-name" + } + ] + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.CfnVPC", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.Vpc", + "version": "0.0.0" + } + }, + "MySgA": { + "id": "MySgA", + "path": "StackWithSg/MySgA", + "children": { + "Resource": { + "id": "Resource", + "path": "StackWithSg/MySgA/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::EC2::SecurityGroup", + "aws:cdk:cloudformation:props": { + "groupDescription": "my-description", + "securityGroupEgress": [ + { + "cidrIp": "0.0.0.0/0", + "description": "Allow all outbound traffic by default", + "ipProtocol": "-1" + } + ], + "tags": [ + { + "key": "myTag", + "value": "my-value" + } + ], + "vpcId": { + "Ref": "MyVpcF9F0CA6F" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.CfnSecurityGroup", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.SecurityGroup", + "version": "0.0.0" + } + }, + "MySgB": { + "id": "MySgB", + "path": "StackWithSg/MySgB", + "children": { + "Resource": { + "id": "Resource", + "path": "StackWithSg/MySgB/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::EC2::SecurityGroup", + "aws:cdk:cloudformation:props": { + "groupDescription": "my-description", + "securityGroupEgress": [ + { + "cidrIp": "0.0.0.0/0", + "description": "Allow all outbound traffic by default", + "ipProtocol": "-1" + } + ], + "vpcId": { + "Ref": "MyVpcF9F0CA6F" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.CfnSecurityGroup", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_ec2.SecurityGroup", + "version": "0.0.0" + } + }, + "SgFromLookup": { + "id": "SgFromLookup", + "path": "StackWithSg/SgFromLookup", + "constructInfo": { + "fqn": "aws-cdk-lib.Resource", + "version": "0.0.0" + } + }, + "BootstrapVersion": { + "id": "BootstrapVersion", + "path": "StackWithSg/BootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnParameter", + "version": "0.0.0" + } + }, + "CheckBootstrapVersion": { + "id": "CheckBootstrapVersion", + "path": "StackWithSg/CheckBootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnRule", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.Stack", + "version": "0.0.0" + } + }, + "SgLookupTest": { + "id": "SgLookupTest", + "path": "SgLookupTest", + "children": { + "DefaultTest": { + "id": "DefaultTest", + "path": "SgLookupTest/DefaultTest", + "children": { + "Default": { + "id": "Default", + "path": "SgLookupTest/DefaultTest/Default", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.3.0" + } + }, + "DeployAssert": { + "id": "DeployAssert", + "path": "SgLookupTest/DefaultTest/DeployAssert", + "children": { + "BootstrapVersion": { + "id": "BootstrapVersion", + "path": "SgLookupTest/DefaultTest/DeployAssert/BootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnParameter", + "version": "0.0.0" + } + }, + "CheckBootstrapVersion": { + "id": "CheckBootstrapVersion", + "path": "SgLookupTest/DefaultTest/DeployAssert/CheckBootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnRule", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.Stack", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/integ-tests-alpha.IntegTestCase", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "@aws-cdk/integ-tests-alpha.IntegTest", + "version": "0.0.0" + } + }, + "Tree": { + "id": "Tree", + "path": "Tree", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.3.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.App", + "version": "0.0.0" + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.ts b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.ts new file mode 100644 index 0000000000000..0141c08f8698c --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-ec2/test/integ.security-group-lookup.ts @@ -0,0 +1,44 @@ +import * as cdk from 'aws-cdk-lib'; +import * as ec2 from 'aws-cdk-lib/aws-ec2'; + +import { EC2_RESTRICT_DEFAULT_SECURITY_GROUP } from 'aws-cdk-lib/cx-api'; +import { IntegTest } from '@aws-cdk/integ-tests-alpha'; + +const app = new cdk.App(); + +const env = { + account: process.env.CDK_INTEG_ACCOUNT || process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_INTEG_REGION || process.env.CDK_DEFAULT_REGION, +}; + +class SgLookupStack extends cdk.Stack { + constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { + super(scope, id, props); + this.node.setContext(EC2_RESTRICT_DEFAULT_SECURITY_GROUP, false); + + const testVpc = new ec2.Vpc(this, 'MyVpc', { + vpcName: 'my-vpc-name', + ipAddresses: ec2.IpAddresses.cidr('10.0.0.0/16'), + subnetConfiguration: [], + natGateways: 0, + }); + const testSgA = new ec2.SecurityGroup(this, 'MySgA', { vpc: testVpc, description: 'my-description' }); + new ec2.SecurityGroup(this, 'MySgB', { vpc: testVpc, description: 'my-description' }); + cdk.Tags.of(testSgA).add('myTag', 'my-value'); + + ec2.SecurityGroup.fromLookupByFilters(this, 'SgFromLookup', { + description: 'my-description', + tags: { + myTag: ['my-value'], + }, + }); + } +} + +const stack = new SgLookupStack(app, 'StackWithSg', { env }); +new IntegTest(app, 'SgLookupTest', { + testCases: [stack], +}); + +app.synth(); + diff --git a/packages/aws-cdk-lib/aws-ec2/README.md b/packages/aws-cdk-lib/aws-ec2/README.md index 5d10fd95d7e5f..54f49c5ae2c0a 100644 --- a/packages/aws-cdk-lib/aws-ec2/README.md +++ b/packages/aws-cdk-lib/aws-ec2/README.md @@ -843,13 +843,23 @@ Alternatively, use lookup methods to import security groups if you do not know t const sg = ec2.SecurityGroup.fromLookupByName(this, 'SecurityGroupLookup', 'security-group-name', vpc); ``` +You can perform lookups based on filter conditions detailed in the [API](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSecurityGroups.html). +```ts +const sg = ec2.SecurityGroup.fromLookupByFilters(this, 'SecurityGroupLookup', { + ownerId: "012345678901", + description: "my description", + tagKeys: ["tagA", "tagB"], + tags: { tagC: ["valueC", "otherValueC"], tagD: ["valueD"] } +}); +``` + If the security group ID is known and configuration details are unknown, use method `SecurityGroup.fromLookupById` instead. This method will lookup property `allowAllOutbound` from the current configuration of the security group. ```ts const sg = ec2.SecurityGroup.fromLookupById(this, 'SecurityGroupLookup', 'sg-1234'); ``` -The result of `SecurityGroup.fromLookupByName` and `SecurityGroup.fromLookupById` operations will be written to a file called `cdk.context.json`. You must commit this file to source control so that the lookup values are available in non-privileged environments such as CI build steps, and to ensure your template builds are repeatable. +The result of `SecurityGroup.fromLookupByName`, `SecurityGroup.fromLookupById`, and `SecurityGroup.fromLookupByFilters` operations will be written to a file called `cdk.context.json`. You must commit this file to source control so that the lookup values are available in non-privileged environments such as CI build steps, and to ensure your template builds are repeatable. ### Cross Stack Connections diff --git a/packages/aws-cdk-lib/aws-ec2/lib/security-group.ts b/packages/aws-cdk-lib/aws-ec2/lib/security-group.ts index e774c1f9de3af..b9c75b7589350 100644 --- a/packages/aws-cdk-lib/aws-ec2/lib/security-group.ts +++ b/packages/aws-cdk-lib/aws-ec2/lib/security-group.ts @@ -387,6 +387,13 @@ export class SecurityGroup extends SecurityGroupBase { return this.fromLookupAttributes(scope, id, { securityGroupName, vpc }); } + /** + * Look up a security group by filters + */ + public static fromLookupByFilters(scope: Construct, id: string, filters: SecurityGroupLookupOptions) { + return this.fromLookupAttributes(scope, id, filters); + } + /** * Import an existing security group into this app. * @@ -434,7 +441,15 @@ export class SecurityGroup extends SecurityGroupBase { * Look up a security group. */ private static fromLookupAttributes(scope: Construct, id: string, options: SecurityGroupLookupOptions) { - if (Token.isUnresolved(options.securityGroupId) || Token.isUnresolved(options.securityGroupName) || Token.isUnresolved(options.vpc?.vpcId)) { + if ([ + options.securityGroupId, + options.securityGroupName, + options.vpc?.vpcId, + options.description, + options.ownerId, + options.tagKeys, + options.tags, + ].some(opt => Token.isUnresolved(opt))) { throw new Error('All arguments to look up a security group must be concrete (no Tokens)'); } @@ -444,6 +459,10 @@ export class SecurityGroup extends SecurityGroupBase { securityGroupId: options.securityGroupId, securityGroupName: options.securityGroupName, vpcId: options.vpc?.vpcId, + description: options.description, + ownerId: options.ownerId, + tagKeys: options.tagKeys, + tags: options.tags, }, dummyValue: { securityGroupId: 'sg-12345678', @@ -816,13 +835,13 @@ function isAllTrafficRule(rule: any) { * * Either `securityGroupName` or `securityGroupId` has to be specified. */ -interface SecurityGroupLookupOptions { +export interface SecurityGroupLookupOptions { /** * The name of the security group * * If given, will import the SecurityGroup with this name. * - * @default Don't filter on securityGroupName + * @default - Don't filter on securityGroupName */ readonly securityGroupName?: string; @@ -831,7 +850,7 @@ interface SecurityGroupLookupOptions { * * If given, will import the SecurityGroup with this ID. * - * @default Don't filter on securityGroupId + * @default - Don't filter on securityGroupId */ readonly securityGroupId?: string; @@ -840,7 +859,35 @@ interface SecurityGroupLookupOptions { * * If given, will filter the SecurityGroup based on the VPC. * - * @default Don't filter on VPC + * @default - Don't filter on VPC */ readonly vpc?: IVpc; + + /** + * Security group description + * + * @default - Don't filter on description + */ + readonly description?: string; + + /** + * Account ID of the owner of the security group + * + * @default - Don't filter on owner ID + */ + readonly ownerId?: string; + + /** + * The keys of tags assigned to the security group + * + * @default - Don't filter on tag keys + */ + readonly tagKeys?: string[]; + + /** + * The key/value combination of a tag assigned to the security group + * + * @default - Don't filter on tags + */ + readonly tags?: Record; } diff --git a/packages/aws-cdk-lib/aws-ec2/test/security-group.test.ts b/packages/aws-cdk-lib/aws-ec2/test/security-group.test.ts index 50e7f9ae5f224..cd98bd1689181 100644 --- a/packages/aws-cdk-lib/aws-ec2/test/security-group.test.ts +++ b/packages/aws-cdk-lib/aws-ec2/test/security-group.test.ts @@ -596,6 +596,30 @@ describe('security group lookup', () => { }); + test('can look up a security group by filters', () => { + // GIVEN + const app = new App(); + const stack = new Stack(app, 'stack', { + env: { + account: '1234', + region: 'us-east-1', + }, + }); + + // WHEN + const securityGroup = SecurityGroup.fromLookupByFilters(stack, 'SG1', { + ownerId: '012345678901', + description: 'my description', + tagKeys: ['tagA', 'tagB'], + tags: { tagC: ['valueC', 'otherValueC'], tagD: ['valueD'] }, + }); + + // THEN + expect(securityGroup.securityGroupId).toEqual('sg-12345678'); + expect(securityGroup.allowAllOutbound).toEqual(true); + + }); + test('can look up a security group and use it as a peer', () => { // GIVEN const app = new App(); diff --git a/packages/aws-cdk-lib/cloud-assembly-schema/lib/cloud-assembly/context-queries.ts b/packages/aws-cdk-lib/cloud-assembly-schema/lib/cloud-assembly/context-queries.ts index bd35d023dfe69..92fd11f9ea376 100644 --- a/packages/aws-cdk-lib/cloud-assembly-schema/lib/cloud-assembly/context-queries.ts +++ b/packages/aws-cdk-lib/cloud-assembly-schema/lib/cloud-assembly/context-queries.ts @@ -449,6 +449,34 @@ export interface SecurityGroupContextQuery { * @default - None */ readonly vpcId?: string; + + /** + * Security group description + * + * @default - None + */ + readonly description?: string; + + /** + * Account ID of the owner of the security group + * + * @default - None + */ + readonly ownerId?: string; + + /** + * The keys of tags assigned to the security group + * + * @default - None + */ + readonly tagKeys?: string[]; + + /** + * The key/value combination of a tag assigned to the security group + * + * @default - None + */ + readonly tags?: Record; } /** diff --git a/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.schema.json b/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.schema.json index 279dfbe369073..2dc1ceae0d7d9 100644 --- a/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.schema.json +++ b/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.schema.json @@ -870,6 +870,25 @@ "vpcId": { "description": "VPC ID (Default - None)", "type": "string" + }, + "description": { + "description": "Security group description (Default - None)", + "type": "string" + }, + "ownerId": { + "description": "Account ID of the owner of the security group (Default - None)", + "type": "string" + }, + "tagKeys": { + "description": "The keys of tags assigned to the security group (Default - None)", + "type": "array", + "items": { + "type": "string" + } + }, + "tags": { + "description": "The key/value combination of a tag assigned to the security group (Default - None)", + "$ref": "#/definitions/Record" } }, "required": [ @@ -877,6 +896,9 @@ "region" ] }, + "Record": { + "type": "object" + }, "KeyContextQuery": { "description": "Query input for looking up a KMS Key", "type": "object", diff --git a/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.version.json b/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.version.json index 1f0068d32659a..079dd58c72d69 100644 --- a/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.version.json +++ b/packages/aws-cdk-lib/cloud-assembly-schema/schema/cloud-assembly.version.json @@ -1 +1 @@ -{"version":"36.0.0"} \ No newline at end of file +{"version":"37.0.0"} \ No newline at end of file diff --git a/packages/aws-cdk/lib/context-providers/security-groups.ts b/packages/aws-cdk/lib/context-providers/security-groups.ts index 19372df9af842..fa68fa4129e23 100644 --- a/packages/aws-cdk/lib/context-providers/security-groups.ts +++ b/packages/aws-cdk/lib/context-providers/security-groups.ts @@ -17,10 +17,6 @@ export class SecurityGroupContextProviderPlugin implements ContextProviderPlugin throw new Error('\'securityGroupId\' and \'securityGroupName\' can not be specified both when looking up a security group'); } - if (!args.securityGroupId && !args.securityGroupName) { - throw new Error('\'securityGroupId\' or \'securityGroupName\' must be specified to look up a security group'); - } - const options = { assumeRoleArn: args.lookupRoleArn }; const ec2 = (await this.aws.forEnvironment(cxapi.EnvironmentUtils.make(account, region), Mode.ForReading, options)).sdk.ec2(); @@ -37,6 +33,32 @@ export class SecurityGroupContextProviderPlugin implements ContextProviderPlugin Values: [args.securityGroupName], }); } + if (args.description) { + filters.push({ + Name: 'description', + Values: [args.description], + }); + } + if (args.tagKeys) { + filters.push({ + Name: 'tag-key', + Values: args.tagKeys, + }); + } + if (args.ownerId) { + filters.push({ + Name: 'owner-id', + Values: [args.ownerId], + }); + } + if (args.tags) { + Object.entries(args.tags).forEach(([key, values]) => { + filters.push({ + Name: `tag:${key}`, + Values: values, + }); + }); + } const response = await ec2.describeSecurityGroups({ GroupIds: args.securityGroupId ? [args.securityGroupId] : undefined, diff --git a/packages/aws-cdk/test/context-providers/security-groups.test.ts b/packages/aws-cdk/test/context-providers/security-groups.test.ts index c7bdc586ad7bc..2477336d98b93 100644 --- a/packages/aws-cdk/test/context-providers/security-groups.test.ts +++ b/packages/aws-cdk/test/context-providers/security-groups.test.ts @@ -1,7 +1,9 @@ +import * as AWS from 'aws-sdk-mock'; /* eslint-disable import/order */ import * as aws from 'aws-sdk'; -import * as AWS from 'aws-sdk-mock'; -import { hasAllTrafficEgress, SecurityGroupContextProviderPlugin } from '../../lib/context-providers/security-groups'; + +import { SecurityGroupContextProviderPlugin, hasAllTrafficEgress } from '../../lib/context-providers/security-groups'; + import { MockSdkProvider } from '../util/mock-sdk'; AWS.setSDK(require.resolve('aws-sdk')); @@ -226,6 +228,74 @@ describe('security group context provider plugin', () => { expect(res.allowAllOutbound).toEqual(true); }); + test('looks up by security group description, owner id, tag keys, and tags', async () => { + // GIVEN + const provider = new SecurityGroupContextProviderPlugin(mockSDK); + + AWS.mock('EC2', 'describeSecurityGroups', (_params: aws.EC2.DescribeSecurityGroupsRequest, cb: AwsCallback) => { + expect(_params).toEqual({ + GroupIds: undefined, + Filters: [ + { + Name: 'description', + Values: ['my description'], + }, + { + Name: 'tag-key', + Values: ['tagA', 'tagB'], + }, + { + Name: 'owner-id', + Values: ['012345678901'], + }, + { + Name: 'tag:tagC', + Values: ['valueC', 'otherValueC'], + }, + { + Name: 'tag:tagD', + Values: ['valueD'], + }, + ], + }); + cb(null, { + SecurityGroups: [ + { + GroupId: 'sg-1234', + IpPermissionsEgress: [ + { + IpProtocol: '-1', + IpRanges: [ + { CidrIp: '0.0.0.0/0' }, + ], + }, + { + IpProtocol: '-1', + Ipv6Ranges: [ + { CidrIpv6: '::/0' }, + ], + }, + ], + }, + ], + }); + }); + + // WHEN + const res = await provider.getValue({ + account: '1234', + region: 'us-east-1', + ownerId: '012345678901', + description: 'my description', + tagKeys: ['tagA', 'tagB'], + tags: { tagC: ['valueC', 'otherValueC'], tagD: ['valueD'] }, + }); + + // THEN + expect(res.securityGroupId).toEqual('sg-1234'); + expect(res.allowAllOutbound).toEqual(true); + }); + test('detects non all-outbound egress', async () => { // GIVEN const provider = new SecurityGroupContextProviderPlugin(mockSDK); @@ -319,19 +389,6 @@ describe('security group context provider plugin', () => { ).rejects.toThrow(/\'securityGroupId\' and \'securityGroupName\' can not be specified both when looking up a security group/i); }); - test('errors when neither securityGroupId nor securityGroupName are specified', async () => { - // GIVEN - const provider = new SecurityGroupContextProviderPlugin(mockSDK); - - // WHEN - await expect( - provider.getValue({ - account: '1234', - region: 'us-east-1', - }), - ).rejects.toThrow(/\'securityGroupId\' or \'securityGroupName\' must be specified to look up a security group/i); - }); - test('identifies allTrafficEgress from SecurityGroup permissions', () => { expect( hasAllTrafficEgress({