BuzzerboyAWSLightsail 0.331.1__py3-none-any.whl → 0.333.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,229 @@
1
+ """
2
+ ArchitectureMaker
3
+ =================
4
+
5
+ Helper routines to build common Lightsail architectures using CDKTF.
6
+ """
7
+
8
+ from typing import Any, Dict, List
9
+
10
+ from cdktf import App
11
+
12
+ from BuzzerboyAWSLightsailStack.LightsailDatabase import (
13
+ LightsailDatabaseStack,
14
+ )
15
+ from BuzzerboyAWSLightsailStack.LightsailDatabaseStandalone import (
16
+ LightsailDatabaseStandaloneStack,
17
+ )
18
+ from BuzzerboyAWSLightsailStack.LightsailContainer import (
19
+ LightsailContainerStack,
20
+ )
21
+ from BuzzerboyAWSLightsailStack.LightsailContainerStandalone import (
22
+ LightsailContainerStandaloneStack,
23
+ )
24
+ from BuzzerboyArchetypeStack.BuzzerboyArchetype import BuzzerboyArchetype
25
+
26
+
27
+ class ArchitectureMaker:
28
+ """
29
+ Factory utilities for building Lightsail architectures from a definition dict.
30
+ """
31
+
32
+ @staticmethod
33
+ def auto_stack_db_only(definition: Dict[str, Any], include_compliance: bool = False) -> App:
34
+ """
35
+ Create a DB-only Lightsail stack from a definition dictionary.
36
+
37
+ Expected keys in definition:
38
+ - product (str)
39
+ - name or app (str)
40
+ - tier (str)
41
+ - organization (str)
42
+ - region (str)
43
+ - databases (list[str])
44
+ Optional keys:
45
+ - profile (str)
46
+ - db_instance_size (str)
47
+ - master_username (str)
48
+ - flags (list[str])
49
+ """
50
+ if not isinstance(definition, dict):
51
+ raise ValueError("definition must be a dictionary")
52
+
53
+ product = definition.get("product")
54
+ app_name = definition.get("name") or definition.get("app")
55
+ tier = definition.get("tier")
56
+ organization = definition.get("organization")
57
+ region = definition.get("region")
58
+ databases = definition.get("databases", [])
59
+
60
+ missing = [key for key, value in {
61
+ "product": product,
62
+ "name/app": app_name,
63
+ "tier": tier,
64
+ "organization": organization,
65
+ "region": region,
66
+ "databases": databases,
67
+ }.items() if not value]
68
+ if missing:
69
+ raise ValueError(f"definition is missing required keys: {', '.join(missing)}")
70
+
71
+ archetype = BuzzerboyArchetype(
72
+ product=product,
73
+ app=app_name,
74
+ tier=tier,
75
+ organization=organization,
76
+ region=region,
77
+ )
78
+
79
+ flags: List[str] = list(definition.get("flags", []))
80
+ flags = list(dict.fromkeys(flags))
81
+
82
+ app = App()
83
+
84
+ stack_class = LightsailDatabaseStack if include_compliance else LightsailDatabaseStandaloneStack
85
+ stack_class(
86
+ app,
87
+ f"{archetype.get_project_name()}-db-stack",
88
+ project_name=archetype.get_project_name(),
89
+ environment=archetype.get_tier(),
90
+ region=archetype.get_region(),
91
+ secret_name=archetype.get_secret_name(),
92
+ databases=databases,
93
+ profile=definition.get("profile", "default"),
94
+ db_instance_size=definition.get("db_instance_size", "micro_2_0"),
95
+ master_username=definition.get("master_username", "dbmasteruser"),
96
+ flags=flags,
97
+ )
98
+
99
+ app.synth()
100
+ return app
101
+
102
+ @staticmethod
103
+ def auto_main_container_only(definition: Dict[str, Any], include_compliance: bool = False) -> App:
104
+ """
105
+ Create a container-only Lightsail stack from a definition dictionary.
106
+
107
+ Expected keys in definition:
108
+ - product (str)
109
+ - name or app (str)
110
+ - tier (str)
111
+ - organization (str)
112
+ - region (str)
113
+ Optional keys:
114
+ - profile (str)
115
+ - flags (list[str])
116
+ """
117
+ if not isinstance(definition, dict):
118
+ raise ValueError("definition must be a dictionary")
119
+
120
+ product = definition.get("product")
121
+ app_name = definition.get("name") or definition.get("app")
122
+ tier = definition.get("tier")
123
+ organization = definition.get("organization")
124
+ region = definition.get("region")
125
+
126
+ missing = [key for key, value in {
127
+ "product": product,
128
+ "name/app": app_name,
129
+ "tier": tier,
130
+ "organization": organization,
131
+ "region": region,
132
+ }.items() if not value]
133
+ if missing:
134
+ raise ValueError(f"definition is missing required keys: {', '.join(missing)}")
135
+
136
+ archetype = BuzzerboyArchetype(
137
+ product=product,
138
+ app=app_name,
139
+ tier=tier,
140
+ organization=organization,
141
+ region=region,
142
+ )
143
+
144
+ flags: List[str] = list(definition.get("flags", []))
145
+ flags.extend([
146
+ "skip_database",
147
+ "skip_domain",
148
+ ])
149
+ flags = list(dict.fromkeys(flags))
150
+
151
+ app = App()
152
+
153
+ stack_class = LightsailContainerStack if include_compliance else LightsailContainerStandaloneStack
154
+ stack_class(
155
+ app,
156
+ f"{archetype.get_project_name()}-stack",
157
+ project_name=archetype.get_project_name(),
158
+ environment=archetype.get_tier(),
159
+ region=archetype.get_region(),
160
+ secret_name=archetype.get_secret_name(),
161
+ profile=definition.get("profile", "default"),
162
+ flags=flags,
163
+ )
164
+
165
+ app.synth()
166
+ return app
167
+
168
+ @staticmethod
169
+ def auto_main(definition: Dict[str, Any], include_compliance: bool = False) -> App:
170
+ """
171
+ Create a container + database Lightsail stack from a definition dictionary.
172
+
173
+ Expected keys in definition:
174
+ - product (str)
175
+ - name or app (str)
176
+ - tier (str)
177
+ - organization (str)
178
+ - region (str)
179
+ Optional keys:
180
+ - profile (str)
181
+ - flags (list[str])
182
+ """
183
+ if not isinstance(definition, dict):
184
+ raise ValueError("definition must be a dictionary")
185
+
186
+ product = definition.get("product")
187
+ app_name = definition.get("name") or definition.get("app")
188
+ tier = definition.get("tier")
189
+ organization = definition.get("organization")
190
+ region = definition.get("region")
191
+
192
+ missing = [key for key, value in {
193
+ "product": product,
194
+ "name/app": app_name,
195
+ "tier": tier,
196
+ "organization": organization,
197
+ "region": region,
198
+ }.items() if not value]
199
+ if missing:
200
+ raise ValueError(f"definition is missing required keys: {', '.join(missing)}")
201
+
202
+ archetype = BuzzerboyArchetype(
203
+ product=product,
204
+ app=app_name,
205
+ tier=tier,
206
+ organization=organization,
207
+ region=region,
208
+ )
209
+
210
+ flags: List[str] = list(definition.get("flags", []))
211
+ flags.append("skip_domain")
212
+ flags = list(dict.fromkeys(flags))
213
+
214
+ app = App()
215
+
216
+ stack_class = LightsailContainerStack if include_compliance else LightsailContainerStandaloneStack
217
+ stack_class(
218
+ app,
219
+ f"{archetype.get_project_name()}-stack",
220
+ project_name=archetype.get_project_name(),
221
+ environment=archetype.get_tier(),
222
+ region=archetype.get_region(),
223
+ secret_name=archetype.get_secret_name(),
224
+ profile=definition.get("profile", "default"),
225
+ flags=flags,
226
+ )
227
+
228
+ app.synth()
229
+ return app
@@ -24,11 +24,8 @@ This class should be extended by specific Lightsail implementations such as:
24
24
  #region specific imports
25
25
 
26
26
  import os
27
- import json
28
27
  from abc import ABC, abstractmethod
29
- from enum import Enum
30
28
  from constructs import Construct
31
- from cdktf import TerraformOutput
32
29
 
33
30
  # Import from the correct base architecture package
34
31
  import sys
@@ -39,47 +36,14 @@ from AWSArchitectureBase.AWSArchitectureBaseStack.AWSArchitectureBase import AWS
39
36
 
40
37
  #region AWS Provider and Resources
41
38
  from cdktf_cdktf_provider_aws.provider import AwsProvider
42
- from cdktf_cdktf_provider_aws import (
43
- iam_user,
44
- iam_access_key,
45
- iam_user_policy,
46
- )
39
+ from cdktf_cdktf_provider_aws import iam_access_key, iam_user, iam_user_policy
47
40
  #endregion
48
41
 
49
- #region Random Provider and Resources
50
- from cdktf_cdktf_provider_random import password
42
+ from .LightsailFlags import BaseLightsailArchitectureFlags
43
+ from .LightsailMixins import LightsailBaseMixin
51
44
 
52
- # AWS Secrets Manager
53
- from cdktf_cdktf_provider_aws.secretsmanager_secret import SecretsmanagerSecret
54
- from cdktf_cdktf_provider_aws.secretsmanager_secret_version import SecretsmanagerSecretVersion
55
- from cdktf_cdktf_provider_aws.data_aws_secretsmanager_secret_version import DataAwsSecretsmanagerSecretVersion
56
45
 
57
- # Null Provider for local-exec provisioner
58
- from cdktf_cdktf_provider_null.resource import Resource as NullResource
59
-
60
- #endregion
61
-
62
- #region Base ArchitectureFlags
63
- class BaseLightsailArchitectureFlags(Enum):
64
- """
65
- Base architecture configuration flags for optional components.
66
-
67
- These flags are common to all Lightsail implementations and can be
68
- extended by specific implementations with additional flags.
69
-
70
- :param SKIP_DEFAULT_POST_APPLY_SCRIPTS: Skip default post-apply scripts
71
- :param PRESERVE_EXISTING_SECRETS: Don't overwrite existing secret versions (smart detection)
72
- :param IGNORE_SECRET_CHANGES: Ignore all changes to secret after initial creation
73
- """
74
-
75
- SKIP_DEFAULT_POST_APPLY_SCRIPTS = "skip_default_post_apply_scripts"
76
- PRESERVE_EXISTING_SECRETS = "preserve_existing_secrets"
77
- IGNORE_SECRET_CHANGES = "ignore_secret_changes"
78
-
79
- #endregion
80
-
81
-
82
- class LightsailBase(AWSArchitectureBase):
46
+ class LightsailBase(LightsailBaseMixin, AWSArchitectureBase):
83
47
  """
84
48
  Abstract base class for AWS Lightsail Infrastructure Stacks.
85
49
 
@@ -377,294 +341,3 @@ class LightsailBase(AWSArchitectureBase):
377
341
  user=self.service_user.name,
378
342
  policy=policy,
379
343
  )
380
-
381
- def get_extra_secret_env(self, env_var_name=None):
382
- """
383
- Load additional secrets from environment variable.
384
-
385
- Attempts to load and parse a JSON string from the environment variable
386
- specified in default_extra_secret_env. Any valid JSON key-value pairs
387
- are added to the secrets dictionary if they don't already exist.
388
-
389
- :param env_var_name: Environment variable name to load secrets from
390
- :raises: No exceptions - silently continues if JSON parsing fails
391
- """
392
- if env_var_name is None:
393
- env_var_name = self.default_extra_secret_env
394
-
395
- extra_secret_env = os.environ.get(env_var_name, None)
396
-
397
- if extra_secret_env:
398
- try:
399
- extra_secret_json = json.loads(extra_secret_env)
400
- for key, value in extra_secret_json.items():
401
- if key not in self.secrets:
402
- self.secrets[key] = value
403
- except json.JSONDecodeError:
404
- # Silently continue if JSON parsing fails
405
- pass
406
-
407
- def create_security_resources(self):
408
- """
409
- Create AWS Secrets Manager resources for credential storage.
410
-
411
- Creates:
412
- * Secrets Manager secret for storing application credentials
413
- * Secret version with JSON-formatted credential data (conditionally)
414
-
415
- **Secret Management Strategy:**
416
-
417
- If PRESERVE_EXISTING_SECRETS flag is set:
418
- - Checks if secret already exists with content
419
- - Only creates new version if secret is empty or doesn't exist
420
- - Preserves manual secret updates and rotations
421
-
422
- **Stored Credentials:**
423
-
424
- * IAM access keys for service authentication
425
- * AWS region and signature version configuration
426
- * Any additional secrets from environment variables
427
- * Subclass-specific credentials (added by create_lightsail_resources)
428
-
429
- .. note::
430
- All secrets are stored as a single JSON document in Secrets Manager
431
- for easy retrieval by applications.
432
- """
433
- # Create Secrets Manager secret
434
- self.secrets_manager_secret = SecretsmanagerSecret(self, self.secret_name, name=f"{self.secret_name}")
435
- self.resources["secretsmanager_secret"] = self.secrets_manager_secret
436
-
437
- # Populate IAM and AWS configuration secrets
438
- self.secrets.update({
439
- "service_user_access_key": self.service_key.id,
440
- "service_user_secret_key": self.service_key.secret,
441
- "access_key": self.service_key.id,
442
- "secret_access_key": self.service_key.secret,
443
- "region_name": self.region,
444
- "signature_version": self.default_signature_version
445
- })
446
-
447
- # Load additional secrets from environment
448
- self.get_extra_secret_env()
449
-
450
- # Conditional secret version creation
451
- if self.has_flag(BaseLightsailArchitectureFlags.PRESERVE_EXISTING_SECRETS.value):
452
- self._create_secret_version_conditionally()
453
- elif self.has_flag(BaseLightsailArchitectureFlags.IGNORE_SECRET_CHANGES.value):
454
- self._create_secret_version_with_lifecycle_ignore()
455
- else:
456
- # Create secret version with all credentials (original behavior)
457
- SecretsmanagerSecretVersion(
458
- self,
459
- self.secret_name + "_version",
460
- secret_id=self.secrets_manager_secret.id,
461
- secret_string=(json.dumps(self.secrets, indent=2, sort_keys=True) if self.secrets else None),
462
- )
463
-
464
- def _create_secret_version_conditionally(self):
465
- """
466
- Create secret version only if one doesn't already exist or is empty.
467
-
468
- This method implements smart secret management:
469
- 1. Attempts to read existing secret using data source
470
- 2. Only creates new version if secret is empty or doesn't exist
471
- 3. Preserves manual updates and rotations made outside Terraform
472
-
473
- **Use Cases:**
474
- - Initial deployment when no secret exists
475
- - Secret exists but has no content (empty)
476
- - Avoid overwriting manually rotated credentials
477
- - Preserve additional keys added through AWS console/CLI
478
- """
479
- try:
480
- # Try to read existing secret version to check if it has content
481
- existing_secret = DataAwsSecretsmanagerSecretVersion(
482
- self,
483
- self.secret_name + "_existing_check",
484
- secret_id=self.secrets_manager_secret.id,
485
- version_stage="AWSCURRENT"
486
- )
487
-
488
- # Create a conditional secret version
489
- conditional_secret = SecretsmanagerSecretVersion(
490
- self,
491
- self.secret_name + "_version_conditional",
492
- secret_id=self.secrets_manager_secret.id,
493
- secret_string=json.dumps(self.secrets, indent=2, sort_keys=True) if self.secrets else None,
494
- lifecycle={
495
- "ignore_changes": ["secret_string"],
496
- "create_before_destroy": False
497
- }
498
- )
499
-
500
- # Add dependency to ensure secret exists before checking
501
- conditional_secret.add_override("count",
502
- "${length(try(jsondecode(data.aws_secretsmanager_secret_version." +
503
- self.secret_name.replace("/", "_").replace("-", "_") + "_existing_check.secret_string), {})) == 0 ? 1 : 0}"
504
- )
505
-
506
- except Exception:
507
- # If data source fails (secret doesn't exist), create the version
508
- SecretsmanagerSecretVersion(
509
- self,
510
- self.secret_name + "_version_fallback",
511
- secret_id=self.secrets_manager_secret.id,
512
- secret_string=json.dumps(self.secrets, indent=2, sort_keys=True) if self.secrets else None,
513
- )
514
-
515
- def _create_secret_version_with_lifecycle_ignore(self):
516
- """
517
- Create secret version with lifecycle rule to ignore future changes.
518
-
519
- This is a simpler approach that:
520
- 1. Creates the secret version with initial values on first deployment
521
- 2. Ignores all future changes to the secret_string
522
- 3. Allows manual updates in AWS console/CLI to persist
523
-
524
- **Pros:**
525
- - Simple implementation
526
- - Reliable behavior
527
- - Preserves manual changes after initial creation
528
-
529
- **Cons:**
530
- - Cannot update secrets through Terraform after initial deployment
531
- - Requires manual secret management for infrastructure changes
532
- """
533
- secret_version = SecretsmanagerSecretVersion(
534
- self,
535
- self.secret_name + "_version_ignored",
536
- secret_id=self.secrets_manager_secret.id,
537
- secret_string=json.dumps(self.secrets, indent=2, sort_keys=True) if self.secrets else None,
538
- )
539
-
540
- # Add lifecycle rule to ignore changes to secret_string
541
- secret_version.add_override("lifecycle", {
542
- "ignore_changes": ["secret_string"]
543
- })
544
-
545
- def execute_post_apply_scripts(self):
546
- """
547
- Execute post-apply scripts using local-exec provisioners.
548
-
549
- Creates a null resource with local-exec provisioner for each script
550
- in the post_apply_scripts list. Scripts are executed sequentially
551
- after all other infrastructure resources are created.
552
-
553
- **Script Execution:**
554
-
555
- * Each script runs as a separate null resource
556
- * Scripts execute in the order they appear in the list
557
- * Failures in scripts don't prevent deployment completion
558
- * All scripts depend on core infrastructure being ready
559
-
560
- **Error Handling:**
561
-
562
- * Scripts use "on_failure: continue" to prevent deployment failures
563
- * Failed scripts are logged but don't halt the deployment process
564
- * Manual intervention may be required if critical scripts fail
565
-
566
- .. note::
567
- Post-apply scripts can be provided via the postApplyScripts parameter
568
- during stack initialization. If no scripts are provided, this method
569
- returns without creating any resources.
570
-
571
- .. warning::
572
- Scripts have access to the local environment where Terraform runs.
573
- Ensure scripts are safe and don't expose sensitive information.
574
- """
575
- if not self.post_apply_scripts:
576
- return
577
-
578
- # Collect dependencies for post-apply scripts
579
- dependencies = []
580
- if hasattr(self, 'secrets_manager_secret'):
581
- dependencies.append(self.secrets_manager_secret)
582
-
583
- # Create a null resource for each post-apply script
584
- for i, script in enumerate(self.post_apply_scripts):
585
- script_resource = NullResource(
586
- self,
587
- f"post_apply_script_{i}",
588
- depends_on=dependencies if dependencies else None
589
- )
590
-
591
- # Add provisioner using override
592
- script_resource.add_override("provisioner", [{
593
- "local-exec": {
594
- "command": script,
595
- "on_failure": "continue"
596
- }
597
- }])
598
-
599
- # ==================== UTILITY METHODS ====================
600
-
601
- def has_flag(self, flag_value):
602
- """
603
- Check if a specific flag is set in the configuration.
604
-
605
- :param flag_value: The flag value to check for
606
- :type flag_value: str
607
- :returns: True if the flag is set, False otherwise
608
- :rtype: bool
609
- """
610
- return flag_value in self.flags
611
-
612
- def clean_hyphens(self, text):
613
- """
614
- Remove hyphens from text for database/resource naming.
615
-
616
- :param text: Text to clean
617
- :type text: str
618
- :returns: Text with hyphens replaced by underscores
619
- :rtype: str
620
- """
621
- return text.replace("-", "_")
622
-
623
- def properize_s3_bucketname(self, bucket_name):
624
- """
625
- Ensure S3 bucket name follows AWS naming conventions.
626
-
627
- :param bucket_name: Proposed bucket name
628
- :type bucket_name: str
629
- :returns: Properly formatted bucket name
630
- :rtype: str
631
- """
632
- # Convert to lowercase and replace invalid characters
633
- clean_name = bucket_name.lower().replace("_", "-")
634
- # Ensure it starts and ends with alphanumeric characters
635
- clean_name = clean_name.strip("-.")
636
- return clean_name
637
-
638
- # ==================== SHARED OUTPUT HELPERS ====================
639
-
640
- def create_iam_outputs(self):
641
- """
642
- Create standard IAM-related Terraform outputs.
643
-
644
- This helper method can be called by subclasses to create
645
- consistent IAM outputs across all Lightsail implementations.
646
- """
647
- # IAM credentials (sensitive)
648
- TerraformOutput(
649
- self,
650
- "iam_user_access_key",
651
- value=self.service_key.id,
652
- sensitive=True,
653
- description="IAM user access key ID (sensitive)",
654
- )
655
-
656
- TerraformOutput(
657
- self,
658
- "iam_user_secret_key",
659
- value=self.service_key.secret,
660
- sensitive=True,
661
- description="IAM user secret access key (sensitive)",
662
- )
663
-
664
- # Secret name for reference
665
- TerraformOutput(
666
- self,
667
- "secrets_manager_secret_name",
668
- value=self.secret_name,
669
- description="AWS Secrets Manager secret name containing all credentials",
670
- )