SkillSprout
Chapter 3 · Lesson 3
Advanced
6 min read

CDK, SAM and Systems Manager

Overview

Writing YAML for everything becomes tedious at scale. The AWS Cloud Development Kit (CDK) lets you define infrastructure in TypeScript, Python, Java, C# or Go and synthesises CloudFormation. The Serverless Application Model (SAM) is a shorthand for serverless resources with a local test and deploy workflow. Both ultimately produce CloudFormation templates.

Where CloudFormation provisions resources, AWS Systems Manager (SSM) operates the instances and applications afterwards: running commands, patching, storing configuration, opening shell sessions without SSH, and automating runbooks. It is the AWS-native replacement for hand-rolled configuration management.

The exam rewards understanding how these tools complement each other: constructs and pipelines for provisioning, SSM Parameter Store/Secrets for configuration, State Manager for desired state, Automation for runbooks, and AppConfig for safe configuration rollout. It may also mention OpsWorks, which AWS has retired, so prefer Systems Manager.

Key Concepts

  • CDK constructs come in L1 (raw CloudFormation), L2 (opinionated defaults) and L3 (patterns) levels; cdk synth, diff, deploy and bootstrap are the key commands.
  • cdk bootstrap creates the CDKToolkit stack (staging bucket, ECR repo, deploy roles) per account/Region; cross-account deploys require bootstrapping with --trust.
  • CDK Pipelines is a self-mutating CodePipeline construct that deploys stages (Waves) to several accounts and Regions.
  • SAM CLI: sam build, sam local invoke/start-api, sam deploy --guided, sam sync for rapid iteration; templates use the AWS::Serverless transform.
  • Parameter Store: standard and advanced tiers, String / StringList / SecureString (KMS), hierarchies, versions and policies (expiration).
  • Run Command executes documents on targets by tag with rate and error controls; State Manager associations keep a desired state on a schedule.
  • Automation runbooks (SSM documents) orchestrate multi-step, cross-account, approval-gated operations, including AMI baking and remediation.
  • Session Manager gives audited shell access without SSH keys, bastions or open ports; AppConfig safely deploys feature flags and configuration.

Detailed Notes

CDK in practice

typescript
import * as cdk from "aws-cdk-lib";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as apigw from "aws-cdk-lib/aws-apigateway";

export class OrdersStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
    const fn = new lambda.Function(this, "Handler", {
      runtime: lambda.Runtime.NODEJS_20_X,
      handler: "index.handler",
      code: lambda.Code.fromAsset("lambda"),
    });
    new apigw.LambdaRestApi(this, "Api", { handler: fn });
  }
}
bash
cdk bootstrap aws://111122223333/us-east-1 \
  --trust 999988887777 --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess
cdk diff && cdk deploy OrdersStack

CDK advantages: loops, conditionals, unit tests with assertions, shared construct libraries, and automatic IAM wiring (grantRead). Use aspects to enforce rules (for example tag or encryption checks) and cdk-nag for security rules.

CDK Pipelines

typescript
const pipeline = new CodePipeline(this, "Pipeline", {
  synth: new ShellStep("Synth", {
    input: CodePipelineSource.connection("my-org/orders", "main", { connectionArn }),
    commands: ["npm ci", "npm run build", "npx cdk synth"],
  }),
  crossAccountKeys: true,
});
pipeline.addStage(new AppStage(this, "Prod", { env: { account: "999988887777", region: "us-east-1" } }));

The pipeline is self-mutating: an UpdatePipeline stage re-deploys the pipeline when its code changes. crossAccountKeys: true creates a KMS key for cross-account artifacts.

SAM

CommandUse
sam initScaffold a project
sam buildBuild functions and layers (optionally in a container)
sam local invoke / start-apiRun functions locally with Docker
sam deployPackage and deploy through CloudFormation, with change set confirmation
sam sync --watchFast code sync to the cloud for development
sam pipeline initGenerate a CI/CD pipeline definition

SAM shorthand types: AWS::Serverless::Function, Api, HttpApi, SimpleTable, StateMachine, Application. DeploymentPreference (previous chapter) and Events simplify triggers.

Systems Manager capability map

CapabilityPurposeExam hint
Parameter StoreConfig and secrets by pathCheap, hierarchical, KMS, no automatic rotation
Run CommandAd-hoc commands at scaleTargets by tag; rate control; output to S3/CloudWatch
State ManagerEnforce desired state (install agent, join domain)Associations on a schedule or on instance launch
Patch ManagerPatch baselines and maintenance windowsCovered in the final chapter
AutomationRunbooks, AMI creation, remediationAWS-owned runbooks such as AWS-RestartEC2Instance
Session ManagerShell without SSHIAM-controlled, logged to S3/CloudWatch, no inbound ports
InventoryCollect metadata of softwareResource Data Sync to S3
DistributorPackage distributionCustom software to instances
AppConfigFeature flags, config rolloutDeployment strategy with alarm rollback

Instances become managed when SSM Agent is installed, an instance profile (AmazonSSMManagedInstanceCore) is attached and there is network access to SSM endpoints (internet or the ssm, ssmmessages and ec2messages VPC endpoints). Default Host Management Configuration can manage instances without individual profiles.

Parameter Store and Secrets Manager

Parameter StoreSecrets Manager
CostFree standard tierPer secret per month
RotationNone built inBuilt-in Lambda rotation
Cross-accountAdvanced tier with sharing via RAMResource policy
UseConfig, AMI IDs, endpointsCredentials, API keys, DB passwords
bash
aws ssm put-parameter --name /prod/orders/db-host --type String --value db.internal
aws ssm get-parameters-by-path --path /prod/orders --with-decryption --recursive
aws ssm send-command --document-name AWS-RunShellScript \
  --targets Key=tag:Env,Values=prod --parameters commands="systemctl restart orders" \
  --max-concurrency 10% --max-errors 1

AppConfig

AppConfig validates configuration (JSON schema or Lambda), deploys it with a strategy (linear, exponential, all-at-once) and monitors CloudWatch alarms, rolling back automatically. Use it to flip feature flags without redeploying code.

OpsWorks and Elastic Beanstalk note

AWS OpsWorks (Chef/Puppet) has reached end of life or end of support for its main offerings; for new designs choose Systems Manager, CloudFormation, ECS or Beanstalk. Questions may still describe OpsWorks layers and Chef recipes, but the preferred modern answer is SSM plus IaC.

Real World Example

Scenario: a platform team supports 30 product teams. They publish an internal CDK construct library (secure VPC, standard ECS service with alarms and tags) and a CDK Pipelines template that deploys to dev, test and prod accounts. Teams write ten lines instead of a thousand.

On the operations side, State Manager keeps the CloudWatch agent and SSM agent current, Session Manager replaced all SSH bastions, and an Automation runbook bakes a golden AMI weekly and updates an SSM parameter that launch templates read.

Architecture Diagram

CDK Pipelines and Systems Manager operations
Architecture
AWS Cloud
CDK appTypeScript
CloudFormation
Workload account
EC2 fleetSSM agent
Systems ManagerState Manager / Run Command
Parameter Store

Constructs provision; Systems Manager operates and configures.

  1. 1CDK code is synthesised to CloudFormation by the pipeline.
  2. 2Stacks deploy into each account using bootstrapped roles.
  3. 3Instances register with Systems Manager via the agent and role.
  4. 4State Manager and Run Command enforce configuration and run operations.
  5. 5Parameter Store and AppConfig supply configuration and flags at runtime.

Best Practices

  • ✓Bootstrap every target account/Region and use CDK Pipelines for cross-account delivery.
  • ✓Unit-test constructs and run cdk-nag or aspects in CI.
  • ✓Use Session Manager instead of SSH and log sessions to S3 or CloudWatch Logs.
  • ✓Store configuration in Parameter Store hierarchies, secrets in Secrets Manager.
  • ✓Use AppConfig with alarms for configuration and feature flag rollouts.

Common Interview Questions

Exam Tips

DOP-C02 focus

  • "Run a command on all tagged instances with limited blast radius" = Run Command with max-concurrency/max-errors.
  • "Keep software configured continuously" = State Manager association.
  • "No SSH, auditable shell" = Session Manager; instances need the SSM agent and role.
  • OpsWorks is legacy; Systems Manager is the preferred configuration management answer.

Finished this lesson?

0 of 44 lessons done · 0% of the course