Infrastructure as Code: CloudFormation and CDK
Clicking in the console is fine for learning, but hard to repeat. Infrastructure as Code (IaC) describes your cloud setup in files. You can review it, keep it in Git, and create the same setup again in minutes.
Clicking through the console is fine once, but how do you build the same setup again for testing, or remember exactly what you changed? Infrastructure as Code keeps your cloud setup in files, so it can be reviewed, versioned in Git, and recreated reliably with one command. It's standard practice in professional cloud teams.
CloudFormation
AWS's built-in IaC service. You write a template (YAML or JSON); CloudFormation creates everything as one stack, and can update or delete it as a whole.
AWSTemplateFormatVersion: "2010-09-09"
Description: Bucket for product images
Parameters:
Env:
Type: String
AllowedValues: [dev, prod]
Resources:
ImagesBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "terixto-images-${Env}-${AWS::AccountId}"
VersioningConfiguration:
Status: Enabled
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
Outputs:
BucketName:
Value: !Ref ImagesBucketaws cloudformation deploy --template-file bucket.yaml --stack-name images-dev --parameter-overrides Env=devAWS CDK: infrastructure in a real programming language
The Cloud Development Kit lets you write infrastructure in TypeScript, Python, Java and more. It turns your code into CloudFormation for you, and its higher-level pieces set safe defaults.
// lib/shop-stack.ts (TypeScript CDK)
import * as cdk from 'aws-cdk-lib';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import { Construct } from 'constructs';
export class ShopStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const table = new dynamodb.Table(this, 'Products', {
partitionKey: { name: 'id', type: dynamodb.AttributeType.STRING },
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
});
const api = new lambda.Function(this, 'ProductsApi', {
runtime: lambda.Runtime.PYTHON_3_12,
handler: 'app.handler',
code: lambda.Code.fromAsset('lambda'),
environment: { TABLE_NAME: table.tableName },
});
table.grantReadWriteData(api); // the right IAM permissions in one line
new s3.Bucket(this, 'Images', { blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL });
}
}npm install -g aws-cdk
cdk init app --language typescript
cdk bootstrap # once per account and Region
cdk diff # see what will change
cdk deploy- IaC describes infrastructure in files you can version and review.
- CloudFormation uses YAML/JSON templates and stacks.
- CDK writes infrastructure in TypeScript, Python, Java and more.
