robisson/build-like-amazon-agent-skills/infrastructure-as-code

Claude Code and agent skill by robisson/build-like-amazon-agent-skills

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

CDK/CloudFormation design principles for immutable infrastructure, environment parity, least privilege, tagging strategy, and cost optimization. Infrastructure is code—it deserves the same rigor as application code.

Install

npx vskill@latest install robisson/build-like-amazon-agent-skills/infrastructure-as-code

SKILL.md

The same SKILL.md was published earlier as robisson/build-like-amazon-agent-skills/infrastructure-as-code.

Infrastructure as Code

Overview

Infrastructure as Code (IaC) means every piece of infrastructure—compute, storage, networking, permissions, monitoring—is defined in version-controlled code that can be reviewed, tested, and deployed through the same pipeline as application code. There is no "clicking in the console." There are no snowflake environments. The code IS the infrastructure, and the infrastructure IS the code.

Immutable infrastructure means you never patch in place. You replace. A server is never SSH'd into and modified; it is destroyed and rebuilt from the code. This eliminates configuration drift, makes deployments predictable, and ensures every environment is reproducible.

When to Use

  • Always. All infrastructure must be defined in code. There are no exceptions.
  • When creating a new service or microservice
  • When modifying any infrastructure component (networking, IAM, storage, compute)
  • When setting up a new environment (dev, staging, production)
  • When responding to an incident that requires infrastructure changes
  • When optimizing costs (changes must be in code so they're reproducible and reviewable)

Amazon Context

At Amazon, teams own their infrastructure end-to-end. There is no separate "ops team" that provisions resources. The team that builds the service provisions, deploys, monitors, and operates the infrastructure. CDK (Cloud Development Kit) and CloudFormation are the primary tools, with CDK preferred for new projects because it provides type safety, composition, and testing capabilities that raw CloudFormation templates lack.

Infrastructure changes go through the same code review and deployment pipeline as application code. A CDK change that modifies IAM permissions gets the same scrutiny as a code change that handles authentication. In many ways, it deserves MORE scrutiny—a bad IAM policy can expose the entire account.

The Process

1. Immutable Infrastructure
Principles
  • Never modify running infrastructure. To change a server's configuration, create a new server with the new configuration and destroy the old one.
  • No SSH in production. If you need to SSH in, your automation is incomplete. Fix the automation.
  • Identical artifacts across environments. The same AMI/container image deployed to dev is deployed to production. Only configuration (env vars, secrets references) differs.
  • Rebuild from scratch regularly. If you can't destroy and recreate your entire environment from code in under an hour, your IaC is incomplete.
Implementation
typescript
// CDK Example: Immutable deployment via Auto Scaling Group
const asg = new autoscaling.AutoScalingGroup(this, 'ServiceASG', {
instanceType: ec2.InstanceType.of(ec2.InstanceClass.M5, ec2.InstanceSize.LARGE),
machineImage: ec2.MachineImage.lookup({
name: `service-ami-${props.buildId}`, // New AMI per build
}),
updatePolicy: autoscaling.UpdatePolicy.rollingUpdate({
maxBatchSize: 1,
minInstancesInService: 2,
pauseTime: Duration.minutes(5),
}),
});
2. Environment Parity
The Rule

Production, staging, and development environments must be structurally identical. They differ only in:

  • Scale (instance count, storage size)
  • Configuration values (endpoints, account IDs)
  • Data (production has real data; lower environments have synthetic data)

They must NOT differ in:

  • Architecture (same services, same topology)
  • Security posture (same IAM structure, same encryption)
  • Networking model (same VPC design, same security groups)
  • Monitoring (same metrics, same alarms—different thresholds are acceptable)
Implementation
typescript
// CDK Example: Environment parity through parameterization
interface EnvironmentConfig {
readonly envName: string;
readonly instanceCount: number;
readonly instanceType: ec2.InstanceType;
readonly alarmThreshold: number;
readonly retentionDays: number;
}
const environments: Record<string, EnvironmentConfig> = {
dev: {
envName: 'dev',
instanceCount: 1,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MEDIUM),
alarmThreshold: 5000,
retentionDays: 7,
},
staging: {
envName: 'staging',
instanceCount: 2,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.M5, ec2.InstanceSize.LARGE),
alarmThreshold: 2000,
retentionDays: 30,
},
production: {
envName: 'production',
instanceCount: 6,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.M5, ec2.InstanceSize.XLARGE),
alarmThreshold: 1000,
retentionDays: 365,
},
};
// Same stack, different config — structural parity guaranteed
new ServiceStack(app, `Service-${config.envName}`, { config });
3. Least Privilege
IAM Design Principles
  1. Start with zero permissions. Add only what's needed, one permission at a time.
  2. Scope to specific resources. Never use Resource: "*" unless there is no alternative.
  3. Use conditions. Restrict by source IP, time, MFA, tags, or organization.
  4. Prefer managed policies for AWS services. Custom policies for application-specific access.
  5. Separate read and write roles. A service that reads from DynamoDB and writes to S3 should have separate role assumptions if possible.
  6. Time-bound elevated access. Admin access should be temporary (STS assume-role with session duration).
Common Violations and Fixes
typescript
// ❌ WRONG: Overly broad permissions
const badPolicy = new iam.PolicyStatement({
actions: ['dynamodb:*'],
resources: ['*'],
});
// ✅ RIGHT: Least privilege
const goodPolicy = new iam.PolicyStatement({
actions: [
'dynamodb:GetItem',
'dynamodb:PutItem',
'dynamodb:Query',
],
resources: [
table.tableArn,
`${table.tableArn}/index/*`,
],
conditions: {
'ForAllValues:StringEquals': {
'dynamodb:LeadingKeys': ['${aws:PrincipalTag/TenantId}'],
},
},
});
IAM Review Checklist
  • [ ] No Action: "*" (wildcard actions)
  • [ ] No Resource: "*" without documented justification
  • [ ] No inline policies on IAM users (use roles)
  • [ ] Cross-account access uses external ID condition
  • [ ] Service roles have trust policy scoped to specific service principal
  • [ ] Admin access requires MFA and has session time limit
  • [ ] Permissions boundaries are applied to delegated admin roles
4. Tagging Strategy
Mandatory Tags

Every resource must have these tags (enforced by Service Control Policy):

Tag KeyDescriptionExample Values
serviceService name (matches repo name)payment-processing
environmentDeployment environmentdev, staging, production
teamOwning team namepayments-core
cost-centerFinance cost allocation codeCC-12345
data-classificationData sensitivity levelpublic, internal, confidential, restricted
managed-byIaC tool managing this resourcecdk, cloudformation, terraform
Enforcement
typescript
// CDK Example: Enforce tags at the stack level
Tags.of(app).add('service', props.serviceName);
Tags.of(app).add('environment', props.environment);
Tags.of(app).add('team', props.teamName);
Tags.of(app).add('cost-center', props.costCenter);
Tags.of(app).add('managed-by', 'cdk');
// CDK Nag: Fail deployment if tags are missing
Aspects.of(app).add(new TagEnforcementAspect(REQUIRED_TAGS));
Tag-Based Policies
  • Cost allocation: All cost reports filter by service and team tags
  • Access control: IAM policies use aws:ResourceTag conditions
  • Automation: Auto-shutdown of dev resources uses environment: dev tag
  • Compliance: Audit queries use data-classification tag to verify encryption
5. Cost Optimization
Design-Time Cost Decisions
DecisionCost ImpactGuideline
Instance type40-60% of compute costRight-size based on actual metrics, not guesses. Start small, scale up.
Storage class20-50% of storage costUse lifecycle policies: hot → warm → cold → archive
Reserved vs. On-Demand30-60% savingsReserve steady-state baseline; On-Demand for burst
Region selection10-30% variationUse cheapest region that meets latency requirements
Data transferOften overlookedKeep data in same AZ/region where possible; use VPC endpoints
Cost Guardrails in Code
typescript
// CDK Example: Cost guardrails
class CostGuardrailAspect implements IAspect {
visit(node: IConstruct) {
// Prevent expensive instance types in non-prod
if (node instanceof ec2.CfnInstance) {
if (props.environment !== 'production') {
const instanceType = node.instanceType;
if (EXPENSIVE_INSTANCE_TYPES.includes(instanceType)) {
Annotations.of(node).addError(
`Instance type ${instanceType} not allowed in ${props.environment}. Use t3/t4g family.`
);
}
}
}
// Ensure DynamoDB tables use on-demand in dev, provisioned in prod
if (node instanceof dynamodb.CfnTable) {
if (props.environment === 'production' && !node.billingMode) {
Annotations.of(node).addWarning(
'Production DynamoDB tables should use PROVISIONED billing with auto-scaling for cost predictability.'
);
}
}
}
}
Cost Monitoring
  • Budget alarms: Set per-service monthly budget with alerts at 50%, 80%, 100%
  • Anomaly detection: AWS Cost Anomaly Detection enabled per-service tag
  • Weekly review: Automated cost report per team, compared to previous week
  • Unused resource detection: Automated scan for unattached EBS, idle EC2, empty S3 buckets
6. CDK Best Practices
Project Structure
infrastructure/
├── bin/
│ └── app.ts # Entry point, environment selection
├── lib/
│ ├── constructs/ # Reusable L3 constructs
│ │ ├── monitored-lambda.ts # Lambda + alarms + dashboard
│ │ ├── secure-bucket.ts # S3 + encryption + lifecycle
│ │ └── api-gateway.ts # APIGW + WAF + logging
│ ├── stacks/
│ │ ├── networking-stack.ts # VPC, subnets, security groups
│ │ ├── data-stack.ts # DynamoDB, S3, ElastiCache
│ │ ├── compute-stack.ts # Lambda, ECS, ASG
│ │ └── monitoring-stack.ts # Dashboards, alarms, SNS
│ └── config/
│ ├── dev.ts
│ ├── staging.ts
│ └── production.ts
├── test/
│ ├── unit/ # Snapshot + fine-grained tests
│ └── integration/ # Deployed stack verification
└── cdk.json
Testing Infrastructure Code
typescript
// Snapshot test: Detect unintended changes
test('infrastructure matches snapshot', () => {
const app = new App();
const stack = new ServiceStack(app, 'TestStack', { config: testConfig });
expect(Template.fromStack(stack)).toMatchSnapshot();
});
// Fine-grained assertion: Verify specific properties
test('DynamoDB table has encryption enabled', () => {
const template = Template.fromStack(stack);
template.hasResourceProperties('AWS::DynamoDB::Table', {
SSESpecification: {
SSEEnabled: true,
SSEType: 'KMS',
},
});
});
// Security assertion: No public S3 buckets
test('no public S3 buckets', () => {
const template = Template.fromStack(stack);
template.hasResourceProperties('AWS::S3::Bucket', {
PublicAccessBlockConfiguration: {
BlockPublicAcls: true,
BlockPublicPolicy: true,
IgnorePublicAcls: true,
RestrictPublicBuckets: true,
},
});
});
Construct Composition
  • L1 (Cfn): Raw CloudFormation. Use only when L2 doesn't exist.
  • L2: AWS-opinionated defaults. Use as building blocks.
  • L3 (Custom): Your team's opinionated constructs. Encode your standards.

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/robisson/build-like-amazon-agent-skills/infrastructure-as-code/badge)](https://verified-skill.com/skills/robisson/build-like-amazon-agent-skills/infrastructure-as-code)

Something wrong with this skill or its page? Tell us.