Amazon DOP-C02: Infrastructure as Code and Configuration Management — Study Guide
Part of the AWS DevOps Engineer Professional DOP-C02 — Study Guide. Practice with verified answers in the Amazon exam hub, or take timed practice tests on ExamRoll.io.
Overview
Infrastructure as Code (IaC) and configuration management on AWS provide repeatable, auditable, and governed provisioning and configuration of infrastructure and applications. CloudFormation and the AWS Cloud Development Kit (CDK) describe resources declaratively or via code that synthesizes to CloudFormation. Configuration layers such as AWS OpsWorks and AWS Systems Manager enforce and report desired state on instances across EC2 and hybrid fleets. Secrets, parameters, and image-baking complete the lifecycle, enabling immutable, secure deployments at scale.
CloudFormation Stacks, Change Control, and Governance
CloudFormation stacks are the unit of deployment. Design stacks around lifecycle boundaries and ownership to minimize blast radius. Use parameters sparingly and prefer opinionated defaults with mappings or SSM lookups. Export and import only stable, shared values via Outputs and Fn::ImportValue to avoid tight coupling.
Nested stacks encapsulate reusable components and keep parent templates small. A parent stack can pass parameters to child stacks and consume their outputs, enabling modular architectures (for example, a shared-network nested stack consumed by an application stack). Keep nested stacks focused on a single concern (VPC, data tier, app tier) and version them independently.
StackSets deploy a single template across accounts and Regions. Use the service-managed permission model with AWS Organizations to auto-deploy to OUs and automatically include new accounts. Configure operation preferences (max concurrent accounts/Regions, failure tolerance) to control rollout. Parameter overrides per account or Region let you adapt a standard template to local constraints. Monitor StackSet and stack instance drift to detect out-of-band changes.
Change sets provide safe, human-reviewable updates. Always CreateChangeSet and inspect the resource-by-resource impact, replacements, and potential data loss before ExecuteChangeSet. Integrate change sets into automated pipelines for gated approvals.
Drift detection validates that stack resources match the template. Run drift detection routinely on critical stacks and StackSets; understand that not all properties are evaluated for all resource types (unsupported properties report as “not checked”). Treat drift as an incident: investigate, capture context, and correct either by stack update or by codifying the drift and reapplying.
Stack policies are JSON documents that protect critical resources during updates. Deny updates to irreplaceable resources (for example, production databases, Route 53 zones) and use StackPolicyDuringUpdateBody to temporarily open a surgical path for a specific change, then restore the stricter policy. Combine with termination protection and DeletionPolicy (Retain/Snapshot) for guardrails. For resources with external state (S3 buckets), plan deletion behaviors. If a bucket must be emptied before deletion, implement a custom resource to purge objects on stack delete.
AWS CDK and CloudFormation Extensibility
AWS CDK models infrastructure in familiar languages (TypeScript, Python, Java, .NET, Go). Constructs are the CDK building blocks:
- L1 constructs (CfnXxx) are generated from the CloudFormation spec and map one-to-one to resources.
- L2 constructs add high-level intent and sane defaults (for example, ApplicationLoadBalancedFargateService).
- L3 “patterns” compose multiple L2s for ready-to-use architectures.
A CDK app contains one or more stacks. During cdk synth, the app resolves context lookups (for example, VPC IDs), renders assets, and produces a CloudFormation template. Before you deploy, cdk bootstrap creates the environment’s asset buckets and roles. Use cdk diff to preview changes, then cdk deploy to submit templates and assets; CDK internally uses change sets and will show and confirm security-sensitive changes (IAM or resource replacements). Tag stacks and resources through Aspects to enforce organization-wide tagging. Where L2 abstractions fall short, use escape hatches (node.defaultChild) or drop to L1 constructs.
CloudFormation custom resources extend IaC to anything accessible via APIs. A Lambda-backed custom resource receives Create, Update, and Delete events with a RequestId, PhysicalResourceId, and properties. The function must:
- Be idempotent and return success/failure to the presigned ResponseURL within the timeout window.
- Set a stable PhysicalResourceId to track updates and drive cleanup on Delete.
- Handle retries and stabilization waits for eventually consistent downstream services.
Use least-privilege IAM execution roles for the Lambda, include exponential-backoff on API calls, and log correlation via the RequestId. For large or long-running operations, consider Step Functions with a custom resource that waits on an execution token. Prefer the CloudFormation Registry for reusable, versioned providers when applicable.
Secrets and Parameters in Infrastructure as Code
Never hardcode secrets in templates or code. Use dynamic references to resolve sensitive values at deploy time:
- Secrets Manager: {{resolve:secretsmanager:secret-id:SecretString:json-key:version-stage}}
- SecureString Parameter Store: {{resolve:ssm-secure:parameter-name:version}}
Dynamic references prevent secrets from being stored in the stack template or events. Do not place secrets in Outputs or resource properties that CloudFormation logs as plaintext. Grant CloudFormation’s execution role permission to decrypt or retrieve referenced values, and scope KMS CMKs to principals that need access.
Parameter Store is ideal for non-secret configuration (feature flags, AMI IDs, endpoints). Use versioned SSM parameters to create safe rollbacks and atomic promotions across environments. In CDK, import values with ssm.StringParameter.fromStringParameterName or fromSecureStringParameterAttributes for secure values, and wire parameter reads into user data or application bootstraps.
Secrets Manager is designed for lifecycle controls, rotation, and auditing. Integrate rotation with supported engines (RDS, Aurora) or custom Lambdas. Reference secrets at runtime rather than baking into AMIs to avoid proliferation of stale material. For containerized or serverless workloads, inject secrets via environment variables backed by Secrets Manager references or mount via ECS/TaskDefinition secrets; rotate with minimal downtime by using short TTL connection pools and retries.
Configuration Management and Immutable Infrastructure
AWS OpsWorks provides opinionated configuration management. OpsWorks Stacks uses Chef cookbooks and lifecycle events (Setup, Configure, Deploy, Undeploy, Shutdown) to orchestrate application configuration and deployments, and supports auto-healing with health checks that stop/start or replace instances. Historically, OpsWorks also offered managed Chef Automate and Puppet Enterprise; today, many teams standardize on Systems Manager for agent-based orchestration or run Ansible/Chef/Puppet control planes themselves. Ansible is not natively integrated with OpsWorks; instead, use Systems Manager State Manager to run playbooks, or AWX/Ansible Automation Platform with SSM Session Manager connectivity and EC2 dynamic inventory.
AWS Systems Manager is the modern control plane for hybrid configuration:
- State Manager enforces desired state through Associations that run SSM documents (YAML/JSON) on a schedule, event, or instance start. Use AWS-RunShellScript, AWS-ApplyAnsiblePlaybooks, AWS-ConfigureDocker, and custom documents to converge configuration. Parameterize associations and target by tags for fleet-wide changes.
- Configuration compliance surfaces association status and Patch Manager results. Use patch baselines to define approved classifications, tie to Maintenance Windows, and track compliance by instance tag, patch group, or resource group. Hybrid Activations onboard on-premises nodes as managed instances for uniform governance.
- Inventory records packages, files, and Windows updates; Resource Data Sync exports to S3 and Athena for enterprise reporting. Combine SSM compliance with AWS Config rules and automatic remediation (Systems Manager Automation runbooks) to close the loop from detection to correction.
Immutable infrastructure eliminates drift and accelerates rollback. EC2 Image Builder codifies image pipelines with:
- Components (install, harden, validate steps) expressed as documents.
- Image recipes that compose components and base images.
- Infrastructure configurations defining subnets, security groups, instance profiles, and logging.
- Distribution configurations to replicate AMIs to Regions and share to accounts.
Add test components to validate CIS benchmarks, agent health (SSM/CloudWatch), and application smoke checks. Version images and label with semantic tags. Publish AMI IDs to Parameter Store (for example, /app/frontend/ami) and reference in Auto Scaling launch templates. Deploy with rolling or blue/green strategies; replace instances instead of in-place patching to preserve immutability. Feed vulnerability scans (Amazon Inspector) into pipeline promotion gates. Do not bake secrets into images; retrieve at boot via Instance Metadata Service v2 and SSM/Secrets Manager references.
Practical Problem Scenario
Capital One needs to standardize multi-account, multi-Region deployments for a customer-facing platform while enforcing tight governance, secret management, and eliminating configuration drift. The environment spans hundreds of accounts in AWS Organizations, with strict controls around database access and OS hardening.
- Model infrastructure with AWS CDK and synthesize to CloudFormation
- Implement L2/L3 constructs for VPCs, ALBs, Auto Scaling groups, and Aurora. Use cdk synth and cdk diff in CI to generate and validate templates and change sets.
- Why CDK: Strong composition and reuse through constructs, programmatic policies via Aspects for org-wide tagging and guardrails, and native integration with CloudFormation for auditability.
- Distribute baseline network and guardrail stacks via CloudFormation StackSets
- Create service-managed StackSets targeting security and sandbox OUs to roll out shared VPC endpoints, standard CloudWatch alarms, and IAM boundaries. Enable automatic deployment to new accounts with failure tolerance and concurrency controls.
- Why StackSets: Organization-scale, consistent rollout with auto-inclusion of new accounts and built-in drift detection.
- Protect critical resources with stack policies and change sets
- Apply stack policies that deny updates to Aurora clusters and Route 53 zones. Require CreateChangeSet and manual approval before ExecuteChangeSet in the pipeline for production.
- Why stack policies/change sets: Enforce least-privilege mutations and provide human review before high-risk changes.
- Extend IaC with Lambda-backed custom resources
- Implement a Custom::S3BucketCleanup to empty application buckets on stack deletion and a Custom::AuroraParameterTuner that applies engine parameters post-create.
- Why custom resources: Close functional gaps in declarative provisioning while keeping lifecycle tied to the stack.
- Centralize secrets and configuration with Secrets Manager and Parameter Store
- Store database credentials and API keys in Secrets Manager with rotation Lambdas; publish AMI IDs, feature flags, and endpoints to Parameter Store. Reference values via dynamic references in CloudFormation and CDK imports at runtime for apps.
- Why these services: Separation of concerns—secrets with rotation and audit, parameters for non-secret config and easy promotion.
- Enforce desired state and compliance via Systems Manager State Manager
- Create associations to install agents, configure OS settings, and apply Ansible playbooks where needed. Use Patch Manager with Maintenance Windows for off-hours patching and compliance dashboards aggregated by Resource Data Sync.
- Why State Manager: Agent-based convergence across EC2 and on-premises with continuous compliance reporting and remediation at scale.
- Adopt immutable infrastructure with EC2 Image Builder
- Build hardened AMIs with components for CIS baselines, SSM/Inspector agents, and app runtime dependencies. Run tests, publish AMI IDs to Parameter Store, and wire Auto Scaling launch templates to the versioned parameters. Deploy via rolling updates; trigger instance refresh on AMI updates.
- Why Image Builder: Reproducible, testable images that eliminate drift and reduce mean time to recovery through fast rollbacks.
- Pipeline orchestration and governance
- Implement a multi-stage pipeline that runs cdk synth/diff, creates change sets, pauses for approval, and then executes. Use EventBridge to trigger StackSet updates on repository changes. Add drift detection scans nightly and open OpsCenter items for discrepancies.
- Why this approach: Continuous delivery with auditable promotions, proactive drift detection, and automated remediation through well-defined service responsibilities.
← CI · All domains · Monitoring →
Practice these questions → · Timed practice on ExamRoll.io →
Pass the whole exam — not just this question
You found this answer. Get every verified question and explanation in one place, and save hours of prep. Free to start.
Pass your exam →