@@ -60,20 +60,20 @@ async function onCreateOrUpdate(
6060 await updateS3Protection ( detectorId , s3Protection ) ;
6161
6262 const isAutoEnabled = await isConfigurationAutoEnabled ( detectorId , s3Protection ) ;
63- if ( isAutoEnabled ) {
63+ if ( ! isAutoEnabled ) {
64+ // Update Config to handle new Account created under Organization
65+ await updateConfig ( detectorId , s3Protection ) ;
66+ } else {
6467 console . log ( `GuardDuty is already enabled ORG Level` ) ;
65- return {
66- physicalResourceId,
67- data : { } ,
68- } ;
6968 }
7069
71- // Update Config to handle new Account created under Organization
72- await updateConfig ( detectorId , s3Protection ) ;
73-
74- if ( memberAccounts . length > 0 ) {
75- await createMembers ( memberAccounts , detectorId ) ;
76- await updateMemberDataSource ( memberAccounts , detectorId , s3Protection ) ;
70+ const existingMembers = await listMembers ( detectorId ) ;
71+ const requiredMemberAccounts = memberAccounts . filter (
72+ ma => ! existingMembers . find ( em => em . AccountId === ma . AccountId && em . RelationshipStatus === 'Enabled' ) ,
73+ ) ;
74+ if ( requiredMemberAccounts . length > 0 ) {
75+ await createMembers ( requiredMemberAccounts , detectorId ) ;
76+ await updateMemberDataSource ( requiredMemberAccounts , detectorId , s3Protection ) ;
7777 }
7878
7979 return {
@@ -239,6 +239,23 @@ async function deleteMembers(memberAccounts: AccountDetail[], detectorId: string
239239 }
240240}
241241
242+ async function listMembers ( detectorId : string ) : Promise < AWS . GuardDuty . Member [ ] > {
243+ const members : AWS . GuardDuty . Member [ ] = [ ] ;
244+ let token : string | undefined ;
245+ do {
246+ const response = await throttlingBackOff ( ( ) =>
247+ guardduty
248+ . listMembers ( {
249+ DetectorId : detectorId ,
250+ } )
251+ . promise ( ) ,
252+ ) ;
253+ token = response . NextToken ;
254+ members . push ( ...response . Members ! ) ;
255+ } while ( token ) ;
256+ return members ;
257+ }
258+
242259function getPropertiesFromEvent ( event : CloudFormationCustomResourceEvent ) {
243260 const properties = ( event . ResourceProperties as unknown ) as HandlerProperties ;
244261 if ( typeof properties . s3Protection === 'string' ) {
0 commit comments