aws-cdk-lib
Version:
Version 2 of the AWS Cloud Development Kit library
2 lines (1 loc) • 1.55 kB
JavaScript
;Object.defineProperty(exports,"__esModule",{value:!0}),exports.handler=void 0;const sdk=require("@aws-sdk/client-ec2"),ec2=new sdk.EC2({});function ingressRuleParams(groupId,account){return{GroupId:groupId,IpPermissions:[{UserIdGroupPairs:[{GroupId:groupId,UserId:account}],IpProtocol:"-1"}]}}function egressRuleParams(groupId){return{GroupId:groupId,IpPermissions:[{IpRanges:[{CidrIp:"0.0.0.0/0"}],IpProtocol:"-1"}]}}async function handler(event){const securityGroupId=event.ResourceProperties.DefaultSecurityGroupId,account=event.ResourceProperties.Account;switch(event.RequestType){case"Create":return revokeRules(securityGroupId,account);case"Update":return onUpdate(event);case"Delete":return authorizeRules(securityGroupId,account)}}exports.handler=handler;async function onUpdate(event){const oldSg=event.OldResourceProperties.DefaultSecurityGroupId,newSg=event.ResourceProperties.DefaultSecurityGroupId;oldSg!==newSg&&(await authorizeRules(oldSg,event.ResourceProperties.Account),await revokeRules(newSg,event.ResourceProperties.Account))}async function revokeRules(groupId,account){try{await ec2.revokeSecurityGroupEgress(egressRuleParams(groupId))}catch(e){if(e.name!=="InvalidPermission.NotFound")throw e}try{await ec2.revokeSecurityGroupIngress(ingressRuleParams(groupId,account))}catch(e){if(e.name!=="InvalidPermission.NotFound")throw e}}async function authorizeRules(groupId,account){await ec2.authorizeSecurityGroupIngress(ingressRuleParams(groupId,account)),await ec2.authorizeSecurityGroupEgress(egressRuleParams(groupId))}