I was trying to import an existing Security Group in CDK by using SecurityGroup.fromSecurityGroupId method and it failed with the following error:
Security Group Id: sg-12345 not found! (Service: AmazonEC2; Status Code: 400; Error Code: InvalidGroup.NotFound; Request ID: 8e2cd924-075d-4c64-b5ba-2e1d9c72fe95; Proxy: null)
Below is my CDK code:
const sg = SecurityGroup.fromSecurityGroupId(this, 'sgFromLookUp', 'sg-084c533df9d662439');
I double checked that the security group id is correct, I also tried the other 2 methods for security group look up:
SecurityGroup.fromLookupById() and SecurityGroup.fromLookupByName()
All of them returned the same error, any ideas why?
2
Answers
It turns out that the security group is looked up after the InterfaceVpcEndpoint which is referencing to it, because I didn't add dependency of the security group to the InterfaceVpcEndpoint. I managed to look up the security group before referencing to it and it works now.
Code that works:
https://kuchbhilearning.blogspot.com/2022/10/get-security-group-from-id-aws-cdk.html
This can help you get started. CDK does provide methods based on which we can get the security group from id.