3434import java .time .Instant ;
3535import java .time .LocalDate ;
3636import java .time .ZoneOffset ;
37+ import java .util .Arrays ;
3738import java .util .Base64 ;
39+ import java .util .List ;
3840import java .util .Optional ;
3941import java .util .UUID ;
4042import java .util .stream .Stream ;
6365import software .amazon .awssdk .services .cloudfront .model .Distribution ;
6466import software .amazon .awssdk .services .cloudfront .model .DistributionConfig ;
6567import software .amazon .awssdk .services .cloudfront .model .DistributionSummary ;
68+ import software .amazon .awssdk .services .cloudfront .model .GetKeyGroupResponse ;
69+ import software .amazon .awssdk .services .cloudfront .model .KeyGroup ;
70+ import software .amazon .awssdk .services .cloudfront .model .KeyGroupConfig ;
6671import software .amazon .awssdk .services .cloudfront .model .KeyGroupSummary ;
6772import software .amazon .awssdk .services .cloudfront .model .Origin ;
6873import software .amazon .awssdk .services .cloudfront .model .PriceClass ;
@@ -589,7 +594,7 @@ private static String getOrCreateOriginAccessIdentity() {
589594 private static String getOrCreateKeyGroup () {
590595 String keyGroupName = RESOURCE_PREFIX + "key-group" ;
591596
592- Optional <KeyGroupSummary > keyGroup =
597+ Optional <KeyGroupSummary > keyGroupSummary =
593598 cloudFrontClient .listKeyGroups (r -> {})
594599 .keyGroupList ()
595600 .items ()
@@ -599,8 +604,29 @@ private static String getOrCreateKeyGroup() {
599604 .name ()))
600605 .findAny ();
601606
602- if (keyGroup .isPresent ()) {
603- return keyGroup .get ().keyGroup ().id ();
607+ if (keyGroupSummary .isPresent ()) {
608+ // ensure that both keys are present in the keyGroup
609+ List <String > keysInGroup = keyGroupSummary .get ().keyGroup ().keyGroupConfig ().items ();
610+ List <String > expectedKeys = Arrays .asList (rsaKeyPairId , ecKeyPairId );
611+ if (!keysInGroup .containsAll (expectedKeys )) {
612+ System .out .println ("Updating key group to include all keys" );
613+ GetKeyGroupResponse keyGroupResp = cloudFrontClient .getKeyGroup (r -> r .id (keyGroupSummary .get ().keyGroup ().id ()));
614+ cloudFrontClient .updateKeyGroup (r -> {
615+ r
616+ .id (keyGroupResp .keyGroup ().id ())
617+ .ifMatch (keyGroupResp .eTag ())
618+ .keyGroupConfig (KeyGroupConfig .builder ().name (keyGroupName ).items (rsaKeyPairId , ecKeyPairId ).build ());
619+ });
620+ // there is no waiter for keyGroup updates, but it may take up to 1 minute for the updates to propagate
621+ try {
622+ System .out .println ("Waiting 1 minute for keygroup updates to propagate in distribution..." );
623+ Thread .sleep (Duration .ofMinutes (1 ).toMillis ());
624+ } catch (InterruptedException e ) {
625+ throw new RuntimeException (e );
626+ }
627+ }
628+
629+ return keyGroupSummary .get ().keyGroup ().id ();
604630 }
605631
606632 System .out .println ("Creating key group." );
0 commit comments