File size: 31,475 Bytes
105b369
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
from typing import List, Optional, Union, Tuple

from phi.app.group import AppGroup
from phi.resource.group import ResourceGroup
from phi.aws.app.base import AwsApp
from phi.aws.app.context import AwsBuildContext
from phi.aws.api_client import AwsApiClient
from phi.aws.resource.base import AwsResource
from phi.infra.resources import InfraResources
from phi.utils.log import logger


class AwsResources(InfraResources):
    apps: Optional[List[Union[AwsApp, AppGroup]]] = None
    resources: Optional[List[Union[AwsResource, ResourceGroup]]] = None

    aws_region: Optional[str] = None
    aws_profile: Optional[str] = None

    # -*- Cached Data
    _api_client: Optional[AwsApiClient] = None

    def get_aws_region(self) -> Optional[str]:
        # Priority 1: Use aws_region from ResourceGroup (or cached value)
        if self.aws_region:
            return self.aws_region

        # Priority 2: Get aws_region from workspace settings
        if self.workspace_settings is not None and self.workspace_settings.aws_region is not None:
            self.aws_region = self.workspace_settings.aws_region
            return self.aws_region

        # Priority 3: Get aws_region from env
        from os import getenv
        from phi.constants import AWS_REGION_ENV_VAR

        aws_region_env = getenv(AWS_REGION_ENV_VAR)
        if aws_region_env is not None:
            logger.debug(f"{AWS_REGION_ENV_VAR}: {aws_region_env}")
            self.aws_region = aws_region_env
        return self.aws_region

    def get_aws_profile(self) -> Optional[str]:
        # Priority 1: Use aws_region from ResourceGroup (or cached value)
        if self.aws_profile:
            return self.aws_profile

        # Priority 2: Get aws_profile from workspace settings
        if self.workspace_settings is not None and self.workspace_settings.aws_profile is not None:
            self.aws_profile = self.workspace_settings.aws_profile
            return self.aws_profile

        # Priority 3: Get aws_profile from env
        from os import getenv
        from phi.constants import AWS_PROFILE_ENV_VAR

        aws_profile_env = getenv(AWS_PROFILE_ENV_VAR)
        if aws_profile_env is not None:
            logger.debug(f"{AWS_PROFILE_ENV_VAR}: {aws_profile_env}")
            self.aws_profile = aws_profile_env
        return self.aws_profile

    @property
    def aws_client(self) -> AwsApiClient:
        if self._api_client is None:
            self._api_client = AwsApiClient(aws_region=self.get_aws_region(), aws_profile=self.get_aws_profile())
        return self._api_client

    def create_resources(
        self,
        group_filter: Optional[str] = None,
        name_filter: Optional[str] = None,
        type_filter: Optional[str] = None,
        dry_run: Optional[bool] = False,
        auto_confirm: Optional[bool] = False,
        force: Optional[bool] = None,
        pull: Optional[bool] = None,
    ) -> Tuple[int, int]:
        from phi.cli.console import print_info, print_heading, confirm_yes_no
        from phi.aws.resource.types import AwsResourceInstallOrder

        logger.debug("-*- Creating AwsResources")
        # Build a list of AwsResources to create
        resources_to_create: List[AwsResource] = []
        if self.resources is not None:
            for r in self.resources:
                if isinstance(r, ResourceGroup):
                    resources_from_resource_group = r.get_resources()
                    if len(resources_from_resource_group) > 0:
                        for resource_from_resource_group in resources_from_resource_group:
                            if isinstance(resource_from_resource_group, AwsResource):
                                resource_from_resource_group.set_workspace_settings(
                                    workspace_settings=self.workspace_settings
                                )
                                if resource_from_resource_group.group is None and self.name is not None:
                                    resource_from_resource_group.group = self.name
                                if resource_from_resource_group.should_create(
                                    group_filter=group_filter,
                                    name_filter=name_filter,
                                    type_filter=type_filter,
                                ):
                                    resources_to_create.append(resource_from_resource_group)
                elif isinstance(r, AwsResource):
                    r.set_workspace_settings(workspace_settings=self.workspace_settings)
                    if r.group is None and self.name is not None:
                        r.group = self.name
                    if r.should_create(
                        group_filter=group_filter,
                        name_filter=name_filter,
                        type_filter=type_filter,
                    ):
                        r.set_workspace_settings(workspace_settings=self.workspace_settings)
                        resources_to_create.append(r)

        # Build a list of AwsApps to create
        apps_to_create: List[AwsApp] = []
        if self.apps is not None:
            for app in self.apps:
                if isinstance(app, AppGroup):
                    apps_from_app_group = app.get_apps()
                    if len(apps_from_app_group) > 0:
                        for app_from_app_group in apps_from_app_group:
                            if isinstance(app_from_app_group, AwsApp):
                                if app_from_app_group.group is None and self.name is not None:
                                    app_from_app_group.group = self.name
                                if app_from_app_group.should_create(group_filter=group_filter):
                                    apps_to_create.append(app_from_app_group)
                elif isinstance(app, AwsApp):
                    if app.group is None and self.name is not None:
                        app.group = self.name
                    if app.should_create(group_filter=group_filter):
                        apps_to_create.append(app)

        # Get the list of AwsResources from the AwsApps
        if len(apps_to_create) > 0:
            logger.debug(f"Found {len(apps_to_create)} apps to create")
            for app in apps_to_create:
                app.set_workspace_settings(workspace_settings=self.workspace_settings)
                app_resources = app.get_resources(
                    build_context=AwsBuildContext(aws_region=self.get_aws_region(), aws_profile=self.get_aws_profile())
                )
                if len(app_resources) > 0:
                    # If the app has dependencies, add the resources from the
                    # dependencies first to the list of resources to create
                    if app.depends_on is not None:
                        for dep in app.depends_on:
                            if isinstance(dep, AwsApp):
                                dep.set_workspace_settings(workspace_settings=self.workspace_settings)
                                dep_resources = dep.get_resources(
                                    build_context=AwsBuildContext(
                                        aws_region=self.get_aws_region(), aws_profile=self.get_aws_profile()
                                    )
                                )
                                if len(dep_resources) > 0:
                                    for dep_resource in dep_resources:
                                        if isinstance(dep_resource, AwsResource):
                                            resources_to_create.append(dep_resource)
                    # Add the resources from the app to the list of resources to create
                    for app_resource in app_resources:
                        if isinstance(app_resource, AwsResource) and app_resource.should_create(
                            group_filter=group_filter, name_filter=name_filter, type_filter=type_filter
                        ):
                            resources_to_create.append(app_resource)

        # Sort the AwsResources in install order
        resources_to_create.sort(key=lambda x: AwsResourceInstallOrder.get(x.__class__.__name__, 5000))

        # Deduplicate AwsResources
        deduped_resources_to_create: List[AwsResource] = []
        for r in resources_to_create:
            if r not in deduped_resources_to_create:
                deduped_resources_to_create.append(r)

        # Implement dependency sorting
        final_aws_resources: List[AwsResource] = []
        logger.debug("-*- Building AwsResources dependency graph")
        for aws_resource in deduped_resources_to_create:
            # Logic to follow if resource has dependencies
            if aws_resource.depends_on is not None and len(aws_resource.depends_on) > 0:
                # Add the dependencies before the resource itself
                for dep in aws_resource.depends_on:
                    if isinstance(dep, AwsResource):
                        if dep not in final_aws_resources:
                            logger.debug(f"-*- Adding {dep.name}, dependency of {aws_resource.name}")
                            final_aws_resources.append(dep)

                # Add the resource to be created after its dependencies
                if aws_resource not in final_aws_resources:
                    logger.debug(f"-*- Adding {aws_resource.name}")
                    final_aws_resources.append(aws_resource)
            else:
                # Add the resource to be created if it has no dependencies
                if aws_resource not in final_aws_resources:
                    logger.debug(f"-*- Adding {aws_resource.name}")
                    final_aws_resources.append(aws_resource)

        # Track the total number of AwsResources to create for validation
        num_resources_to_create: int = len(final_aws_resources)
        num_resources_created: int = 0
        if num_resources_to_create == 0:
            return 0, 0

        if dry_run:
            print_heading("--**- AWS resources to create:")
            for resource in final_aws_resources:
                print_info(f"  -+-> {resource.get_resource_type()}: {resource.get_resource_name()}")
            print_info("")
            if self.get_aws_region():
                print_info(f"Region: {self.get_aws_region()}")
            if self.get_aws_profile():
                print_info(f"Profile: {self.get_aws_profile()}")
            print_info(f"Total {num_resources_to_create} resources")
            return 0, 0

        # Validate resources to be created
        if not auto_confirm:
            print_heading("\n--**-- Confirm resources to create:")
            for resource in final_aws_resources:
                print_info(f"  -+-> {resource.get_resource_type()}: {resource.get_resource_name()}")
            print_info("")
            if self.get_aws_region():
                print_info(f"Region: {self.get_aws_region()}")
            if self.get_aws_profile():
                print_info(f"Profile: {self.get_aws_profile()}")
            print_info(f"Total {num_resources_to_create} resources")
            confirm = confirm_yes_no("\nConfirm deploy")
            if not confirm:
                print_info("-*-")
                print_info("-*- Skipping create")
                print_info("-*-")
                return 0, 0

        for resource in final_aws_resources:
            print_info(f"\n-==+==- {resource.get_resource_type()}: {resource.get_resource_name()}")
            if force is True:
                resource.force = True
            # logger.debug(resource)
            try:
                _resource_created = resource.create(aws_client=self.aws_client)
                if _resource_created:
                    num_resources_created += 1
                else:
                    if self.workspace_settings is not None and not self.workspace_settings.continue_on_create_failure:
                        return num_resources_created, num_resources_to_create
            except Exception as e:
                logger.error(f"Failed to create {resource.get_resource_type()}: {resource.get_resource_name()}")
                logger.error(e)
                logger.error("Please fix and try again...")

        print_heading(f"\n--**-- Resources created: {num_resources_created}/{num_resources_to_create}")
        if num_resources_to_create != num_resources_created:
            logger.error(
                f"Resources created: {num_resources_created} do not match resources required: {num_resources_to_create}"
            )  # noqa: E501
        return num_resources_created, num_resources_to_create

    def delete_resources(
        self,
        group_filter: Optional[str] = None,
        name_filter: Optional[str] = None,
        type_filter: Optional[str] = None,
        dry_run: Optional[bool] = False,
        auto_confirm: Optional[bool] = False,
        force: Optional[bool] = None,
    ) -> Tuple[int, int]:
        from phi.cli.console import print_info, print_heading, confirm_yes_no
        from phi.aws.resource.types import AwsResourceInstallOrder

        logger.debug("-*- Deleting AwsResources")

        # Build a list of AwsResources to delete
        resources_to_delete: List[AwsResource] = []
        if self.resources is not None:
            for r in self.resources:
                if isinstance(r, ResourceGroup):
                    resources_from_resource_group = r.get_resources()
                    if len(resources_from_resource_group) > 0:
                        for resource_from_resource_group in resources_from_resource_group:
                            if isinstance(resource_from_resource_group, AwsResource):
                                resource_from_resource_group.set_workspace_settings(
                                    workspace_settings=self.workspace_settings
                                )
                                if resource_from_resource_group.group is None and self.name is not None:
                                    resource_from_resource_group.group = self.name
                                if resource_from_resource_group.should_delete(
                                    group_filter=group_filter,
                                    name_filter=name_filter,
                                    type_filter=type_filter,
                                ):
                                    resources_to_delete.append(resource_from_resource_group)
                elif isinstance(r, AwsResource):
                    r.set_workspace_settings(workspace_settings=self.workspace_settings)
                    if r.group is None and self.name is not None:
                        r.group = self.name
                    if r.should_delete(
                        group_filter=group_filter,
                        name_filter=name_filter,
                        type_filter=type_filter,
                    ):
                        r.set_workspace_settings(workspace_settings=self.workspace_settings)
                        resources_to_delete.append(r)

        # Build a list of AwsApps to delete
        apps_to_delete: List[AwsApp] = []
        if self.apps is not None:
            for app in self.apps:
                if isinstance(app, AppGroup):
                    apps_from_app_group = app.get_apps()
                    if len(apps_from_app_group) > 0:
                        for app_from_app_group in apps_from_app_group:
                            if isinstance(app_from_app_group, AwsApp):
                                if app_from_app_group.group is None and self.name is not None:
                                    app_from_app_group.group = self.name
                                if app_from_app_group.should_delete(group_filter=group_filter):
                                    apps_to_delete.append(app_from_app_group)
                elif isinstance(app, AwsApp):
                    if app.group is None and self.name is not None:
                        app.group = self.name
                    if app.should_delete(group_filter=group_filter):
                        apps_to_delete.append(app)

        # Get the list of AwsResources from the AwsApps
        if len(apps_to_delete) > 0:
            logger.debug(f"Found {len(apps_to_delete)} apps to delete")
            for app in apps_to_delete:
                app.set_workspace_settings(workspace_settings=self.workspace_settings)
                app_resources = app.get_resources(
                    build_context=AwsBuildContext(aws_region=self.get_aws_region(), aws_profile=self.get_aws_profile())
                )
                if len(app_resources) > 0:
                    for app_resource in app_resources:
                        if isinstance(app_resource, AwsResource) and app_resource.should_delete(
                            group_filter=group_filter, name_filter=name_filter, type_filter=type_filter
                        ):
                            resources_to_delete.append(app_resource)

        # Sort the AwsResources in install order
        resources_to_delete.sort(key=lambda x: AwsResourceInstallOrder.get(x.__class__.__name__, 5000), reverse=True)

        # Deduplicate AwsResources
        deduped_resources_to_delete: List[AwsResource] = []
        for r in resources_to_delete:
            if r not in deduped_resources_to_delete:
                deduped_resources_to_delete.append(r)

        # Implement dependency sorting
        final_aws_resources: List[AwsResource] = []
        logger.debug("-*- Building AwsResources dependency graph")
        for aws_resource in deduped_resources_to_delete:
            # Logic to follow if resource has dependencies
            if aws_resource.depends_on is not None and len(aws_resource.depends_on) > 0:
                # 1. Reverse the order of dependencies
                aws_resource.depends_on.reverse()

                # 2. Remove the dependencies if they are already added to the final_aws_resources
                for dep in aws_resource.depends_on:
                    if dep in final_aws_resources:
                        logger.debug(f"-*- Removing {dep.name}, dependency of {aws_resource.name}")
                        final_aws_resources.remove(dep)

                # 3. Add the resource to be deleted before its dependencies
                if aws_resource not in final_aws_resources:
                    logger.debug(f"-*- Adding {aws_resource.name}")
                    final_aws_resources.append(aws_resource)

                # 4. Add the dependencies back in reverse order
                for dep in aws_resource.depends_on:
                    if isinstance(dep, AwsResource):
                        if dep not in final_aws_resources:
                            logger.debug(f"-*- Adding {dep.name}, dependency of {aws_resource.name}")
                            final_aws_resources.append(dep)
            else:
                # Add the resource to be deleted if it has no dependencies
                if aws_resource not in final_aws_resources:
                    logger.debug(f"-*- Adding {aws_resource.name}")
                    final_aws_resources.append(aws_resource)

        # Track the total number of AwsResources to delete for validation
        num_resources_to_delete: int = len(final_aws_resources)
        num_resources_deleted: int = 0
        if num_resources_to_delete == 0:
            return 0, 0

        if dry_run:
            print_heading("--**- AWS resources to delete:")
            for resource in final_aws_resources:
                print_info(f"  -+-> {resource.get_resource_type()}: {resource.get_resource_name()}")
            print_info("")
            if self.get_aws_region():
                print_info(f"Region: {self.get_aws_region()}")
            if self.get_aws_profile():
                print_info(f"Profile: {self.get_aws_profile()}")
            print_info(f"Total {num_resources_to_delete} resources")
            return 0, 0

        # Validate resources to be deleted
        if not auto_confirm:
            print_heading("\n--**-- Confirm resources to delete:")
            for resource in final_aws_resources:
                print_info(f"  -+-> {resource.get_resource_type()}: {resource.get_resource_name()}")
            print_info("")
            if self.get_aws_region():
                print_info(f"Region: {self.get_aws_region()}")
            if self.get_aws_profile():
                print_info(f"Profile: {self.get_aws_profile()}")
            print_info(f"Total {num_resources_to_delete} resources")
            confirm = confirm_yes_no("\nConfirm delete")
            if not confirm:
                print_info("-*-")
                print_info("-*- Skipping delete")
                print_info("-*-")
                return 0, 0

        for resource in final_aws_resources:
            print_info(f"\n-==+==- {resource.get_resource_type()}: {resource.get_resource_name()}")
            if force is True:
                resource.force = True
            # logger.debug(resource)
            try:
                _resource_deleted = resource.delete(aws_client=self.aws_client)
                if _resource_deleted:
                    num_resources_deleted += 1
                else:
                    if self.workspace_settings is not None and not self.workspace_settings.continue_on_delete_failure:
                        return num_resources_deleted, num_resources_to_delete
            except Exception as e:
                logger.error(f"Failed to delete {resource.get_resource_type()}: {resource.get_resource_name()}")
                logger.error(e)
                logger.error("Please fix and try again...")

        print_heading(f"\n--**-- Resources deleted: {num_resources_deleted}/{num_resources_to_delete}")
        if num_resources_to_delete != num_resources_deleted:
            logger.error(
                f"Resources deleted: {num_resources_deleted} do not match resources required: {num_resources_to_delete}"
            )  # noqa: E501
        return num_resources_deleted, num_resources_to_delete

    def update_resources(
        self,
        group_filter: Optional[str] = None,
        name_filter: Optional[str] = None,
        type_filter: Optional[str] = None,
        dry_run: Optional[bool] = False,
        auto_confirm: Optional[bool] = False,
        force: Optional[bool] = None,
        pull: Optional[bool] = None,
    ) -> Tuple[int, int]:
        from phi.cli.console import print_info, print_heading, confirm_yes_no
        from phi.aws.resource.types import AwsResourceInstallOrder

        logger.debug("-*- Updating AwsResources")

        # Build a list of AwsResources to update
        resources_to_update: List[AwsResource] = []
        if self.resources is not None:
            for r in self.resources:
                if isinstance(r, ResourceGroup):
                    resources_from_resource_group = r.get_resources()
                    if len(resources_from_resource_group) > 0:
                        for resource_from_resource_group in resources_from_resource_group:
                            if isinstance(resource_from_resource_group, AwsResource):
                                resource_from_resource_group.set_workspace_settings(
                                    workspace_settings=self.workspace_settings
                                )
                                if resource_from_resource_group.group is None and self.name is not None:
                                    resource_from_resource_group.group = self.name
                                if resource_from_resource_group.should_update(
                                    group_filter=group_filter,
                                    name_filter=name_filter,
                                    type_filter=type_filter,
                                ):
                                    resources_to_update.append(resource_from_resource_group)
                elif isinstance(r, AwsResource):
                    r.set_workspace_settings(workspace_settings=self.workspace_settings)
                    if r.group is None and self.name is not None:
                        r.group = self.name
                    if r.should_update(
                        group_filter=group_filter,
                        name_filter=name_filter,
                        type_filter=type_filter,
                    ):
                        r.set_workspace_settings(workspace_settings=self.workspace_settings)
                        resources_to_update.append(r)

        # Build a list of AwsApps to update
        apps_to_update: List[AwsApp] = []
        if self.apps is not None:
            for app in self.apps:
                if isinstance(app, AppGroup):
                    apps_from_app_group = app.get_apps()
                    if len(apps_from_app_group) > 0:
                        for app_from_app_group in apps_from_app_group:
                            if isinstance(app_from_app_group, AwsApp):
                                if app_from_app_group.group is None and self.name is not None:
                                    app_from_app_group.group = self.name
                                if app_from_app_group.should_update(group_filter=group_filter):
                                    apps_to_update.append(app_from_app_group)
                elif isinstance(app, AwsApp):
                    if app.group is None and self.name is not None:
                        app.group = self.name
                    if app.should_update(group_filter=group_filter):
                        apps_to_update.append(app)

        # Get the list of AwsResources from the AwsApps
        if len(apps_to_update) > 0:
            logger.debug(f"Found {len(apps_to_update)} apps to update")
            for app in apps_to_update:
                app.set_workspace_settings(workspace_settings=self.workspace_settings)
                app_resources = app.get_resources(
                    build_context=AwsBuildContext(aws_region=self.get_aws_region(), aws_profile=self.get_aws_profile())
                )
                if len(app_resources) > 0:
                    for app_resource in app_resources:
                        if isinstance(app_resource, AwsResource) and app_resource.should_update(
                            group_filter=group_filter, name_filter=name_filter, type_filter=type_filter
                        ):
                            resources_to_update.append(app_resource)

        # Sort the AwsResources in install order
        resources_to_update.sort(key=lambda x: AwsResourceInstallOrder.get(x.__class__.__name__, 5000))

        # Deduplicate AwsResources
        deduped_resources_to_update: List[AwsResource] = []
        for r in resources_to_update:
            if r not in deduped_resources_to_update:
                deduped_resources_to_update.append(r)

        # Implement dependency sorting
        final_aws_resources: List[AwsResource] = []
        logger.debug("-*- Building AwsResources dependency graph")
        for aws_resource in deduped_resources_to_update:
            # Logic to follow if resource has dependencies
            if aws_resource.depends_on is not None and len(aws_resource.depends_on) > 0:
                # Add the dependencies before the resource itself
                for dep in aws_resource.depends_on:
                    if isinstance(dep, AwsResource):
                        if dep not in final_aws_resources:
                            logger.debug(f"-*- Adding {dep.name}, dependency of {aws_resource.name}")
                            final_aws_resources.append(dep)

                # Add the resource to be created after its dependencies
                if aws_resource not in final_aws_resources:
                    logger.debug(f"-*- Adding {aws_resource.name}")
                    final_aws_resources.append(aws_resource)
            else:
                # Add the resource to be created if it has no dependencies
                if aws_resource not in final_aws_resources:
                    logger.debug(f"-*- Adding {aws_resource.name}")
                    final_aws_resources.append(aws_resource)

        # Track the total number of AwsResources to update for validation
        num_resources_to_update: int = len(final_aws_resources)
        num_resources_updated: int = 0
        if num_resources_to_update == 0:
            return 0, 0

        if dry_run:
            print_heading("--**- AWS resources to update:")
            for resource in final_aws_resources:
                print_info(f"  -+-> {resource.get_resource_type()}: {resource.get_resource_name()}")
            print_info("")
            if self.get_aws_region():
                print_info(f"Region: {self.get_aws_region()}")
            if self.get_aws_profile():
                print_info(f"Profile: {self.get_aws_profile()}")
            print_info(f"Total {num_resources_to_update} resources")
            return 0, 0

        # Validate resources to be updated
        if not auto_confirm:
            print_heading("\n--**-- Confirm resources to update:")
            for resource in final_aws_resources:
                print_info(f"  -+-> {resource.get_resource_type()}: {resource.get_resource_name()}")
            print_info("")
            if self.get_aws_region():
                print_info(f"Region: {self.get_aws_region()}")
            if self.get_aws_profile():
                print_info(f"Profile: {self.get_aws_profile()}")
            print_info(f"Total {num_resources_to_update} resources")
            confirm = confirm_yes_no("\nConfirm patch")
            if not confirm:
                print_info("-*-")
                print_info("-*- Skipping patch")
                print_info("-*-")
                return 0, 0

        for resource in final_aws_resources:
            print_info(f"\n-==+==- {resource.get_resource_type()}: {resource.get_resource_name()}")
            if force is True:
                resource.force = True
            # logger.debug(resource)
            try:
                _resource_updated = resource.update(aws_client=self.aws_client)
                if _resource_updated:
                    num_resources_updated += 1
                else:
                    if self.workspace_settings is not None and not self.workspace_settings.continue_on_patch_failure:
                        return num_resources_updated, num_resources_to_update
            except Exception as e:
                logger.error(f"Failed to update {resource.get_resource_type()}: {resource.get_resource_name()}")
                logger.error(e)
                logger.error("Please fix and try again...")

        print_heading(f"\n--**-- Resources updated: {num_resources_updated}/{num_resources_to_update}")
        if num_resources_to_update != num_resources_updated:
            logger.error(
                f"Resources updated: {num_resources_updated} do not match resources required: {num_resources_to_update}"
            )  # noqa: E501
        return num_resources_updated, num_resources_to_update

    def save_resources(
        self,
        group_filter: Optional[str] = None,
        name_filter: Optional[str] = None,
        type_filter: Optional[str] = None,
    ) -> Tuple[int, int]:
        raise NotImplementedError