BuzzerboyAWSLightsail 0.329.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,405 @@
1
+ """
2
+ AWS Lightsail Database Infrastructure Stack
3
+ ==========================================
4
+
5
+ This module provides a specialized AWS Lightsail database deployment stack
6
+ using CDKTF (Cloud Development Kit for Terraform) with Python.
7
+
8
+ The stack includes:
9
+ * Lightsail Database instance (PostgreSQL)
10
+ * Multiple databases within the instance
11
+ * Individual database users with scoped permissions
12
+ * Secrets Manager for credential storage per database
13
+ * IAM resources for service access
14
+
15
+ :author: Generated with GitHub Copilot
16
+ :version: 1.0.0
17
+ :license: MIT
18
+ """
19
+
20
+ #region specific imports
21
+
22
+ import os
23
+ import json
24
+ from enum import Enum
25
+ from constructs import Construct
26
+ from cdktf import TerraformOutput
27
+
28
+ # Import the base class
29
+ from .LightsailBase import LightsailBase, BaseLightsailArchitectureFlags
30
+
31
+ #endregion
32
+
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 ArchitectureFlags
45
+ class ArchitectureFlags(BaseLightsailArchitectureFlags):
46
+ """
47
+ Architecture configuration flags for optional components.
48
+
49
+ Extends BaseLightsailArchitectureFlags with database-specific flags.
50
+
51
+ :param SKIP_DATABASE_USERS: Skip creating individual database users (use master user only)
52
+ """
53
+
54
+ SKIP_DATABASE_USERS = "skip_database_users"
55
+
56
+ #endregion
57
+
58
+
59
+ class LightsailDatabaseStack(LightsailBase):
60
+ """
61
+ AWS Lightsail Database Infrastructure Stack.
62
+
63
+ A comprehensive database stack that deploys:
64
+ * Lightsail Database instance with PostgreSQL
65
+ * Multiple databases within the instance
66
+ * Individual database users with scoped permissions
67
+ * Secrets Manager for storing all database credentials
68
+ * IAM resources for programmatic access
69
+
70
+ :param scope: The construct scope
71
+ :param id: The construct ID
72
+ :param kwargs: Configuration parameters including databases array
73
+
74
+ Example:
75
+ >>> stack = LightsailDatabaseStack(
76
+ ... app, "my-db-stack",
77
+ ... region="ca-central-1",
78
+ ... project_name="my-app",
79
+ ... databases=["app_db", "analytics_db", "logs_db"],
80
+ ... postApplyScripts=[
81
+ ... "echo 'Database deployment completed'",
82
+ ... "psql -h $DB_HOST -U master -d postgres -c '\\l'"
83
+ ... ]
84
+ ... )
85
+ """
86
+
87
+ @staticmethod
88
+ def get_architecture_flags():
89
+ """
90
+ Get the ArchitectureFlags enum for configuration.
91
+
92
+ :returns: ArchitectureFlags enum class
93
+ :rtype: type[ArchitectureFlags]
94
+ """
95
+ return ArchitectureFlags
96
+
97
+ def __init__(self, scope, id, **kwargs):
98
+ """
99
+ Initialize the AWS Lightsail Database Infrastructure Stack.
100
+
101
+ :param scope: The construct scope
102
+ :param id: Unique identifier for this stack
103
+ :param kwargs: Configuration parameters
104
+
105
+ **Configuration Parameters:**
106
+
107
+ :param region: AWS region (default: "us-east-1")
108
+ :param environment: Environment name (default: "dev")
109
+ :param project_name: Project identifier (default: "bb-aws-lightsail-db")
110
+ :param databases: List of database names to create (required)
111
+ :param flags: List of ArchitectureFlags to modify behavior
112
+ :param profile: AWS profile to use (default: "default")
113
+ :param postApplyScripts: List of shell commands to execute after deployment
114
+ :param secret_name: Custom secret name (default: "{project_name}/{environment}/database-credentials")
115
+ :param db_instance_size: Database instance size (default: "micro_2_0")
116
+ :param db_engine: Database engine version (default: "postgres_14")
117
+ :param master_username: Master database username (default: "dbmasteruser")
118
+ """
119
+ # Set database-specific defaults
120
+ if "project_name" not in kwargs:
121
+ kwargs["project_name"] = "bb-aws-lightsail-db"
122
+ if "secret_name" not in kwargs:
123
+ project_name = kwargs["project_name"]
124
+ environment = kwargs.get("environment", "dev")
125
+ kwargs["secret_name"] = f"{project_name}/{environment}/database-credentials"
126
+
127
+ # Call parent constructor
128
+ super().__init__(scope, id, **kwargs)
129
+
130
+ # ===== Database-Specific Configuration =====
131
+ self.databases = kwargs.get("databases", [])
132
+
133
+ # Validate required parameters
134
+ if not self.databases:
135
+ raise ValueError("The 'databases' parameter is required and must contain at least one database name")
136
+
137
+ # ===== Database Configuration =====
138
+ self.master_username = kwargs.get("master_username", "dbmasteruser")
139
+ self.db_instance_size = kwargs.get("db_instance_size", "micro_2_0")
140
+ self.db_engine = kwargs.get("db_engine", "postgres_14")
141
+
142
+ # ===== Internal State =====
143
+ self.database_users = {}
144
+ self.database_passwords = {}
145
+
146
+ def _set_default_post_apply_scripts(self):
147
+ """
148
+ Set default post-apply scripts specific to database deployments.
149
+ """
150
+ # Call parent method for base scripts
151
+ super()._set_default_post_apply_scripts()
152
+
153
+ # Skip if flag is set
154
+ if BaseLightsailArchitectureFlags.SKIP_DEFAULT_POST_APPLY_SCRIPTS.value in self.flags:
155
+ return
156
+
157
+ # Add database-specific scripts before the final message
158
+ databases_list = ", ".join(self.databases)
159
+ database_scripts = [
160
+ f"echo '️ Database Instance: {self.project_name}-db'",
161
+ f"echo '📊 Databases Created: {databases_list}'",
162
+ f"echo '👥 Database Users: {len(self.databases)} individual users created'",
163
+ "echo '🔗 Connection Information:'",
164
+ "echo ' - Instance Endpoint: Available in Terraform outputs'",
165
+ f"echo ' - Master User: {self.master_username}'",
166
+ "echo ' - Port: 5432 (PostgreSQL)'",
167
+ "echo ' - Credentials: Stored in AWS Secrets Manager'",
168
+ ]
169
+
170
+ # Insert database-specific scripts before the final "execution started" message
171
+ if self.post_apply_scripts:
172
+ # Find the index of the last script and insert before it
173
+ insert_index = len(self.post_apply_scripts) - 1
174
+ for script in reversed(database_scripts):
175
+ self.post_apply_scripts.insert(insert_index, script)
176
+
177
+ def create_lightsail_resources(self):
178
+ """
179
+ Create Lightsail-specific resources for database deployment.
180
+
181
+ Creates:
182
+ * Database passwords for master and individual users
183
+ * Lightsail PostgreSQL database instance
184
+ * Individual database user credentials (for later manual creation)
185
+ """
186
+ # Generate passwords first
187
+ self.create_database_passwords()
188
+
189
+ # Create the database instance
190
+ self.create_lightsail_database()
191
+
192
+ # Prepare database user credentials
193
+ self.create_database_users()
194
+
195
+ def create_database_passwords(self):
196
+ """
197
+ Generate secure passwords for master user and individual database users.
198
+
199
+ Creates:
200
+ * Master database password for the instance
201
+ * Individual passwords for each database user
202
+ * Stores passwords in internal dictionaries for later use
203
+ """
204
+ # Master database password
205
+ self.master_password = password.Password(
206
+ self, "master_db_password",
207
+ length=20,
208
+ special=True,
209
+ override_special="!#$%&*()-_=+[]{}<>:?"
210
+ )
211
+
212
+ # Individual database user passwords
213
+ for db_name in self.databases:
214
+ db_password = password.Password(
215
+ self, f"{db_name}_user_password",
216
+ length=16,
217
+ special=True,
218
+ override_special="!#$%&*()-_=+[]{}<>:?"
219
+ )
220
+ self.database_passwords[db_name] = db_password
221
+
222
+ def create_lightsail_database(self):
223
+ """
224
+ Create Lightsail PostgreSQL database instance.
225
+
226
+ Creates a PostgreSQL database instance with the specified configuration.
227
+ The instance will host multiple databases as specified in the databases parameter.
228
+
229
+ Database Configuration:
230
+ * Engine: PostgreSQL (version specified by db_engine)
231
+ * Size: Configurable (default: micro_2_0)
232
+ * Master database: Uses first database name from the list
233
+ * Final snapshot: Disabled (skip_final_snapshot=True)
234
+ """
235
+ # Use the first database name as the master database name
236
+ master_db_name = self.clean_hyphens(self.databases[0])
237
+
238
+ self.database = lightsail_database.LightsailDatabase(
239
+ self,
240
+ "database_instance",
241
+ relational_database_name=f"{self.project_name}-db",
242
+ blueprint_id=self.db_engine,
243
+ bundle_id=self.db_instance_size,
244
+ master_database_name=master_db_name,
245
+ master_username=self.master_username,
246
+ master_password=self.master_password.result,
247
+ skip_final_snapshot=True,
248
+ tags={
249
+ "Environment": self.environment,
250
+ "Project": self.project_name,
251
+ "Stack": self.__class__.__name__,
252
+ "DatabaseCount": str(len(self.databases))
253
+ },
254
+ )
255
+
256
+ # Store database instance in resources registry
257
+ self.resources["lightsail_database"] = self.database
258
+
259
+ # Populate master credentials in secrets
260
+ self.secrets.update({
261
+ "master_username": self.master_username,
262
+ "master_password": self.master_password.result,
263
+ "master_database": master_db_name,
264
+ "host": self.database.master_endpoint_address,
265
+ "port": self.database.master_endpoint_port,
266
+ "engine": self.db_engine,
267
+ "region": self.region
268
+ })
269
+
270
+ def create_database_users(self):
271
+ """
272
+ Prepare database user credentials for individual databases.
273
+
274
+ This method creates credentials for individual database users that would be
275
+ created manually or via external scripts after deployment. For each database
276
+ in the databases list, it will:
277
+ 1. Generate a password for the database user
278
+ 2. Store credentials in the secrets dictionary
279
+ 3. Create user information for reference
280
+
281
+ **Manual Database Setup Required:**
282
+ After deployment, you'll need to manually create databases and users:
283
+ * CREATE DATABASE {db_name};
284
+ * CREATE USER "{db_name}-dbuser" WITH PASSWORD '{password}';
285
+ * GRANT ALL PRIVILEGES ON DATABASE {db_name} TO "{db_name}-dbuser";
286
+
287
+ .. note::
288
+ Database and user creation happens manually after deployment since
289
+ Lightsail doesn't provide Terraform resources for individual databases.
290
+ """
291
+ if ArchitectureFlags.SKIP_DATABASE_USERS.value in self.flags:
292
+ return
293
+
294
+ for db_name in self.databases:
295
+ clean_db_name = self.clean_hyphens(db_name)
296
+ username = f"{clean_db_name}-dbuser"
297
+ password_ref = self.database_passwords[db_name].result
298
+
299
+ # Store user credentials in secrets
300
+ self.secrets[f"{clean_db_name}_username"] = username
301
+ self.secrets[f"{clean_db_name}_password"] = password_ref
302
+ self.secrets[f"{clean_db_name}_database"] = clean_db_name
303
+
304
+ # Store in database_users for reference
305
+ self.database_users[clean_db_name] = {
306
+ "username": username,
307
+ "password": password_ref,
308
+ "database": clean_db_name
309
+ }
310
+
311
+ # Add manual setup instructions to post-terraform messages
312
+ if self.databases and not self.has_flag(ArchitectureFlags.SKIP_DATABASE_USERS.value):
313
+ setup_commands = []
314
+ for db_name in self.databases:
315
+ clean_db_name = self.clean_hyphens(db_name)
316
+ username = f"{clean_db_name}-dbuser"
317
+ setup_commands.extend([
318
+ f"CREATE DATABASE IF NOT EXISTS \"{clean_db_name}\";",
319
+ f"CREATE USER \"{username}\" WITH PASSWORD '<password_from_secrets>';",
320
+ f"GRANT ALL PRIVILEGES ON DATABASE \"{clean_db_name}\" TO \"{username}\";"
321
+ ])
322
+
323
+ self.post_terraform_messages.append(
324
+ f"Manual database setup required. Connect to the database instance and run:\n" +
325
+ "\n".join(setup_commands)
326
+ )
327
+
328
+ def create_outputs(self):
329
+ """
330
+ Create Terraform outputs for important resource information.
331
+
332
+ Generates outputs for:
333
+ * Database instance endpoint
334
+ * Master database credentials (sensitive)
335
+ * Individual database credentials (sensitive)
336
+ * IAM access keys (sensitive)
337
+ * Database list and connection information
338
+
339
+ .. note::
340
+ Sensitive outputs are marked as such and will be hidden in
341
+ Terraform output unless explicitly requested.
342
+ """
343
+ # Database instance outputs
344
+ TerraformOutput(
345
+ self,
346
+ "database_endpoint",
347
+ value=f"{self.database.master_endpoint_address}:{self.database.master_endpoint_port}",
348
+ description="Database instance connection endpoint",
349
+ )
350
+
351
+ TerraformOutput(
352
+ self,
353
+ "database_instance_name",
354
+ value=self.database.relational_database_name,
355
+ description="Lightsail database instance name",
356
+ )
357
+
358
+ # Master credentials (sensitive)
359
+ TerraformOutput(
360
+ self,
361
+ "master_username",
362
+ value=self.master_username,
363
+ description="Master database username",
364
+ )
365
+
366
+ TerraformOutput(
367
+ self,
368
+ "master_password",
369
+ value=self.master_password.result,
370
+ sensitive=True,
371
+ description="Master database password (sensitive)",
372
+ )
373
+
374
+ # Database list
375
+ TerraformOutput(
376
+ self,
377
+ "databases_created",
378
+ value=json.dumps(self.databases),
379
+ description="List of databases created in the instance",
380
+ )
381
+
382
+ # Individual database credentials (sensitive)
383
+ if not self.has_flag(ArchitectureFlags.SKIP_DATABASE_USERS.value):
384
+ for db_name in self.databases:
385
+ clean_name = self.clean_hyphens(db_name)
386
+ if clean_name in self.database_users:
387
+ user_info = self.database_users[clean_name]
388
+
389
+ TerraformOutput(
390
+ self,
391
+ f"{clean_name}_username",
392
+ value=user_info["username"],
393
+ description=f"Database user for {clean_name}",
394
+ )
395
+
396
+ TerraformOutput(
397
+ self,
398
+ f"{clean_name}_password",
399
+ value=user_info["password"],
400
+ sensitive=True,
401
+ description=f"Database password for {clean_name} (sensitive)",
402
+ )
403
+
404
+ # Use the shared IAM output helper
405
+ self.create_iam_outputs()
File without changes
@@ -0,0 +1,191 @@
1
+ Metadata-Version: 2.4
2
+ Name: BuzzerboyAWSLightsail
3
+ Version: 0.329.1
4
+ Summary: Buzzerboy Architecture for Deploying Web Applications on AWS LightSail
5
+ Home-page: https://www.buzzerboy.com/
6
+ Author: Buzzerboy Inc
7
+ Author-email: Buzzerboy Inc <info@buzzerboy.com>
8
+ Project-URL: Homepage, https://www.buzzerboy.com/
9
+ Project-URL: Issues, https://dev.azure.com/buzzerboyinc/buzzerboy
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.8
14
+ Description-Content-Type: text/markdown
15
+ Requires-Dist: cdktf<1.0,>=0.17.0
16
+ Requires-Dist: constructs<11.0,>=10.0.0
17
+ Requires-Dist: cdktf-cdktf-provider-aws>=12.0.0
18
+ Requires-Dist: cdktf-cdktf-provider-random>=8.0.0
19
+ Requires-Dist: toml
20
+ Requires-Dist: pipenv
21
+ Requires-Dist: boto3>=1.26.0
22
+ Requires-Dist: botocore>=1.29.0
23
+ Requires-Dist: BuzzerboyArchetype
24
+ Requires-Dist: AWSArchitectureBase
25
+ Dynamic: author
26
+ Dynamic: home-page
27
+ Dynamic: requires-dist
28
+ Dynamic: requires-python
29
+
30
+ # AWS Infrastructure with CDKTF (Python)
31
+
32
+ This project uses the **Cloud Development Kit for Terraform (CDKTF)** with **Python** to define and deploy AWS infrastructure using named AWS profiles via `~/.aws/credentials` and `~/.aws/config`.
33
+
34
+ ---
35
+
36
+ ## ✅ Prerequisites
37
+
38
+ ### 1. Install Required Tools
39
+
40
+ Make sure the following tools are installed:
41
+
42
+ * **Node.js** (v16 or later)
43
+ * **npm**
44
+ * **Terraform CLI**
45
+ * **Python 3.7+**
46
+ * **AWS CLI**
47
+
48
+ #### macOS Example:
49
+
50
+ ```bash
51
+ brew install node
52
+ brew install terraform
53
+ brew install python
54
+ brew install awscli
55
+ ```
56
+
57
+ ### 2. Install CDKTF CLI
58
+
59
+ ```bash
60
+ npm install -g cdktf-cli
61
+ ```
62
+
63
+ ### 3a. Configure AWS CLI (Option 1 - Use AWS Provided Tooling)
64
+
65
+ ```bash
66
+ aws configure --profile myprofile
67
+ ```
68
+
69
+ This creates or updates the following files:
70
+
71
+ `~/.aws/credentials`:
72
+
73
+ ```ini
74
+ [myprofile]
75
+ aws_access_key_id=YOUR_ACCESS_KEY
76
+ aws_secret_access_key=YOUR_SECRET_KEY
77
+ ```
78
+
79
+ `~/.aws/config`:
80
+
81
+ ```ini
82
+ [profile myprofile]
83
+ region=us-west-2
84
+ output=json
85
+ ```
86
+
87
+
88
+ ### 3b. Configure AWS CLI (Option 2 - Use Open Source AWS Login - Recommended)
89
+
90
+
91
+ #### 3b - 1. Clone the code repo from Fahad Zain Jawaid
92
+ ```bash
93
+ git clone https://github.com/fahadzainjawaid/awsIdentityTools
94
+ ```
95
+
96
+ You can follow the ReadMe on the repo above to get latest usage and setup guides.
97
+
98
+ ---
99
+
100
+ ## 🚀 Getting Started
101
+
102
+ ### 1. Install the package
103
+
104
+ ```bash
105
+ pip install pip install BBAWSLightsailMiniV1a
106
+ ```
107
+
108
+ ### 2. Set Up Python Environment & Install Dependencies
109
+
110
+ ```bash
111
+ python3 -m venv .venv
112
+ source .venv/bin/activate
113
+ export PIPENV_VERBOSITY=-1
114
+ pip install -r requirements.txt
115
+ ```
116
+
117
+ ### 3. Install AWS Provider Bindings
118
+
119
+ ```bash
120
+ cdktf get
121
+ ```
122
+
123
+ ### 4. Synthesize Terraform Configuration
124
+
125
+ ```bash
126
+ cdktf synth
127
+ ```
128
+
129
+ ### 5. Review the Plan
130
+
131
+ ```bash
132
+ cdktf plan
133
+ ```
134
+
135
+ ### 6. Deploy the Infrastructure
136
+
137
+ ```bash
138
+ cdktf deploy
139
+ ```
140
+
141
+ ### 7. Destroy the Infrastructure (if needed)
142
+
143
+ ```bash
144
+ cdktf destroy
145
+ ```
146
+
147
+ ## 🛠 Useful Commands
148
+
149
+ | Command | Description |
150
+ | --------------- | ------------------------------- |
151
+ | `cdktf get` | Install provider bindings |
152
+ | `cdktf synth` | Generate Terraform JSON config |
153
+ | `cdktf plan` | Preview planned changes |
154
+ | `cdktf deploy` | Deploy infrastructure to AWS |
155
+ | `cdktf destroy` | Destroy deployed infrastructure |
156
+
157
+ ---
158
+
159
+ ## 📁 .gitignore Suggestions
160
+
161
+ ```gitignore
162
+ .venv/
163
+ cdktf.out/
164
+ .terraform/
165
+ __pycache__/
166
+ *.pyc
167
+ ```
168
+
169
+ ---
170
+
171
+ ## 📝 Notes
172
+
173
+ * To install additional Python packages:
174
+
175
+ ```bash
176
+ pip install <package>
177
+ pip freeze > requirements.txt
178
+ ```
179
+
180
+ * To suppress pipenv verbosity in environments where pipenv is used:
181
+
182
+ ```bash
183
+ export PIPENV_VERBOSITY=-1
184
+ ```
185
+
186
+ ---
187
+
188
+ ## 📚 References
189
+
190
+ * [CDK for Terraform Documentation](https://developer.hashicorp.com/terraform/cdktf)
191
+ * [AWS Provider Docs](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)
@@ -0,0 +1,10 @@
1
+ BuzzerboyAWSLightsailStack/LightSailPostDeploy.py,sha256=uOEOe5qORPgvivC0Ba0w045PQztfS6z-ynwyikaPQzI,5025
2
+ BuzzerboyAWSLightsailStack/LightsailAIContainer.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ BuzzerboyAWSLightsailStack/LightsailBase.py,sha256=YfQrFNHvdWxGgpgy1A2CgAD2R5fz_ebQyVaADZaxCPw,25946
4
+ BuzzerboyAWSLightsailStack/LightsailContainer.py,sha256=_PvA5fMFEHdlI-jATcDTOAOs6R0MHwBj5Hjudh4SMxI,13314
5
+ BuzzerboyAWSLightsailStack/LightsailDatabase.py,sha256=hffRjVbYADV7SK5cD4orwt0etb-pTDxtQvEv58iQyyI,15425
6
+ BuzzerboyAWSLightsailStack/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ buzzerboyawslightsail-0.329.1.dist-info/METADATA,sha256=CXKk9RZiVbGDaQksYC_7spEH2HqjlK5I2-ORAbpdPj4,3839
8
+ buzzerboyawslightsail-0.329.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
+ buzzerboyawslightsail-0.329.1.dist-info/top_level.txt,sha256=xqYoH36d7_13q4vRi5bZr1zIz9mR7b8ms_6ez3BqRgQ,27
10
+ buzzerboyawslightsail-0.329.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ BuzzerboyAWSLightsailStack