-
Notifications
You must be signed in to change notification settings - Fork 0
Create infra.ts #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
Terracotta detected changes in your CDK files. Running an initial plan and review of your changes – please hold on for a moment while we process your request. 🔍 Need help? View the Getting Started Guide |
In order to run a Terraform/CDK plan, a backend credential is required for this repository. Please add the appropriate credentials in the Terracotta app. 🔍 Need help? View How to Add Credentials |
🔍 What’s Wrong? The error Common reasons for this failure include:
✅ Recommended Fix To resolve this issue, ensure the following steps are explicitly performed and verifiable in your build or pipeline before Terraform analysis:
For TypeScript or JavaScript cdktf projects: cdktf synth For Python cdktf projects: cdktf synth This command generates the
Right after synthesis, run a check to confirm the file: test -f cdk.tf.json && echo "Synthesis successful" || echo "cdk.tf.json not found"
The Terraform plan or security linting tools should use this synthesized file, not the raw cdktf source code.
# Install dependencies
npm install # or pip install -r requirements.txt for Python
# Compile code (if TypeScript)
npm run build # optional and depends on your setup
# Synthesize Terraform
cdktf synth
# Confirm synthesis output
if [ ! -f cdk.tf.json ]; then
echo "cdk.tf.json not found. Synthesis failed."
exit 1
fi
# Run terraform commands (plan, validate, scan)
terraform init
terraform validate
terraform plan -input=false 🛡 Preventive Measures
Add unit or integration tests to your CI pipeline to confirm that
Use toolchain dependencies explicitly and document them in your pipeline manifests—e.g.,
Use tooling like
Incorporate file existence checks in the pipeline so failures are detected early and clearly.
Avoid running Terraform scans, plans, or applies on the source code directory. Always run them on the generated SummaryUse the following commands to produce the necessary Terraform config and avoid the npm install # or pip install dependencies
cdktf synth # generates cdk.tf.json
test -f cdk.tf.json && echo "Found cdk.tf.json" || exit 1
terraform init
terraform validate
terraform plan Integrate these steps systematically in your CI/CD to guarantee the Terraform review step can successfully analyze synthesized Terraform code. |
Terracotta detected changes in your CDK files. Running an initial plan and review of your changes – please hold on for a moment while we process your request. 🔍 Need help? View the Getting Started Guide |
In order to run a Terraform/CDK plan, a backend credential is required for this repository. Please add the appropriate credentials in the Terracotta app. 🔍 Need help? View How to Add Credentials |
🔍 What’s Wrong? The error Without ✅ Recommended Fix To resolve this issue, ensure that your workflow explicitly runs the synthesis step and verifies its success before attempting Terraform operations:
cdktf synth This command generates
if [ ! -s cdk.tf.json ]; then
echo "Error: cdk.tf.json not found or empty after synthesis."
exit 1
fi
terraform init
terraform validate
terraform plan 🛡 Preventive Measures
Production-Ready Synthesis and Terraform Workflow Snippet# Install dependencies
npm ci # or pip install -r requirements.txt for Python projects
# Run synthesis step
cdktf synth
# Validate synthesis output exists
if [ ! -f cdk.tf.json ]; then
echo "cdk.tf.json not found. CDKTF synthesis failed."
exit 1
fi
# Terraform lifecycle commands
terraform init
terraform validate
terraform plan -out=tfplan.binary Use the above snippet to ensure the Terraform review step always runs against generated Terraform JSON, resolving errors stemming from missing synthesized outputs. This authoritative sequence enforces a robust infrastructure IaC pipeline that prevents missing or incomplete synthesized Terraform configurations, guaranteeing that |
Terracotta detected changes in your CDK files. Running an initial plan and review of your changes – please hold on for a moment while we process your request. 🔍 Need help? View the Getting Started Guide |
In order to run a Terraform/CDK plan, a backend credential is required for this repository. Please add the appropriate credentials in the Terracotta app. 🔍 Need help? View How to Add Credentials |
🔍 What’s Wrong? The error This failure is typically caused by one or more of the following:
Without this JSON file, Terraform cannot proceed with validation, planning, or scanning, causing the review step to fail. ✅ Recommended Fix Implement the following CLI workflow to guarantee successful synthesis and Terraform review: # 1. Install dependencies
npm ci # or pip install -r requirements.txt for Python projects
# 2. Run build step (if applicable)
npm run build # For TypeScript projects with separate build step; omit if unnecessary
# 3. Run synthesis step to produce cdk.tf.json
cdktf synth
# 4. Validate cdk.tf.json presence and non-emptiness
if [ ! -s cdk.tf.json ]; then
echo "Error: cdk.tf.json file missing or empty after synthesis."
exit 1
fi
# 5. Initialize Terraform based on synthesized files
terraform init
# 6. Validate Terraform configuration syntax
terraform validate
# 7. Run Terraform plan (or static security scanning)
terraform plan -input=false Ensure that your CI pipeline or local workflow always runs the above steps in this order before attempting any Terraform plans or linting. This will make 🛡 Preventive Measures
Following this authoritative process ensures your Terraform review step has the required synthesized JSON files and avoids failures due to missing or invalid cdktf outputs. |
Terracotta detected changes in your CDK files. Running an initial plan and review of your changes – please hold on for a moment while we process your request. 🔍 Need help? View the Getting Started Guide |
In order to run a Terraform/CDK plan, a backend credential is required for this repository. Please add the appropriate credentials in the Terracotta app. 🔍 Need help? View How to Add Credentials |
🔍 What’s Wrong? The error message This situation commonly occurs because:
✅ Recommended Fix Use the following CLI sequence in your build and CI pipeline to guarantee that # 1. Install dependencies (adjust for your language)
npm ci # For TypeScript/JavaScript projects
# or
pip install -r requirements.txt # For Python projects
# 2. Build project (if applicable for TypeScript)
npm run build # Only if you have a separate build step
# 3. Execute synthesis to generate cdk.tf.json
cdktf synth
# 4. Validate the synthesized output presence and non-empty status
if [[ ! -s cdk.tf.json ]]; then
echo "Error: cdk.tf.json missing or empty after synthesis"
exit 1
fi
# 5. Initialize Terraform in the output directory
terraform init
# 6. Validate Terraform configuration
terraform validate
# 7. Run terraform plan or terraform security scans
terraform plan -input=false Make sure to invoke this command sequence within the working directory where your cdktf app and 🛡 Preventive Measures
This authoritative guidance guarantees the presence of |
🛡️ Security Analysis ResultsFound 8 security issues:
📋 Detailed Descriptions🔴 Public S3 bucket with disabled public access block settingsFile: Description: The S3 bucket is created with 💡 Recommendation: Remove 🔴 Security Group wide-open ingress ruleFile: Description: The security group 💡 Recommendation: Restrict the ingress rule to only the required IP ranges and ports. For example, use 🔴 IAM role with administrator-level managed policyFile: Description: The 💡 Recommendation: Define a custom IAM policy or attach only the specific AWS managed policies that grant the minimal set of permissions required for your application to function. 🔴 RDS instance is publicly accessibleFile: Description: The RDS instance is created with 💡 Recommendation: Set 🔴 RDS instance has storage encryption disabledFile: Description: The RDS instance is created with 💡 Recommendation: Enable encryption at rest by setting 🟡 S3 bucket missing server-side encryptionFile: Description: The S3 bucket is created without any server-side encryption configuration. Data at rest in S3 should always be encrypted to meet compliance and security requirements. 💡 Recommendation: Enable encryption by specifying 🟡 VPC created as raw resource with only public subnetsFile: Description: A raw 💡 Recommendation: Include 🔵 S3 bucket versioning is disabledFile: Description: Versioning is turned off for this bucket. Without versioning, accidental or malicious deletions/overwrites cannot be recovered. 💡 Recommendation: Consider enabling versioning by setting 📊 Summary
🤖 Analysis powered by Infrabase AI |
🔍 What’s Wrong? Your Terraform code synthesized via CDKTF is failing the review step because the file Separately, your infrastructure code (
Addressing the missing ✅ Recommended Fix
Make sure your project runs these commands in the project root where your cdktf app resides before the Terraform review step: # Install dependencies (adjust for your language)
npm ci # for TypeScript
# or
pip install -r requirements.txt # for Python
# Optional build step (TypeScript only)
npm run build # if you have a build script, else omit
# Run synthesis to generate cdk.tf.json
cdktf synth
# Confirm the synthesized output exists
if [[ ! -s cdk.tf.json ]]; then
echo "Error: cdk.tf.json missing or empty after synthesis"
exit 1
fi
# Afterwards, run terraform commands on the synthesized JSON
terraform init
terraform validate
terraform plan -input=false
Use the production-ready CDK patterns below to fix the critical issues in your import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as rds from 'aws-cdk-lib/aws-rds';
export class SecureStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// Secure S3 bucket with encryption and public access blocked
const bucket = new s3.Bucket(this, 'SecureBucket', {
bucketName: 'my-secure-bucket-001',
encryption: s3.BucketEncryption.S3_MANAGED, // Enable SSE-S3 encryption
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL, // Block all public access
versioned: true, // Enable versioning
removalPolicy: cdk.RemovalPolicy.RETAIN,
autoDeleteObjects: false,
});
// VPC with public + private isolated subnets for security
const vpc = new ec2.Vpc(this, 'SecureVpc', {
maxAzs: 2,
subnetConfiguration: [
{
cidrMask: 24,
name: 'public',
subnetType: ec2.SubnetType.PUBLIC,
},
{
cidrMask: 24,
name: 'private',
subnetType: ec2.SubnetType.PRIVATE_WITH_NAT,
},
],
});
// Security Group allowing only limited ingress (e.g., SSH from narrow IP)
const sg = new ec2.SecurityGroup(this, 'RestrictedSg', {
vpc,
description: 'Allow SSH from corporate CIDR',
allowAllOutbound: true,
});
sg.addIngressRule(
ec2.Peer.ipv4('203.0.113.0/24'), // Restrict to known IP range
ec2.Port.tcp(22),
'Allow SSH from trusted IP range'
);
// IAM role with least privilege policy example (no administrator access)
const role = new iam.Role(this, 'LeastPrivilegeRole', {
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
description: 'Role with scoped permissions',
});
const policy = new iam.Policy(this, 'ExamplePolicy', {
statements: [
new iam.PolicyStatement({
actions: ['s3:GetObject'],
resources: [bucket.bucketArn + '/*'],
}),
],
});
role.attachInlinePolicy(policy);
// RDS instance placed in private subnets with encryption enabled
new rds.DatabaseInstance(this, 'SecureDb', {
engine: rds.DatabaseInstanceEngine.postgres({
version: rds.PostgresEngineVersion.VER_15,
}),
vpc,
vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_WITH_NAT },
publiclyAccessible: false,
storageEncrypted: true,
allocatedStorage: 20,
credentials: rds.Credentials.fromGeneratedSecret('postgres'),
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
}
} 🛡 Preventive Measures
Following this approach ensures your CI pipeline produces valid Terraform artifacts for review, and your infrastructure code complies with best security practices to pass detailed security analysis in review steps. |
const bucket = new s3.Bucket(this, 'PublicBucket', { | ||
bucketName: 'my-public-bucket-001', | ||
publicReadAccess: true, | ||
blockPublicAccess: s3.BlockPublicAccess.NONE, // 🔴 no block-public-access settings | ||
versioned: false, | ||
removalPolicy: cdk.RemovalPolicy.DESTROY, | ||
autoDeleteObjects: true, | ||
}); |
Check failure
Code scanning / Infrabase AI
S3 Buckets Must Block Public Access Error
subnetConfiguration: [ | ||
{ name: 'public', subnetType: ec2.SubnetType.PUBLIC }, | ||
], | ||
maxAzs: 2, |
Check warning
Code scanning / Infrabase AI
No raw resources when possible Warning
|
||
const sg = new ec2.SecurityGroup(this, 'OpenSg', { | ||
vpc, |
Check failure
Code scanning / Infrabase AI
No raw resources when possible Error
}); | ||
sg.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.allTraffic(), 'Wide-open SG'); // 🔴 0.0.0.0/0 ALL | ||
|
||
/* 3️⃣ Wild-card IAM permissions */ | ||
const role = new iam.Role(this, 'OverPermissiveRole', { | ||
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'), | ||
description: 'Wild-card role for demo', |
Check failure
Code scanning / Infrabase AI
S3 Buckets Must Block Public Access Error
Terracotta detected changes in your CDK files. Running an initial plan and review of your changes – please hold on for a moment while we process your request. 🔍 Need help? View the Getting Started Guide |
In order to run a Terraform/CDK plan, a backend credential is required for this repository. Please add the appropriate credentials in the Terracotta app. 🔍 Need help? View How to Add Credentials |
🛡️ Security Analysis ResultsFound 6 security issues:
📋 Detailed Descriptions🔴 Public S3 bucket with no public access controls or encryptionFile: Description: In cdk-test/infra.ts (lines ~14-21), a new S3 bucket is created with publicReadAccess set to true, blockPublicAccess disabled, versioning off, and no server-side encryption. This exposes all objects to anonymous users and stores data unencrypted at rest. 💡 Recommendation: Remove publicReadAccess or scope it to a narrow set of principals. Enable BlockPublicAccess.BLOCK_ALL (or at minimum block public ACLs and policies), set the ACL to private, and configure server-side encryption (e.g. bucketEncryption: s3.BucketEncryption.S3_MANAGED). Enable versioning to protect against accidental deletes if appropriate. 🔴 Security Group open to all trafficFile: Description: In cdk-test/infra.ts (lines ~29-33), the security group "OpenSg" allows all inbound IPv4 traffic on all ports (0.0.0.0/0). This effectively exposes any resources in the VPC to the entire Internet. 💡 Recommendation: Restrict ingress rules to only the required ports and trusted CIDR ranges. For example, replace ec2.Peer.anyIpv4() and ec2.Port.allTraffic() with specific Port.tcp(portNumber) and your organization’s IP ranges. 🔴 Publicly accessible, unencrypted RDS instanceFile: Description: In cdk-test/infra.ts (lines ~43-50), an Amazon RDS instance is created with publiclyAccessible set to true, storageEncrypted disabled, and removalPolicy DESTROY. The database is exposed to the Internet and data at rest is unencrypted. 💡 Recommendation: Set publiclyAccessible to false unless absolutely required. Enable storageEncrypted: true and specify a KMS key if you need customer-managed encryption keys. Consider setting removalPolicy to RETAIN or enabling deletionProtection in production environments. 🟡 IAM Role granted AdministratorAccess wildcard permissionFile: Description: In cdk-test/infra.ts (lines ~36-40), the IAM role "OverPermissiveRole" is assigned the AWS-managed AdministratorAccess policy, granting broad privileges across all services and resources. 💡 Recommendation: Follow the principle of least privilege. Define a custom IAM policy or attach only the specific AWS-managed policies that grant the minimal set of actions and resources required by your workload. 🔵 Raw VPC resource instead of internal moduleFile: Description: In cdk-test/infra.ts (lines ~23-27), a VPC is created directly using ec2.Vpc. Your organization maintains an internal VPC module (git::https://github.com/diggerhq/common-modules//vpc) that enforces standard tagging, flow logging, and subnet layouts. 💡 Recommendation: Use the internal VPC module to ensure consistency: e.g., new ModuleVPC(this, 'MyVpc', { source: 'git::https://github.com/diggerhq/common-modules//vpc', /* module inputs */ }); ⚪ Destructive removal policies enabledFile: Description: In cdk-test/infra.ts (lines ~20 and ~50), both the S3 bucket and the RDS instance use removalPolicy: DESTROY. This configuration causes permanent data loss upon stack deletion. 💡 Recommendation: In non-development environments, use RemovalPolicy.RETAIN or enable snapshot/deletionProtection options to prevent accidental data loss. 📊 Summary
🤖 Analysis powered by Infrabase AI |
🔍 What’s Wrong? The Terraform review step failed because Additionally, your infrastructure code (
Fixing the missing ✅ Recommended Fix 1. Ensure Proper CDKTF Synthesis to Generate
|
🔍 What’s Wrong? The Terraform review step failed because the The root causes of this failure typically include:
✅ Recommended Fix To resolve this, enforce the following production-ready commands and workflow before the Terraform review step: # 1. Install project dependencies
npm ci # For TypeScript/JavaScript projects
# or
pip install -r requirements.txt # For Python projects
# 2. (If applicable) Build the project to transpile TypeScript to JavaScript
npm run build # Only needed if your project requires compilation before synth
# 3. Run synthesis to generate cdk.tf.json
cdktf synth
# 4. Confirm that cdk.tf.json exists and is not empty
if [[ ! -s cdk.tf.json ]]; then
echo "Error: cdk.tf.json not found or empty after synthesis."
exit 1
fi
# 5. Initialize Terraform in the synthesis output folder
terraform init
# 6. Validate the Terraform configuration
terraform validate
# 7. Run Terraform plan or security scanning tools
terraform plan -input=false Make sure that:
🛡 Preventive Measures
This authoritative approach guarantees your |
removalPolicy: cdk.RemovalPolicy.DESTROY, | ||
autoDeleteObjects: true, | ||
}); | ||
|
||
/* 2️⃣ VPC with a security group open to the world */ | ||
const vpc = new ec2.Vpc(this, 'MyVpc', { | ||
subnetConfiguration: [ | ||
{ name: 'public', subnetType: ec2.SubnetType.PUBLIC }, | ||
], | ||
maxAzs: 2, | ||
}); | ||
|
||
const sg = new ec2.SecurityGroup(this, 'OpenSg', { | ||
vpc, | ||
description: 'Allow all inbound traffic', | ||
allowAllOutbound: true, | ||
}); | ||
sg.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.allTraffic(), 'Wide-open SG'); // 🔴 0.0.0.0/0 ALL | ||
|
||
/* 3️⃣ Wild-card IAM permissions */ | ||
const role = new iam.Role(this, 'OverPermissiveRole', { | ||
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'), | ||
description: 'Wild-card role for demo', | ||
}); | ||
role.addManagedPolicy( | ||
iam.ManagedPolicy.fromAwsManagedPolicyName('AdministratorAccess'), // 🔴 * | ||
); | ||
|
||
/* 4️⃣ Public, unencrypted RDS instance */ | ||
new rds.DatabaseInstance(this, 'InsecureDb', { | ||
engine: rds.DatabaseInstanceEngine.postgres({ |
Check notice
Code scanning / Infrabase AI
No raw resources when possible Note
|
||
/* 2️⃣ VPC with a security group open to the world */ | ||
const vpc = new ec2.Vpc(this, 'MyVpc', { | ||
subnetConfiguration: [ | ||
{ name: 'public', subnetType: ec2.SubnetType.PUBLIC }, |
Check notice
Code scanning / Infrabase AI
No raw resources when possible Note
No description provided.