# Automation and IaC: CloudFormation, CDK and Systems Manager

Deploy a template as a CloudFormation stack, preview updates with a change set, catch manual edits with drift detection, and know where CDK and Systems Manager fit.

Course: [AWS for DevOps](https://devops.rajeev.pro/courses/aws), lesson 16. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/aws/16-automation-and-iac

## What you will learn

- Write a CloudFormation template with parameters, resources and outputs
- Deploy it as a stack and read its events, resources and template
- Preview an update with a change set before executing it
- Find manual changes with drift detection
- Know when to use CDK, Terraform, and Systems Manager Run Command, Session Manager and Patch Manager
- Place CodeBuild, CodePipeline and CodeDeploy next to GitHub Actions

## Why not click

Lessons 3 to 5 built servers, networks and load balancers by clicking. Clicking doesn't scale: you can't review
it, repeat it in another Region, or know what changed last Tuesday. **Infrastructure as code** describes
resources in files that live in git, go through pull requests, and deploy the same way every time.

With code, a change starts as a diff someone can review. The deployment tool compares that desired description
with the current account, then creates or updates the resources needed to match. That gives the team a repeatable
record, but not a guarantee that every change is safe: review replacements, permissions and data retention
before approving. In this lesson, you'll use CloudFormation, inspect its change set and drift views, then compare
it with CDK, Terraform and Systems Manager.

On AWS you have two families:

| Tool               | Writes                        | Deploys through                                      |
| ------------------ | ----------------------------- | ---------------------------------------------------- |
| **CloudFormation** | YAML or JSON templates        | CloudFormation stacks                                |
| **AWS CDK**        | TypeScript, Python, Java, Go… | generates CloudFormation                             |
| **Terraform**      | HCL                           | its own engine and state file (the Terraform course) |

This lesson uses CloudFormation, because it's built in and everything else on AWS builds on it. Everything
below ran in a real account and was deleted afterwards.

## A template

```yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: DevOps Academy - a versioned bucket and a config parameter
Parameters:
  Environment:
    Type: String
    AllowedValues: [dev, prod]
    Default: dev
Resources:
  AssetsBucket:
    Type: AWS::S3::Bucket
    Properties:
      VersioningConfiguration:
        Status: Enabled
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
  LogLevelParam:
    Type: AWS::SSM::Parameter
    Properties:
      Name: !Sub /academy/${Environment}/log-level
      Type: String
      Value: info
Outputs:
  BucketName:
    Value: !Ref AssetsBucket
```

| Section      | Holds                                                        |
| ------------ | ------------------------------------------------------------ |
| `Parameters` | inputs, so one template serves dev and prod                  |
| `Resources`  | what to create: a logical ID, a `Type`, and its `Properties` |
| `Outputs`    | values to show or pass to other stacks                       |

`!Ref` and `!Sub` are **intrinsic functions**: `!Ref AssetsBucket` becomes the bucket's real name, and
`!Sub` fills `${Environment}` into the string. No bucket name is set, so CloudFormation generates a unique one.

The logical ID (`AssetsBucket`) is the name used inside the template. CloudFormation maps it to a physical
resource name in the account. Parameters let one template accept a value such as `dev` or `prod`, while intrinsic
functions connect resource properties to those values and other resources. Outputs make selected results visible
after deployment. This separation is useful when the same reviewed structure is deployed to more than one
environment. Keep resource definitions explicit and avoid putting credentials in template parameters; pass secret
references instead. The template is the desired state, and the stack is CloudFormation's managed deployment of it.

## Deploy it as a stack

```sh
$ aws cloudformation validate-template --template-body file://stack.yaml --query 'Parameters[].ParameterKey' --output text
Environment
$ aws cloudformation create-stack --stack-name academy-iac --template-body file://stack.yaml \
    --parameters ParameterKey=Environment,ParameterValue=dev
$ aws cloudformation wait stack-create-complete --stack-name academy-iac
$ aws cloudformation describe-stacks --stack-name academy-iac --query 'Stacks[0].[StackStatus,Outputs[0].OutputValue]' --output text
CREATE_COMPLETE	academy-iac-assetsbucket-2hizm9a4hixg
```

> **Figure.** CloudFormation stack academy-iac, Events tab: the stack and each resource going from CREATE_IN_PROGRESS to CREATE_COMPLETE, with the final CREATE_COMPLETE for the stack highlighted.
>
> The Events tab: every step CloudFormation took, newest first. Read it bottom-up when something fails.

> **Figure.** Resources tab of academy-iac: (1) AssetsBucket, an AWS::S3::Bucket with its generated physical ID, and (2) LogLevelParam, an AWS::SSM::Parameter named /academy/dev/log-level, both CREATE_COMPLETE.
>
> (1) The bucket and (2) the parameter, each with the logical ID from the template and the real (physical) ID AWS gave it.

> **Figure.** Template tab of academy-iac showing the YAML template that created the stack.
>
> The stack keeps the exact template it was deployed from.

If a resource fails to create, CloudFormation **rolls back**: it deletes everything it made in that attempt, so
you're never left with half a stack. The reason is in the Events tab, on the first `CREATE_FAILED` line.

## Change sets: preview before you change

Edit the template: add a tag to the bucket and change the log level to `warn`. Then ask CloudFormation what it
would do, without doing it:

```sh
$ aws cloudformation create-change-set --stack-name academy-iac --change-set-name add-tag-warn-logs \
    --template-body file://stack-v2.yaml --parameters ParameterKey=Environment,UsePreviousValue=true
$ aws cloudformation describe-change-set --stack-name academy-iac --change-set-name add-tag-warn-logs \
    --query 'Changes[].ResourceChange.[Action,LogicalResourceId,Replacement]' --output text
Modify	AssetsBucket	False
Modify	LogLevelParam	False
```

> **Figure.** Change set add-tag-warn-logs for academy-iac: both AssetsBucket and LogLevelParam with action (1) Modify and replacement False. (2) The Execute change set button.
>
> (1) Both resources will be modified in place, nothing replaced. (2) Execute change set applies it.

The column to read is **Replacement**. Some property changes can't be done in place, so CloudFormation creates a
new resource and deletes the old one: for a database, that means a new, empty database. A change set is how you
see that before it happens.

```sh
$ aws cloudformation execute-change-set --stack-name academy-iac --change-set-name add-tag-warn-logs
$ aws cloudformation wait stack-update-complete --stack-name academy-iac
$ aws ssm get-parameter --name /academy/dev/log-level --query Parameter.Value --output text
warn
```

> **Video.** [AWS CloudFormation Change Sets : How to Update Your Resources Easily and Efficiently](https://www.youtube.com/watch?v=jP0bii0O7u8) (AC)

> **Figure.** A CloudFormation template in Git describes the resources. Step one, a change is proposed in a pull request and reviewed like code. Step two, CloudFormation creates a change set that lists what will be added, modified or replaced, before anything changes. Step three, executing the change set updates the stack academy-iac, which owns its resources, such as an S3 bucket and an IAM role. If someone edits a resource by hand in the console, drift detection shows the difference between the stack and reality.
>
> Review the template, preview the change set, then update the stack. Drift detection catches console edits.

## Drift: when someone clicks in the console

Now someone "quickly fixes" the value by hand, outside the template:

```sh
$ aws ssm put-parameter --name /academy/dev/log-level --value debug --overwrite
$ DID=$(aws cloudformation detect-stack-drift --stack-name academy-iac --query StackDriftDetectionId --output text)
$ aws cloudformation describe-stack-resource-drifts --stack-name academy-iac \
    --query 'StackResourceDrifts[].[LogicalResourceId,StackResourceDriftStatus]' --output text
AssetsBucket	IN_SYNC
LogLevelParam	MODIFIED
```

> **Figure.** Drifts page of academy-iac: stack drift status DRIFTED. Resource drift status: AssetsBucket IN_SYNC and LogLevelParam MODIFIED, both highlighted.
>
> (1) The parameter changed by hand is MODIFIED. (2) The bucket still matches the template.

Drift is a problem waiting for the next deploy: the next update sets `warn` again and the manual fix silently
disappears. Either put the change in the template, or undo it. In production, block console edits of
stack-managed resources with IAM, and run drift detection on a schedule.

> **Video.** [AWS CloudFormation - How to Detect Drift?](https://www.youtube.com/watch?v=uqIYUfaDWHo) (JasCloudTech)

## CDK and Terraform

**AWS CDK** writes the same stack in a programming language:

```ts
const bucket = new s3.Bucket(this, 'AssetsBucket', {
  versioned: true,
  blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
});
new ssm.StringParameter(this, 'LogLevelParam', {
  parameterName: `/academy/${props.environment}/log-level`,
  stringValue: 'info',
});
```

`cdk synth` turns it into a CloudFormation template and `cdk deploy` deploys it as a stack, with change sets
behind the scenes. Its constructs bundle good defaults (like Block Public Access above), and loops and functions
replace copy-paste. **Terraform** works across clouds and keeps its own state; teams that already use it for
GitHub, Cloudflare or Datadog often use it for AWS too. Pick one per team and stick to it.

CDK is a higher-level authoring language, not a separate AWS deployment engine: `cdk synth` produces a
CloudFormation template that you can inspect before deployment. Constructs can encode defaults and repeated
patterns, but you still need to review the synthesized output. Terraform follows a different model and records
managed resources in its state so later plans can compare code with the account. Sharing one resource between
both tools can cause ownership conflicts. Choose the tool your team can review, test and operate, and keep a clear
single owner for each resource.

## Systems Manager: run the fleet

IaC creates servers; **AWS Systems Manager** works on them once they run, through the SSM agent that Amazon Linux
already has (the instance needs a role with `AmazonSSMManagedInstanceCore`):

| Feature             | Does                                                                                                     |
| ------------------- | -------------------------------------------------------------------------------------------------------- |
| **Run Command**     | runs a document (such as `AWS-RunShellScript`) on many instances at once, by tag, and records the output |
| **Session Manager** | a shell in the browser or CLI with no SSH port or keys (lesson 3), every session logged                  |
| **Patch Manager**   | scans and installs OS patches on a schedule, by patch baseline and maintenance window                    |
| **Parameter Store** | configuration values like `/academy/dev/log-level` (lesson 15 covers secrets)                            |

```sh
$ aws ssm send-command --document-name AWS-RunShellScript --targets Key=tag:Name,Values=academy-web \
    --parameters 'commands=["systemctl is-active nginx"]'
```

Systems Manager is the operations layer after provisioning. The SSM agent checks in using the instance's role;
then Run Command can target managed instances without opening an SSH port. A tag target lets you address a
group, but a broad target can run a command on more machines than intended. Start with a harmless inspection,
confirm the target count, and review the returned invocation status and output. Session Manager provides an
interactive shell through the same managed access path. Patch Manager schedules updates from a baseline. These
features require the agent, permissions and network connectivity to the service endpoints; installing the agent
alone does not establish access.

> **Video.** [13.6 AWS Systems Manager: Session Manager, Run Command & CloudShell](https://www.youtube.com/watch?v=fww8oL1VeWs) (CSE Gawd)

## AWS CI/CD services

The CI/CD course used GitHub Actions. AWS has its own pipeline services, common in companies that keep
everything inside AWS:

| Service          | Like                                                                                      |
| ---------------- | ----------------------------------------------------------------------------------------- |
| **CodeBuild**    | a build runner: runs `buildspec.yml` in a container, pay per minute                       |
| **CodePipeline** | the workflow: source → build → deploy stages, with manual approvals                       |
| **CodeDeploy**   | deploys to EC2, Auto Scaling groups, ECS or Lambda, with rolling or blue/green strategies |

Many teams mix them: GitHub Actions for CI, assuming an AWS role with OIDC (lesson 2), then `cloudformation
deploy` or CodeDeploy for the release.

CodeBuild runs the commands in a build specification. CodePipeline connects source, build and deployment stages,
and can pause for approval. CodeDeploy coordinates application rollout to supported compute targets. These are
separate responsibilities, so you can choose only the stages that solve a real workflow problem. A pipeline does
not make credentials safe by itself: give its role only the permissions needed for that stage and keep secrets
out of build logs. Teams that already use GitHub Actions can retain it for tests and use an assumed AWS role for
deployment rather than migrating every step at once.

## Clean up

```sh
$ aws cloudformation delete-stack --stack-name academy-iac
$ aws cloudformation wait stack-delete-complete --stack-name academy-iac
$ aws ssm get-parameter --name /academy/dev/log-level
An error occurred (ParameterNotFound) when calling the GetParameter operation:
```

Deleting the stack deleted the bucket and the parameter with it. One catch: CloudFormation can't delete a bucket
that still has objects, so empty it first, or set `DeletionPolicy: Retain` on data you mean to keep.

> **In production.** Every resource comes from code in git and reaches AWS through a pipeline, never from a laptop. Review change sets in pull requests, turn on termination protection for important stacks, set `DeletionPolicy: Retain` and `UpdateReplacePolicy: Retain` on databases and buckets, detect drift on a schedule, and split big systems into stacks per layer (network, data, app).

## Nested stacks keep one system understandable

A nested stack is a child stack created by a parent. Put network, application and monitoring in separate templates,
then pass outputs such as a subnet ID between them. Use StackSets when the same template must be copied across
accounts or Regions.

The parent owns the relationship and supplies parameters to each child. A child stack owns its own resources and
exposes selected outputs, which the parent can reference. This keeps a large template easier to read and lets a
network template be reused by more than one application. It also introduces dependencies: the parent cannot
finish until its child operations complete, and a child failure can roll back the parent operation. Keep template
URLs stable and versioned, make parameter contracts clear, and inspect nested events when a deployment fails.
Use this structure to split a system into understandable units, not to hide an oversized design behind more files.

```yaml
Resources:
  Network:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: https://example.invalid/network.yaml
      Parameters: {EnvironmentName: academy-demo}
Outputs:
  VpcId: {Value: !GetAtt Network.Outputs.VpcId}
```

Replace the example URL with a real reviewed template URL before deploying; it is not claimed output. Validate
with `cfn-lint`, inspect the change set, and delete the demonstration stack.

> **Video.** [AWS CloudFormation Nested Stack Tutorial](https://www.youtube.com/watch?v=zjOxdCw0KSc) (TechCoach)

## StackSets and CDK solve different repetition problems

StackSets applies one CloudFormation template to many accounts or Regions. CDK generates CloudFormation from typed
constructs. Bootstrap once, inspect `cdk synth`, review `cdk diff`, and deploy only after approval.

Use a StackSet when the same centrally managed resources must be rolled out across multiple accounts or Regions,
such as a baseline configuration. It coordinates stack instances but does not replace account governance or
reviewing what the template will create. CDK solves a different problem: it lets developers express resources in
code and synthesize CloudFormation. For one account and one stack, ordinary CloudFormation or CDK may be enough.
For many accounts, use StackSets only when the distribution and ownership model are clear. `cdk synth` and `cdk
diff` are review points; bootstrap establishes the deployment roles and resources that CDK needs.

```sh
$ cfn-lint parent.yaml network.yaml
$ cdk synth > template.json
$ cdk diff
```

## Mission: Template, change set, drift, delete

Deploy this lesson's template as a stack, preview and execute a change with a change set, change the parameter by hand and catch it with drift detection, then delete the stack and prove its resources are gone.

- You need: An AWS account and the AWS CLI
- You'll have: CREATE_COMPLETE, a change set with Replacement False, LogLevelParam MODIFIED in drift detection, then ParameterNotFound after deletion

```sh
$ aws cloudformation create-stack --stack-name academy-iac --template-body file://stack.yaml
$ aws cloudformation wait stack-create-complete --stack-name academy-iac
$ sed -e 's/Value: info/Value: warn/' stack.yaml > stack-v2.yaml
$ aws cloudformation create-change-set --stack-name academy-iac --change-set-name warn-logs \
    --template-body file://stack-v2.yaml --parameters ParameterKey=Environment,UsePreviousValue=true
$ aws cloudformation wait change-set-create-complete --stack-name academy-iac --change-set-name warn-logs
$ aws cloudformation describe-change-set --stack-name academy-iac --change-set-name warn-logs \
    --query 'Changes[].ResourceChange.[Action,LogicalResourceId,Replacement]' --output text
$ aws cloudformation execute-change-set --stack-name academy-iac --change-set-name warn-logs
$ aws cloudformation wait stack-update-complete --stack-name academy-iac
$ aws ssm put-parameter --name /academy/dev/log-level --value debug --overwrite
$ DID=$(aws cloudformation detect-stack-drift --stack-name academy-iac --query StackDriftDetectionId --output text)
$ sleep 20; aws cloudformation describe-stack-resource-drifts --stack-name academy-iac \
    --query 'StackResourceDrifts[].[LogicalResourceId,StackResourceDriftStatus]' --output text
$ aws cloudformation delete-stack --stack-name academy-iac && aws cloudformation wait stack-delete-complete --stack-name academy-iac
```

Everything in this stack is free: an empty bucket and a standard parameter. If drift detection still says
`DETECTION_IN_PROGRESS`, wait a few more seconds and ask again.

## Try it

- Deploy this lesson's template with aws cloudformation create-stack and watch the Events tab.
- Change the parameter's Value in the template and create a change set. Is anything replaced?
- Execute the change set and read the new events.
- Change the SSM parameter by hand, run drift detection and find the MODIFIED resource.
- Delete the stack and check that the bucket and parameter are gone.
- Read one Systems Manager Run Command document, such as AWS-RunShellScript.

## Quiz

1. What is a CloudFormation stack?
   - A list of EC2 instances
   - **The set of resources created from one template, managed and deleted together** (answer)
   - A Docker image
   Why: Delete the stack and CloudFormation deletes every resource it created, in the right order.

2. Why create a change set before updating a stack?
   - It is faster
   - **It shows what will be added, modified or replaced before anything changes, so you catch a database replacement before it happens** (answer)
   - It is required for every update
   Why: The change set here showed Modify for both resources and Replacement False. A True on a database would mean new, empty storage.

3. Someone changed a value in the console that the stack also manages. What finds it?
   - CloudTrail only
   - **Drift detection, which compares each resource's real configuration with the template** (answer)
   - Nothing; the stack fixes it automatically
   Why: Drift detection reported LogLevelParam as MODIFIED. The next update would overwrite the manual change, so fix the template or undo the edit.

4. When does AWS CDK make sense over writing CloudFormation YAML?
   - Never
   - **When you'd rather define infrastructure in a programming language with loops, functions and reusable constructs; it generates CloudFormation for you** (answer)
   - Only for Lambda
   Why: cdk synth produces a template and cdk deploy deploys it as a stack, so everything in this lesson still applies.

5. You need to run the same shell command on 50 instances without SSH. Which service?
   - CodeDeploy
   - **Systems Manager Run Command** (answer)
   - CloudFront
   Why: Run Command sends a document such as AWS-RunShellScript to instances through the SSM agent and records the output, with no open ports or keys.

## Resources

- [What is AWS CloudFormation?](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) (AWS Docs)
- [Update stacks using change sets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-changesets.html) (AWS Docs)
- [Detect unmanaged configuration changes (drift)](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift.html) (AWS Docs)
- [AWS CDK developer guide](https://docs.aws.amazon.com/cdk/v2/guide/home.html) (AWS Docs)
- [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) (AWS Docs)
