Skip to main content

Infrastructure as Code Concepts

What is IaC?​

Infrastructure as Code (IaC) is the practice of managing and provisioning infrastructure through configuration files rather than manual processes.

┌─────────────────────────────────────────────────────────────┐
│ IaC vs MANUAL │
├─────────────────────────────────────────────────────────────┤
│ │
│ MANUAL PROVISIONING │
│ ─────────────────── │
│ 1. Open AWS console │
│ 2. Click "Launch Instance" │
│ 3. Manually configure... │
│ 4. Repeat for each resource │
│ 5. Document the parameters │
│ │
│ Problems: │
│ ❌ Non-reproducible │
│ ❌ Human errors │
│ ❌ No versioning │
│ ❌ Outdated documentation │
│ ❌ Difficult to audit │
│ │
│ ──────────────────────────────────────────────────────── │
│ │
│ INFRASTRUCTURE AS CODE │
│ ────────────────────── │
│ 1. Write a template (YAML/JSON) │
│ 2. Version in Git │
│ 3. Deploy with CloudFormation │
│ 4. Automate via CI/CD │
│ │
│ Advantages: │
│ ✅ Reproducible (same result every time) │
│ ✅ Versioned (complete history) │
│ ✅ Code review (peer review) │
│ ✅ Living documentation (the code IS the doc) │
│ ✅ Automatable (CI/CD) │
│ │
└─────────────────────────────────────────────────────────────┘

AWS CloudFormation​

Overview​

┌─────────────────────────────────────────────────────────────┐
│ CLOUDFORMATION │
├─────────────────────────────────────────────────────────────┤
│ │
│ COMPONENTS: │
│ │
│ ┌─────────────┐ │
│ │ TEMPLATE │ YAML/JSON file describing │
│ │ (code) │ the desired infrastructure │
│ └──────┬──────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ STACK │ Instance of a template │
│ │ │ with real resources │
│ └──────┬──────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ AWS RESOURCES │ │
│ │ │ │
│ │ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ │ │
│ │ │ VPC │ │ EC2 │ │ RDS │ │ ALB │ │ SG │ │ │
│ │ └─────┘ └─────┘ └─────┘ └─────┘ └─────┘ │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ LIFECYCLE: │
│ Create → Update → Delete │
│ (or Rollback if error) │
│ │
└─────────────────────────────────────────────────────────────┘

Template Structure​

Sections​

AWSTemplateFormatVersion: "2010-09-09"
Description: Template description

# 1. PARAMETERS - Input variables
Parameters:
EnvironmentType:
Type: String
Default: dev
AllowedValues: [dev, staging, prod]

# 2. MAPPINGS - Lookup tables
Mappings:
RegionAMI:
us-east-1:
AMI: ami-0123456789

# 3. CONDITIONS - Conditional logic
Conditions:
IsProd: !Equals [!Ref EnvironmentType, prod]

# 4. RESOURCES - Resources to create (REQUIRED)
Resources:
MyEC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: !FindInMap [RegionAMI, !Ref "AWS::Region", AMI]
InstanceType: t3.micro

# 5. OUTPUTS - Exported values
Outputs:
InstanceId:
Value: !Ref MyEC2Instance
Export:
Name: MyInstanceId

Common Resource Types​

TypeDescription
AWS::EC2::InstanceEC2 Instance
AWS::EC2::VPCVPC
AWS::EC2::SubnetSubnet
AWS::EC2::SecurityGroupSecurity Group
AWS::RDS::DBInstanceRDS Database
AWS::S3::BucketS3 Bucket
AWS::Lambda::FunctionLambda Function
AWS::ElasticLoadBalancingV2::LoadBalancerALB/NLB

Intrinsic Functions​

Most Used​

Resources:
# !Ref - Reference a parameter or resource
MyInstance:
Type: AWS::EC2::Instance
Properties:
InstanceType: !Ref InstanceType # Parameter
SubnetId: !Ref MySubnet # Resource

# !GetAtt - Get an attribute of a resource
MyDNSRecord:
Type: AWS::Route53::RecordSet
Properties:
Name: app.example.com
ResourceRecords:
- !GetAtt MyInstance.PublicIp # Public IP of the instance

# !Sub - Variable substitution
MyBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "${AWS::StackName}-${AWS::Region}-data"

# !Join - Concatenate values
MyTag:
Type: AWS::EC2::Instance
Properties:
Tags:
- Key: Name
Value: !Join ["-", [web, !Ref EnvironmentType, server]]

# !If - Condition
MyVolume:
Type: AWS::EC2::Volume
Properties:
Size: !If [IsProd, 100, 20] # 100 GB in prod, 20 otherwise

# !FindInMap - Lookup in Mappings
MyInstance2:
Type: AWS::EC2::Instance
Properties:
ImageId: !FindInMap [RegionAMI, !Ref "AWS::Region", AMI]

Complete Example: Web Infrastructure​

AWSTemplateFormatVersion: "2010-09-09"
Description: Simple web infrastructure with EC2 and Security Group

Parameters:
Environment:
Type: String
Default: dev
AllowedValues: [dev, staging, prod]
Description: Environment name

InstanceType:
Type: String
Default: t3.micro
AllowedValues: [t3.micro, t3.small, t3.medium]

KeyName:
Type: AWS::EC2::KeyPair::KeyName
Description: EC2 Key Pair for SSH access

Mappings:
RegionAMI:
us-east-1:
AMI: ami-0c55b159cbfafe1f0
eu-west-1:
AMI: ami-0d729a60

Resources:
# Security Group
WebSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Allow HTTP and SSH
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0
Tags:
- Key: Name
Value: !Sub "${Environment}-web-sg"
- Key: Environment
Value: !Ref Environment

# EC2 Instance
WebServer:
Type: AWS::EC2::Instance
Properties:
ImageId: !FindInMap [RegionAMI, !Ref "AWS::Region", AMI]
InstanceType: !Ref InstanceType
KeyName: !Ref KeyName
SecurityGroupIds:
- !Ref WebSecurityGroup
Tags:
- Key: Name
Value: !Sub "${Environment}-web-server"
- Key: Environment
Value: !Ref Environment
UserData:
Fn::Base64: |
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1>Hello from CloudFormation!</h1>" > /var/www/html/index.html

Outputs:
InstanceId:
Description: Instance ID
Value: !Ref WebServer
Export:
Name: !Sub "${Environment}-WebServerId"

PublicIP:
Description: Public IP address
Value: !GetAtt WebServer.PublicIp

WebsiteURL:
Description: URL of the website
Value: !Sub "http://${WebServer.PublicIp}"

CLI Commands​

# Validate a template
aws cloudformation validate-template \
--template-body file://template.yaml

# Create a stack
aws cloudformation create-stack \
--stack-name my-web-stack \
--template-body file://template.yaml \
--parameters \
ParameterKey=Environment,ParameterValue=dev \
ParameterKey=KeyName,ParameterValue=my-key

# View stack status
aws cloudformation describe-stacks \
--stack-name my-web-stack

# View events (debug)
aws cloudformation describe-stack-events \
--stack-name my-web-stack

# Update a stack
aws cloudformation update-stack \
--stack-name my-web-stack \
--template-body file://template.yaml \
--parameters \
ParameterKey=Environment,ParameterValue=staging

# Delete a stack
aws cloudformation delete-stack \
--stack-name my-web-stack

Best Practices​

┌─────────────────────────────────────────────────────────────┐
│ CLOUDFORMATION BEST PRACTICES │
├─────────────────────────────────────────────────────────────┤
│ │
│ ✅ DO │
│ ──────── │
│ • Version templates in Git │
│ • Use parameters for flexibility │
│ • Add clear descriptions │
│ • Use meaningful logical names │
│ • Validate before deploying │
│ • Use Change Sets for preview │
│ • Tag all resources │
│ │
│ ❌ AVOID │
│ ───────── │
│ • Hardcoding values (AMIs, IPs...) │
│ • Creating monolithic templates (> 500 lines) │
│ • Ignoring validation errors │
│ • Deploying without code review │
│ • Forgetting outputs for references │
│ │
└─────────────────────────────────────────────────────────────┘

Summary​

ConceptDescription
TemplateYAML/JSON file describing the infrastructure
StackDeployed instance of a template
ParametersConfigurable input variables
ResourcesAWS resources to create
OutputsExported values for reference
!RefReference a resource or parameter
!GetAttGet an attribute of a resource

Next section: CloudFormation Lab