automation-deploy-template-iac
Version:
AWS CDK Infrastructure as Code templates for deploying full-stack applications with FastAPI backend, Vue.js frontend, and automated deployment
299 lines (220 loc) • 9.39 kB
Markdown
# Infrastructure as Code (IaC)
This directory contains AWS infrastructure definitions for the automation-deploy-template project.
## 📚 Documentation
### Essential Documentation
- **[Custom Container Configuration Guide](CUSTOM_CONTAINER_CONFIG_GUIDE.md)** ⭐ How to add custom secrets and environment variables
- **[Architecture Compliance Summary](ARCHITECTURE_COMPLIANCE_SUMMARY.md)** - Technical architecture details
### Deployment Guides
- [Frontend Deployment](FRONTEND_DEPLOYMENT_README.md)
- [Database Deployment](DATABASE_DEPLOYMENT_README.md)
- [Database Cleanup](DATABASE_CLEANUP_GUIDE.md)
## Overview
- **Network Stack**: VPC, subnets, NAT Gateway configuration
- **Database Stack**: RDS Aurora Serverless PostgreSQL configuration
- **Backend Stack**: ECS Fargate, ALB, ECR, SSL/TLS certificate configuration
- **Frontend Stack**: S3, CloudFront, Route53, SSL certificate configuration
- **Secrets Stack**: Custom secrets management with AWS Secrets Manager
## Prerequisites
- Node.js 18 or higher
- AWS CLI configured
- AWS CDK v2
## Setup
```bash
cd iac
npm install
npm run build
```
## GitHub Secrets Configuration
If using GitHub Actions for CI/CD deployment, configure the following secrets:
### 📋 Required Secrets
| Secret Name | Description | Example |
|----------|------|-----|
| `AWS_ROLE_TO_ASSUME` | IAM Role ARN for GitHub Actions | `arn:aws:iam::123456789012:role/GitHubActionsRole-AutomationDeploy` |
| `AWS_REGION` | AWS Region | `ap-northeast-1` |
### 🔧 Optional Secrets
| Secret Name | Description | Example | Purpose |
|----------|------|-----|------|
| `ROOT_DOMAIN` | Root domain name | `yourdomain.com` | Deploy with custom domain (subdomains automatically generated per environment) |
> **Important**: Do **NOT** set `BACKEND_DOMAIN_NAME` or `FRONTEND_DOMAIN_NAME`.
> They are automatically generated from `ROOT_DOMAIN`.
### 📡 Automatic Domain Generation per Environment
When `ROOT_DOMAIN` is set, domains are **automatically generated** in the following format:
#### Dev Environment
- Backend: `devapi.{ROOT_DOMAIN}` (e.g., `devapi.yourdomain.com`)
- Frontend: `dev.{ROOT_DOMAIN}` (e.g., `dev.yourdomain.com`)
#### Stg Environment
- Backend: `stgapi.{ROOT_DOMAIN}` (e.g., `stgapi.yourdomain.com`)
- Frontend: `stg.{ROOT_DOMAIN}` (e.g., `stg.yourdomain.com`)
#### Prod Environment
- Backend: `api.{ROOT_DOMAIN}` (e.g., `api.yourdomain.com`)
- Frontend: `{ROOT_DOMAIN}` (e.g., `yourdomain.com`)
### 🚫 Secrets NOT to Configure
Do **NOT** configure the following secrets (they are auto-generated from `ROOT_DOMAIN`):
- `BACKEND_DOMAIN_NAME` ❌
- `FRONTEND_DOMAIN_NAME` ❌
- `DOMAIN_NAME` ❌
### 🔄 Automatic CORS Configuration
When `ROOT_DOMAIN` is set, the following are automatically configured:
#### Backend (ECS) Environment Variables
```bash
# Automatically generated environment variables
CORS_IS_LOCAL=false # Always false in cloud environment
CORS_DOMAINS=dev.yourdomain.com,stg.yourdomain.com,yourdomain.com # Auto-generated per environment
CORS_ALLOW_CREDENTIALS=true
CORS_MAX_AGE=600
```
### 🔐 Adding Custom Secrets and Environment Variables
You can add custom secrets and environment variables to your ECS containers.
#### 📖 Detailed Guide
**See [Custom Container Configuration Guide](CUSTOM_CONTAINER_CONFIG_GUIDE.md)**
#### ✨ Key Features
- ✅ **Automatic Secret Discovery** - No command line arguments needed
- ✅ **Multiple Secrets Support** - Load from 2, 3, or more AWS Secrets Manager entries
- ✅ **Add Environment Variables** - Add custom environment variables
- ✅ **Merge or Override** - Supplement defaults or completely replace them
- ✅ **Type Safe** - Full TypeScript support
#### 🚀 Quick Start
```bash
# 1. Deploy SecretsStack (automatically creates test secrets)
cdk deploy MyProject-dev-Secrets
# 2. Deploy BackendStack (auto-discovers secrets)
cdk deploy MyProject-dev-BackendStack
```
Secrets are automatically discovered and loaded!
#### 📝 Usage Example
```typescript
import {
CustomSecretsRequests,
ContainerConfigRequests
} from 'automation-deploy-template-iac';
// Define secrets to load (adapter handles the actual loading)
const customSecretsRequests = CustomSecretsRequests.buildFromMultiple([
{
secretName: 'myapp-dev-api-keys',
keyMappings: [
{ envVarName: 'STRIPE_API_KEY', secretKey: 'stripe-api-key' },
{ envVarName: 'SENDGRID_API_KEY', secretKey: 'sendgrid-api-key' },
]
}
]);
// Add custom environment variables
const containerConfigRequests = ContainerConfigRequests.build(
{
LOG_LEVEL: 'debug',
FEATURE_FLAG_ENABLED: 'true',
},
customSecretsRequests
);
// Use in BackendStack
new BackendStack(app, 'MyBackendStack', {
containerConfigRequests, // Add your custom configuration
// ... other properties
});
```
For detailed examples and advanced usage, see the [complete guide](CUSTOM_CONTAINER_CONFIG_GUIDE.md).
#### Frontend (Build Time) Environment Variables
```bash
# Provided as CDK Output
VITE_BACKEND_DOMAIN=api.yourdomain.com # Auto-generated per environment
VITE_IS_LOCAL=false # Always false in cloud environment
VITE_BACKEND_PORT= # Empty string in cloud environment
```
### 🛠️ GitHub Secrets Configuration Steps
1. Click the **Settings** tab on your GitHub repository page
2. Click **Secrets and variables** → **Actions** in the left sidebar
3. Click the **New repository secret** button
4. Add each of the above secret names and values one by one
### 📝 Creating IAM Role
The IAM role for GitHub Actions can be created using `iac/cloudformation/github-actions-role.yaml`:
```bash
# Create IAM role with CloudFormation
aws cloudformation create-stack \
--stack-name github-actions-automation-deploy \
--template-body file://iac/cloudformation/github-actions-role.yaml \
--parameters \
ParameterKey=GitHubOrganization,ParameterValue=YOUR_GITHUB_USERNAME \
ParameterKey=GitHubRepository,ParameterValue=automation-deploy-template \
ParameterKey=AllowedBranches,ParameterValue=main \
--capabilities CAPABILITY_NAMED_IAM
```
Set the ARN of the created role to the `AWS_ROLE_TO_ASSUME` secret.
## Deployment
### 1. Deploy Network Stack
```bash
# Development environment (standard configuration)
npx cdk deploy dev-NetworkStack --app "node bin/network.js" --context environment=dev --context costLevel=standard
# Production environment (high-availability configuration)
npx cdk deploy prod-NetworkStack --app "node bin/network.js" --context environment=prod --context costLevel=high-availability
```
### 2. Deploy Backend Stack
```bash
# Development environment
npx cdk deploy dev-BackendStack --app "node bin/backend.js" --context environment=dev --context rootDomain=yourdomain.com
# Production environment
npx cdk deploy prod-BackendStack --app "node bin/backend.js" --context environment=prod --context rootDomain=yourdomain.com
```
> **Note**: When `rootDomain` is specified, it is automatically generated per environment as follows:
> - Dev: `devapi.yourdomain.com`
> - Prod: `api.yourdomain.com`
### 3. Deploy Frontend Stack
#### Deploy Using Script (Recommended)
```bash
# Deploy to development environment
./deploy-frontend.sh dev deploy standard
# Deploy to staging environment
./deploy-frontend.sh stg deploy standard
# Deploy to production environment (high-availability configuration)
./deploy-frontend.sh prod deploy high-availability
```
#### Manual CDK Deploy
```bash
# Development environment
npx cdk deploy dev-FrontendStack --app "node bin/frontend.js" --context environment=dev --context rootDomain=yourdomain.com
# Production environment
npx cdk deploy prod-FrontendStack --app "node bin/frontend.js" --context environment=prod --context rootDomain=yourdomain.com
```
> **Note**: When `rootDomain` is specified, it is automatically generated per environment as follows:
> - Dev: `dev.yourdomain.com`
> - Prod: `yourdomain.com`
> **🚀 Fully Automated**: Frontend deployment automatically handles everything from SSL certificate creation to Route53 configuration just by specifying the domain name!
For details, see [FRONTEND_DEPLOYMENT_README.md](./FRONTEND_DEPLOYMENT_README.md).
## Cost Levels
### minimal
- Public subnets only
- No NAT Gateway
- CloudFront Price Class: 100 (North America & Europe only)
- Minimum cost
### standard
- Public + Private subnets
- NAT Gateway x1
- CloudFront Price Class: 200 (includes Asia Pacific)
- Balanced
### high-availability
- Public + Private subnets
- NAT Gateway x2 (per AZ)
- CloudFront Price Class: ALL (all regions)
- High availability
## Environment Variables
### Common
- `ENVIRONMENT`: dev, stg, prod
- `COST_LEVEL`: minimal, standard, high-availability
- `AWS_REGION`: ap-northeast-1
### Backend
- `ROOT_DOMAIN`: Root domain name (optional) - Backend domain is auto-generated per environment
### Frontend
- `ROOT_DOMAIN`: Root domain name (optional) - Frontend domain is auto-generated per environment
## Troubleshooting
### Build Errors
```bash
npm run clean
npm run build
```
### Stack Deletion
```bash
# Delete frontend stack
npx cdk destroy dev-FrontendStack --app "node bin/frontend.js"
# Delete backend stack
npx cdk destroy dev-BackendStack --app "node bin/backend.js"
# Delete network stack (delete last)
npx cdk destroy dev-NetworkStack --app "node bin/network.js"
```