BuzzerboyAWSLightsail 0.332.1__py3-none-any.whl → 0.334.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.
@@ -19,61 +19,19 @@ The stack includes:
19
19
 
20
20
  #region specific imports
21
21
 
22
- import os
23
- import json
24
- from enum import Enum
25
22
  from constructs import Construct
26
- from cdktf import TerraformOutput
27
23
 
28
24
  # Import the base class
29
- from .LightsailBase import LightsailBase, BaseLightsailArchitectureFlags
25
+ from .LightsailBase import LightsailBase
26
+ from .LightsailFlags import DatabaseArchitectureFlags
27
+ from .LightsailMixins import LightsailDatabaseMixin
30
28
 
31
29
  #endregion
32
30
 
33
- #region AWS Provider and Resources
34
- from cdktf_cdktf_provider_aws import (
35
- lightsail_database,
36
- )
37
- #endregion
38
-
39
- #region Random Provider and Resources
40
- from cdktf_cdktf_provider_random import password
41
-
42
- #endregion
43
-
44
- #region Null Provider and Resources
45
- from cdktf_cdktf_provider_null.resource import Resource as NullResource
46
-
47
- #endregion
48
-
49
- #region ArchitectureFlags
50
- class ArchitectureFlags(Enum):
51
- """
52
- Architecture configuration flags for optional components.
31
+ ArchitectureFlags = DatabaseArchitectureFlags
53
32
 
54
- Includes both base flags and database-specific flags.
55
33
 
56
- Base flags:
57
- :param SKIP_DEFAULT_POST_APPLY_SCRIPTS: Skip default post-apply scripts
58
- :param PRESERVE_EXISTING_SECRETS: Don't overwrite existing secret versions (smart detection)
59
- :param IGNORE_SECRET_CHANGES: Ignore all changes to secret after initial creation
60
-
61
- Database-specific flags:
62
- :param SKIP_DATABASE_USERS: Skip creating individual database users (use master user only)
63
- """
64
-
65
- # Base flags from BaseLightsailArchitectureFlags
66
- SKIP_DEFAULT_POST_APPLY_SCRIPTS = "skip_default_post_apply_scripts"
67
- PRESERVE_EXISTING_SECRETS = "preserve_existing_secrets"
68
- IGNORE_SECRET_CHANGES = "ignore_secret_changes"
69
-
70
- # Database-specific flags
71
- SKIP_DATABASE_USERS = "skip_database_users"
72
-
73
- #endregion
74
-
75
-
76
- class LightsailDatabaseStack(LightsailBase):
34
+ class LightsailDatabaseStack(LightsailDatabaseMixin, LightsailBase):
77
35
  """
78
36
  AWS Lightsail Database Infrastructure Stack.
79
37
 
@@ -109,7 +67,7 @@ class LightsailDatabaseStack(LightsailBase):
109
67
  :returns: ArchitectureFlags enum class
110
68
  :rtype: type[ArchitectureFlags]
111
69
  """
112
- return ArchitectureFlags
70
+ return DatabaseArchitectureFlags
113
71
 
114
72
  def __init__(self, scope, id, **kwargs):
115
73
  """
@@ -161,324 +119,3 @@ class LightsailDatabaseStack(LightsailBase):
161
119
 
162
120
  # Call parent constructor (this will call _set_default_post_apply_scripts)
163
121
  super().__init__(scope, id, **kwargs)
164
-
165
- def _set_default_post_apply_scripts(self):
166
- """
167
- Set default post-apply scripts specific to database deployments.
168
- """
169
- # Call parent method for base scripts
170
- super()._set_default_post_apply_scripts()
171
-
172
- # Skip if flag is set
173
- if BaseLightsailArchitectureFlags.SKIP_DEFAULT_POST_APPLY_SCRIPTS.value in self.flags:
174
- return
175
-
176
- # Add database-specific scripts before the final message
177
- databases_list = ", ".join(self.databases)
178
- database_scripts = [
179
- f"echo '️ Database Instance: {self.project_name}-db'",
180
- f"echo '📊 Databases Created: {databases_list}'",
181
- f"echo '👥 Database Users: {len(self.databases)} individual users created'",
182
- "echo '🔗 Connection Information:'",
183
- "echo ' - Instance Endpoint: Available in Terraform outputs'",
184
- f"echo ' - Master User: {self.master_username}'",
185
- "echo ' - Port: 5432 (PostgreSQL)'",
186
- "echo ' - Credentials: Stored in AWS Secrets Manager'",
187
- ]
188
-
189
- # Insert database-specific scripts before the final "execution started" message
190
- if self.post_apply_scripts:
191
- # Find the index of the last script and insert before it
192
- insert_index = len(self.post_apply_scripts) - 1
193
- for script in reversed(database_scripts):
194
- self.post_apply_scripts.insert(insert_index, script)
195
-
196
- def create_lightsail_resources(self):
197
- """
198
- Create Lightsail-specific resources for database deployment.
199
-
200
- Creates:
201
- * Database passwords for master and individual users
202
- * Lightsail PostgreSQL database instance (with public access enabled)
203
- * Individual databases within the instance (automated via SQL)
204
- * Individual database users with scoped permissions (automated via SQL)
205
- """
206
- # Generate passwords first
207
- self.create_database_passwords()
208
-
209
- # Create the database instance
210
- self.create_lightsail_database()
211
-
212
- # Prepare database user credentials
213
- self.create_database_users()
214
-
215
- def create_database_passwords(self):
216
- """
217
- Generate secure passwords for master user and individual database users.
218
-
219
- Creates:
220
- * Master database password for the instance
221
- * Individual passwords for each database user
222
- * Stores passwords in internal dictionaries for later use
223
- """
224
- # Master database password
225
- self.master_password = password.Password(
226
- self, "master_db_password",
227
- length=20,
228
- special=True,
229
- override_special="!#$%&*()-_=+[]{}<>:?"
230
- )
231
-
232
- # Individual database user passwords
233
- for db_name in self.databases:
234
- db_password = password.Password(
235
- self, f"{db_name}_user_password",
236
- length=16,
237
- special=True,
238
- override_special="!#$%&*()-_=+[]{}<>:?"
239
- )
240
- self.database_passwords[db_name] = db_password
241
-
242
- def create_lightsail_database(self):
243
- """
244
- Create Lightsail PostgreSQL database instance.
245
-
246
- Creates a PostgreSQL database instance with the specified configuration.
247
- The instance will host multiple databases as specified in the databases parameter.
248
-
249
- Database Configuration:
250
- * Engine: PostgreSQL (version specified by db_engine)
251
- * Size: Configurable (default: micro_2_0)
252
- * Master database: Uses first database name from the list
253
- * Public Access: Configurable (default: True for automated provisioning)
254
- * Final snapshot: Disabled (skip_final_snapshot=True)
255
-
256
- .. note::
257
- Public access is enabled by default to allow automated database creation
258
- via local-exec provisioners. This can be disabled by setting
259
- db_publicly_accessible=False, but will require manual database setup.
260
- """
261
- # Use the first database name as the master database name
262
- master_db_name = self.clean_hyphens(self.databases[0])
263
-
264
- self.database = lightsail_database.LightsailDatabase(
265
- self,
266
- "database_instance",
267
- relational_database_name=f"{self.project_name}-db",
268
- blueprint_id=self.db_engine,
269
- bundle_id=self.db_instance_size,
270
- master_database_name=master_db_name,
271
- master_username=self.master_username,
272
- master_password=self.master_password.result,
273
- publicly_accessible=self.db_publicly_accessible,
274
- skip_final_snapshot=True,
275
- tags={
276
- "Environment": self.environment,
277
- "Project": self.project_name,
278
- "Stack": self.__class__.__name__,
279
- "DatabaseCount": str(len(self.databases))
280
- },
281
- )
282
-
283
- # Store database instance in resources registry
284
- self.resources["lightsail_database"] = self.database
285
-
286
- # Populate master credentials in secrets
287
- self.secrets.update({
288
- "master_username": self.master_username,
289
- "master_password": self.master_password.result,
290
- "master_database": master_db_name,
291
- "host": self.database.master_endpoint_address,
292
- "port": self.database.master_endpoint_port,
293
- "engine": self.db_engine,
294
- "region": self.region
295
- })
296
-
297
- def create_database_users(self):
298
- """
299
- Create individual databases and users within the Lightsail PostgreSQL instance.
300
-
301
- This method automates the creation of databases and users using SQL commands
302
- executed via null_resource provisioners. For each database in the databases list:
303
- 1. Generates a password for the database user
304
- 2. Stores credentials in the secrets dictionary
305
- 3. Creates the database (if not the first one - master database)
306
- 4. Creates a dedicated user with the generated password
307
- 5. Grants all privileges on the database to the user
308
-
309
- **Automated Database Setup:**
310
- The following operations are performed automatically for each database:
311
- * CREATE DATABASE {db_name};
312
- * CREATE USER "{db_name}-dbuser" WITH PASSWORD '{password}';
313
- * GRANT ALL PRIVILEGES ON DATABASE {db_name} TO "{db_name}-dbuser";
314
- * GRANT ALL ON SCHEMA public TO "{db_name}-dbuser";
315
-
316
- .. note::
317
- The first database in the list is created as the master database during
318
- instance creation, so it's skipped in this automated provisioning process.
319
-
320
- .. note::
321
- Requires publicly_accessible=True on the database instance for the
322
- provisioner to connect from the local machine running Terraform.
323
- """
324
- if ArchitectureFlags.SKIP_DATABASE_USERS.value in self.flags:
325
- return
326
-
327
- # Store credentials for all databases
328
- for db_name in self.databases:
329
- clean_db_name = self.clean_hyphens(db_name)
330
- username = f"{clean_db_name}-dbuser"
331
- password_ref = self.database_passwords[db_name].result
332
-
333
- # Store user credentials in secrets
334
- self.secrets[f"{clean_db_name}_username"] = username
335
- self.secrets[f"{clean_db_name}_password"] = password_ref
336
- self.secrets[f"{clean_db_name}_database"] = clean_db_name
337
-
338
- # Store in database_users for reference
339
- self.database_users[clean_db_name] = {
340
- "username": username,
341
- "password": password_ref,
342
- "database": clean_db_name
343
- }
344
-
345
- # Skip the first database as it's already created as the master database
346
- databases_to_create = self.databases[1:] if len(self.databases) > 1 else []
347
-
348
- # Create additional databases and users using null_resource
349
- for db_name in databases_to_create:
350
- clean_db_name = self.clean_hyphens(db_name)
351
- username = f"{clean_db_name}-dbuser"
352
- password_ref = self.database_passwords[db_name].result
353
-
354
- # SQL commands to create database and user
355
- # Using environment variables to avoid Terraform interpolation issues
356
- sql_commands = f"""#!/bin/bash
357
- set -e
358
-
359
- echo "Creating database: {clean_db_name}"
360
-
361
- # Wait for database to be ready (add retry logic)
362
- for i in {{1..30}}; do
363
- if PGPASSWORD="$MASTER_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -c "SELECT 1" > /dev/null 2>&1; then
364
- echo "Database is ready"
365
- break
366
- fi
367
- echo "Waiting for database to be ready... ($i/30)"
368
- sleep 10
369
- done
370
-
371
- # Create database
372
- PGPASSWORD="$MASTER_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -c "CREATE DATABASE \\"{clean_db_name}\\";" || echo "Database {clean_db_name} may already exist"
373
-
374
- # Create user
375
- PGPASSWORD="$MASTER_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -c "CREATE USER \\"{username}\\" WITH PASSWORD '$USER_PASSWORD';" || echo "User {username} may already exist"
376
-
377
- # Grant database privileges
378
- PGPASSWORD="$MASTER_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -c "GRANT ALL PRIVILEGES ON DATABASE \\"{clean_db_name}\\" TO \\"{username}\\";"
379
-
380
- # Grant schema privileges
381
- PGPASSWORD="$MASTER_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d {clean_db_name} -c "GRANT ALL ON SCHEMA public TO \\"{username}\\";"
382
-
383
- echo "Successfully created database: {clean_db_name} with user: {username}"
384
- """
385
-
386
- # Create null_resource to execute SQL commands
387
- db_resource = NullResource(
388
- self,
389
- f"create_database_{clean_db_name}",
390
- depends_on=[self.database]
391
- )
392
-
393
- # Add provisioner using override
394
- db_resource.add_override("provisioner", [{
395
- "local-exec": {
396
- "command": sql_commands,
397
- "environment": {
398
- "DB_HOST": self.database.master_endpoint_address,
399
- "DB_PORT": self.database.master_endpoint_port,
400
- "DB_USER": self.master_username,
401
- "MASTER_PASSWORD": self.master_password.result,
402
- "USER_PASSWORD": password_ref,
403
- }
404
- }
405
- }])
406
-
407
- def create_outputs(self):
408
- """
409
- Create Terraform outputs for important resource information.
410
-
411
- Generates outputs for:
412
- * Database instance endpoint
413
- * Master database credentials (sensitive)
414
- * Individual database credentials (sensitive)
415
- * IAM access keys (sensitive)
416
- * Database list and connection information
417
-
418
- .. note::
419
- Sensitive outputs are marked as such and will be hidden in
420
- Terraform output unless explicitly requested.
421
- """
422
- # Database instance outputs
423
- TerraformOutput(
424
- self,
425
- "database_endpoint",
426
- value=f"{self.database.master_endpoint_address}:{self.database.master_endpoint_port}",
427
- description="Database instance connection endpoint",
428
- )
429
-
430
- TerraformOutput(
431
- self,
432
- "database_instance_name",
433
- value=self.database.relational_database_name,
434
- description="Lightsail database instance name",
435
- )
436
-
437
- # Master credentials (sensitive)
438
- TerraformOutput(
439
- self,
440
- "master_username",
441
- value=self.master_username,
442
- description="Master database username",
443
- )
444
-
445
- TerraformOutput(
446
- self,
447
- "master_password",
448
- value=self.master_password.result,
449
- sensitive=True,
450
- description="Master database password (sensitive)",
451
- )
452
-
453
- # Database list
454
- TerraformOutput(
455
- self,
456
- "databases_created",
457
- value=json.dumps(self.databases),
458
- description="List of databases created in the instance",
459
- )
460
-
461
- # Individual database credentials (sensitive)
462
- if not self.has_flag(ArchitectureFlags.SKIP_DATABASE_USERS.value):
463
- for db_name in self.databases:
464
- clean_name = self.clean_hyphens(db_name)
465
- if clean_name in self.database_users:
466
- user_info = self.database_users[clean_name]
467
-
468
- TerraformOutput(
469
- self,
470
- f"{clean_name}_username",
471
- value=user_info["username"],
472
- description=f"Database user for {clean_name}",
473
- )
474
-
475
- TerraformOutput(
476
- self,
477
- f"{clean_name}_password",
478
- value=user_info["password"],
479
- sensitive=True,
480
- description=f"Database password for {clean_name} (sensitive)",
481
- )
482
-
483
- # Use the shared IAM output helper
484
- self.create_iam_outputs()