Infrastructure as Code

Learn to define cloud infrastructure in code and deploy it safely. Compare declarative and imperative provisioning, write and run Terraform configurations and modules, deploy Azure resources with ARM templates and Bicep, and build AWS stacks with CloudFormation. Manage state and drift, preview every change before it is applied, and enforce your organization's rules automatically with policy as code.

IntermediateLesson 7 of 8 in Cloud Architecture and Administration Course

What you will learn

  1. Describe what it means to manage cloud infrastructure as code, compare declarative and imperative provisioning, and match the main tools to the situations they suit.
    • Describe infrastructure as code and the problems it solves
      Explain how definition files kept in version control replace manual console work, and what teams gain and must still manage when they adopt them.
    • Compare declarative and imperative provisioning
      Tell desired-state definitions apart from step-by-step scripts, explain idempotency, and decide when each style fits.
    • Match Terraform, Bicep and CloudFormation to the situations they suit
      Compare how the three main declarative tools reach the cloud, where each keeps its record of deployed resources, and how each previews and recovers from changes.
  2. Write HCL configurations with providers, resources, variables and modules, and use the init, plan and apply workflow to make reviewed changes.
    • Declare providers, resources and data sources in HCL
      Write the blocks of a Terraform configuration, pin provider versions, and connect resources through references that set the order of work.
    • Make configurations reusable with variables, outputs and expressions
      Parameterize a configuration with typed input variables, expose results with outputs, and create repeated or optional resources with count, for_each, expressions and lifecycle rules.
    • Run the Terraform workflow and review a plan before applying
      Initialize, format, validate, plan, apply and destroy, read every symbol of a plan, and catch risky changes before they reach the cloud.
    • Build and use Terraform modules
      Package resources into modules with clear inputs and outputs, call them from local paths, registries and Git, and control which module version each environment uses.
  3. Explain how IaC tools track what they deploy, store and lock Terraform state safely, change state without recreating resources, and find and fix drift in every tool.
    • Explain, store and protect Terraform state
      Describe what the state records, move it to a shared backend with locking, and keep secrets out of it where possible.
    • Import, move and remove resources in state
      Bring existing resources under Terraform management, rename or restructure code without recreating resources, use workspaces with care, and recover state.
    • Detect and resolve drift
      Recognize drift between code and real resources, find it with each tool's checks, and decide whether to revert, adopt or ignore each change.
  4. Read and modify ARM JSON templates, write Bicep files and modules, and deploy them safely with parameter files, what-if previews and the right deployment mode.
    • Read and modify an ARM template
      Identify the sections of an ARM JSON template, follow its expressions, loops and dependencies, and change it without breaking the deployment.
    • Write Bicep files and modules
      Write parameters, variables, resources, loops and outputs in Bicep, split a deployment into modules, and convert between Bicep and ARM JSON.
    • Deploy, preview and track Azure deployments
      Deploy templates at the right scope, preview changes with what-if, choose a deployment mode, and manage resources as a unit with deployment stacks.
  5. Write CloudFormation templates, create and update stacks through reviewed change sets, and reuse templates across stacks, accounts and Regions.
    • Write a CloudFormation template
      Use the sections of a CloudFormation template, intrinsic functions and resource attributes to describe AWS resources that deploy reliably and keep their data safe.
    • Create and update stacks with change sets
      Follow a stack through creation, update, rollback and deletion, review change sets before executing them, and protect critical resources from unwanted updates.
    • Reuse templates across stacks, accounts and Regions
      Split infrastructure into stacks that work together, nest reusable templates, deploy one template to many accounts and Regions, and use the tools built on CloudFormation.
  6. Write rules that check infrastructure definitions and deployments automatically, and place them before, during and after deployment.
    • Explain policy as code and where policies run
      Describe how organizational rules become automated checks, where in the lifecycle each kind of check runs, and how platform guardrails such as Azure Policy work alongside template checks.
    • Check templates and plans before deployment
      Scan IaC files with ready-made rule sets, write and test custom rules for Terraform plans and CloudFormation templates, and act on the findings.

Infrastructure as Code study guide

6 chapters

1

Explain infrastructure as code and choose an approach

Cloud resources are easier to reproduce when their settings live in files that a team can review. Learn how infrastructure as code changes everyday administration, why desired-state definitions behave differently from command scripts, and how Terraform, Azure native tools, and CloudFormation divide the work. Tool choice also decides where deployment records live and what recovery looks like after a failed change.

1.1 Describe infrastructure as code and the problems it solves

Infrastructure as code, or IaC, defines infrastructure in machine-readable files. A tool reads the files and creates or changes networks, virtual machines, storage, databases, and access rules. The files express the team's agreed infrastructure design.

Turn repeated work into a definition

With manual setup, one administrator can miss a subnet setting while another picks a different machine size. Months later, rebuilding depends on notes and memory. IaC makes those choices explicit. Repeatability means the definition can build an environment again; consistency means related environments share a design with deliberate differences.

For example, a web application needs a network, two subnets, storage, and a group of virtual machines. The team writes one definition and supplies different inputs for development, test, and production. Development needs 1 machine; production needs 3. A temporary load-test environment uses the same definition with another input file. The team can inspect exactly which values differ.

IaC speeds provisioning by letting the tool perform the defined work. Code also documents connections: a machine's subnet reference shows where it belongs. If an environment is lost, the team can rebuild its infrastructure from the definition, including in another region when the design supports it. Application data still needs its own backup and recovery process.

Make a change reviewable

Keep definitions in Git. Each commit records the author, time, and reason for a change. A pull request lets a colleague inspect both the code and its preview, the proposed operations against the selected environment.

A practical change follows this sequence:

  1. Edit the definition and the environment's inputs.
  2. Check syntax, types, and formatting.
  3. Preview the resulting creates, updates, and deletions.
  4. Review the preview, including data and access changes.
  5. Apply the reviewed change and verify the result.

Reverting a Git commit restores an earlier definition. It does not itself restore the cloud or recover deleted data. The earlier definition must still be previewed and applied, and rebuilding a resource can produce a new identity.

Manage the whole lifecycle

IaC handles creation, updates, and eventual deletion. Existing resources can also be imported into management. An emergency console edit leaves the real resource different from the definition; that difference is drift. Record an accepted emergency fix in code before the next deployment can undo it.

Mutable infrastructure changes in place, such as patching an existing server. Immutable infrastructure replaces an old instance with a new one built from an updated image or definition. IaC supports both. Replacement keeps machines closer to a known build, while traffic movement and data preservation still need planning.

Automation can spread an error quickly. Preview and peer review are essential before applying. Protect deployment records and secrets, and give critical data resources deletion protection. Automated policy checks can reject known unsafe settings before they reach the cloud.

Key Takeaways

  • Keep the desired infrastructure in version control so changes can be reviewed and reproduced.
  • Use shared definitions with explicit environment inputs to keep differences visible.
  • Preview, review, apply, and verify every infrastructure change.
  • Reverting code still requires a new deployment; data recovery needs backups.
  • Keep accepted manual fixes in code so later deployments preserve them.

1.2 Compare declarative and imperative provisioning

An imperative script describes the actions to perform in order. A declarative definition describes the result that should exist. The distinction concerns what the tool is told, not whether the file looks like code.

Describe an action or a desired state
ApproachWhat the author suppliesHow work is chosen
ImperativeOrdered commandsThe script encodes the steps and checks
DeclarativeDesired resources and settingsThe tool compares the definition with its resource records and cloud reads

The command aws ec2 run-instances --count 2 requests 2 new instances. Run it twice successfully and it launches 4. A Terraform resource with count = 2 declares 2 managed instances. Applying it again with unchanged inputs and unchanged infrastructure leaves those 2 in place.

This is idempotency: repeating an operation with the same input leaves the same result as doing it once. Declarative tools are designed around this property. If the definition changes from 2 instances to 3, the tool plans one addition. If it changes from 3 to 1, the tool plans two deletions. An imperative script must inspect the starting count and implement each adjustment itself. A script can be written idempotently, but an action command alone does not provide that behavior.

Let references set the order

A subnet cannot be created before its network exists. An imperative script must put the network command first. A declarative tool follows resource references and builds a dependency graph. A subnet that refers to a network waits for it. Independent resources can be created in parallel, even if their definitions appear in a different order in the file.

The graph orders operations; it does not guarantee success. A missing permission, exhausted quota, or unavailable name can still cause a deployment to stop partway through. The definition is the intended result, not a claim that every API request will succeed.

Combine the approaches where they fit

Desired-state definitions suit lasting infrastructure: networks, machines, storage, and permissions. Imperative commands suit investigation and actions such as reading logs, restarting a machine, or triggering a database failover. A team can keep its infrastructure declarative while using commands for operations.

A general-purpose language can still produce a declarative deployment. AWS CDK programs use loops and functions, but cdk synth produces a CloudFormation template. CloudFormation then manages the desired resources. Pulumi also supports desired-state infrastructure through familiar programming languages. Seeing Python or TypeScript is therefore insufficient to classify the approach.

Separate provisioning from software setup

Provisioning creates or changes the infrastructure resources. Configuration management installs and configures software inside existing servers. Terraform can provision virtual machines, then Ansible can configure their software. A startup script through cloud-init or user data is a lighter way to perform initial software setup from a provisioning definition. The presence of that script does not turn the whole deployment into an imperative infrastructure workflow.

Key Takeaways

  • Imperative code gives steps; declarative code gives the desired end state.
  • Idempotency means repeating unchanged input leaves the same resulting state.
  • References create a dependency graph; file order is not deployment order.
  • Programming language syntax does not decide whether a workflow is declarative.
  • Provisioning manages resources; configuration management manages software inside servers.
  • Declarative deployments can still fail when cloud APIs reject an operation.

1.3 Match Terraform, Bicep and CloudFormation to the situations they suit

Terraform, ARM/Bicep, and CloudFormation all deploy desired infrastructure. Their most useful differences are which platforms they reach, where they record managed resources, and how they handle a failed change.

Compare the deployment engines
ToolDefinition and platformDeployment recordPreview
TerraformHCL; provider plugins for many platformsState maintained by the team or HCP TerraformPlan
ARM/BicepARM JSON or Bicep compiled to JSON; AzureAzure resources and deployment historyWhat-if
CloudFormationJSON or YAML; AWSStack managed by AWSChange set

A Terraform provider translates resource declarations into a platform's API calls. Providers support major clouds and services such as DNS, GitHub, and monitoring systems. Terraform runs on a laptop, a build server, or HCP Terraform. The state maps code addresses to real resource IDs, so the team must store and protect it.

Bicep is Azure's shorter authoring language for ARM templates. Both are deployed through Azure Resource Manager, Azure's control plane for resource creation and change. A deployment targets a resource group, subscription, management group, or tenant. A resource's API version selects its available properties. There is no Terraform-style state file for the author to maintain.

CloudFormation deploys a stack, a group of AWS resources tracked together by the service. The stack record stays within AWS. AWS CDK and SAM are other authoring routes that deploy through CloudFormation.

Know what a failed deployment leaves behind

A Terraform apply does not roll back successful operations when another operation fails. Those successful changes stay and are recorded in state. Fix the cause, inspect a fresh plan, and continue.

CloudFormation normally rolls a failed update back toward the last stable stack configuration. The stack events show the failure and rollback progress. Azure deployments keep successful operations in place after a failure; an explicit rollback-on-error request can redeploy a previous successful deployment. These behaviors affect the recovery procedure a team must prepare.

Choose for the system and the team

An organization deploying Azure applications, external DNS, and a separate monitoring service can manage them through several Terraform providers in one workflow. An Azure-only team may prefer Bicep's direct platform support and no separate state file. An AWS team may choose CloudFormation or CDK for AWS-managed stacks and native integrations. Existing skills and organizational standards also matter.

The ideas transfer between tools. Terraform variables, Bicep parameters, and CloudFormation Parameters supply inputs. All expose outputs. Terraform and Bicep modules and CloudFormation nested stacks package reusable components.

A shared Terraform workflow is not portable resource code. An aws_instance still describes an AWS resource. Moving the application to Azure requires Azure resource types and a new platform design. OpenTofu, an open-source Terraform fork created in 2023, follows the familiar HCL and state-based workflow; it does not remove provider-specific resource definitions.

Key Takeaways

  • Terraform reaches several platforms through providers and keeps a separate resource state.
  • Bicep compiles to ARM JSON and deploys through Azure Resource Manager.
  • CloudFormation manages AWS resources as stacks and previews updates with change sets.
  • Compare failure handling and team skills along with platform support.
2

Write and run Terraform configurations

Terraform combines small declarations into a plan for a whole environment. Learn to connect provider settings, resources, inputs, and outputs, then package repeated designs as modules. Read plans closely enough to distinguish an ordinary update from a replacement, and use a saved plan to carry a reviewed decision into apply. Stable resource identities and controlled dependency versions make later changes easier to predict.

2.1 Declare providers, resources and data sources in HCL

Terraform reads every .tf file in one directory as one root module. Splitting declarations among files helps people navigate the code; it does not set execution order. HCL uses blocks with a type, labels, and arguments written as name = value.

Select and configure a provider
terraform {
  required_version = ">= 1.12"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}
provider "aws" {
  region = "eu-central-1"
}
resource "aws_s3_bucket" "logs" {
  bucket = "example-logs-prod"
}

The source address identifies the provider plugin. The requirement selects allowed versions; the provider block configures an instance of that plugin. Credentials come from the environment, a CLI login, or an identity supplied to the runner. Keep them out of the configuration.

~> 6.0 permits versions from 6.0.0 up to, but excluding, 7.0.0. ~> 6.12.0 permits versions from 6.12.0 up to, but excluding, 6.13.0. Constraints can also use =, !=, >, >=, <, and <=. A constraint is an allowed range, not the exact installed selection.

terraform init installs providers and writes the selected versions and checksums to the dependency lock file, .terraform.lock.hcl. Commit it so colleagues reuse the selection. Exclude the .terraform/ download directory. A later init reuses the locked provider; init -upgrade selects newer versions within the constraints.

For another region, declare another provider configuration with an alias such as backup. A resource selects it with provider = aws.backup. The provider source stays the same; the connection settings differ.

Give resources stable addresses

In resource "aws_s3_bucket" "logs", the type and local label form the address aws_s3_bucket.logs. The cloud bucket name comes from the bucket argument. Renaming the code label changes the address even if the cloud name stays the same.

References connect resources. An Azure storage account can use resource_group_name = azurerm_resource_group.main.name and location = azurerm_resource_group.main.location. Terraform creates the resource group first because those references establish implicit dependencies. An attribute such as aws_s3_bucket.logs.arn may be unknown until creation; the plan then shows (known after apply).

Use depends_on for a genuine hidden dependency, such as waiting for a role's permission attachment when no attribute reference expresses that need. Adding it everywhere serializes work and makes the relationships harder to understand.

Read resources managed elsewhere

A data source reads an existing object without taking ownership:

data "aws_availability_zones" "available" {
  state = "available"
}

Read its names with data.aws_availability_zones.available.names. Destroying this configuration does not delete the zones it read. A resource declaration manages an object's lifecycle; a data source looks up information about one. Azure's azurerm provider additionally needs features {} and, from version 4, a subscription ID.

Key Takeaways

  • Provider requirements select the plugin and allowed versions; provider blocks configure its connection.
  • Commit the provider lock file, and upgrade deliberately within version constraints.
  • A resource address identifies the declaration; a cloud name identifies the real object.
  • Use attribute references for dependencies and reserve depends_on for hidden ordering needs.
  • Data sources read existing information without managing the source object.

2.2 Make configurations reusable with variables, outputs and expressions

Input variables make one configuration serve several environments. Outputs expose results; local values name repeated expressions. Resource instance keys and lifecycle settings decide how those environments behave when the inputs change.

Declare inputs and computed values
variable "environment" {
  type    = string
  default = "dev"
  validation {
    condition     = contains(["dev", "test", "prod"], var.environment)
    error_message = "Choose dev, test, or prod."
  }
}
locals {
  name_prefix = "web-${var.environment}"
}
output "bucket_arn" {
  value = aws_s3_bucket.logs.arn
}

Read the input as var.environment and the local as local.name_prefix. Types include strings, numbers, booleans, and collections such as lists, sets, maps, objects, and tuples. Without a default, the input is required. Validation rejects an unsuitable value with a useful message. Resource lifecycle preconditions and postconditions check assumptions such as an image's architecture.

For local CLI runs, later command-line -var and -var-file values take priority. Below those come automatic variable files in lexical order, then terraform.tfvars.json, terraform.tfvars, TF_VAR_ environment variables, and defaults. HCP Terraform also supplies workspace/run inputs. For example, a default of t3.micro, an environment value of t3.medium, and terraform.tfvars containing t3.small produce t3.small; a command-line -var="instance_type=t3.large" wins over all three.

Build values and instances

A conditional such as var.environment == "prod" ? 3 : 1 selects a count. for expressions transform collections; a splat such as aws_instance.web[*].id gathers attributes. Functions include length, lower, lookup, merge, and cidrsubnet. For example, cidrsubnet("10.0.0.0/16", 8, 2) gives 10.0.2.0/24: add 8 prefix bits, then select subnet number 2. Try expressions in terraform console.

count = 3 creates instances indexed 0, 1, and 2. An optional resource can use count = var.create_bastion ? 1 : 0. Use for_each over a map or set of strings when each item has a stable name, such as aws_s3_bucket.this["logs"].

With count-based buckets from ["logs", "media", "backups"], removing the middle entry shifts backups into index 1. Terraform replaces the bucket at index 1 and destroys index 2: 1 to add and 2 to destroy. Named for_each instances retain their keys, so removing media destroys only that bucket. A dynamic block repeats nested blocks within a resource; it does not create separately addressed resource instances.

Set lifecycle behavior deliberately

create_before_destroy creates a replacement first, but needs compatible names and capacity; application readiness and traffic movement still decide availability. prevent_destroy rejects destructive plans while its resource and rule remain in the configuration. Removing the entire block removes that protection. ignore_changes delegates selected attributes to another process, and replace_triggered_by requests replacement when a related managed object changes. Marking an input or output sensitive hides normal display, but does not remove the value from state.

Key Takeaways

  • Use typed inputs, validation, local expressions, and outputs for a clear configurable interface.
  • Variable files outrank TF_VAR_ environment values in local CLI runs.
  • Choose for_each when named items need stable instance identities.
  • count uses numeric positions, so removing a middle list entry can affect later instances.
  • Lifecycle rules change replacement, destruction, and attribute ownership behavior.
  • Sensitive values still need protected state storage.

2.3 Run the Terraform workflow and review a plan before applying

A Terraform run turns a desired configuration into real operations. The important decision point is the plan, where the team can inspect consequences before granting permission to apply them.

Initialize and check

Run terraform init in a new working directory and after changing providers, module sources, or the backend. It prepares dependencies and state access. terraform fmt standardizes formatting; fmt -check reports formatting differences without rewriting, and -recursive includes subdirectories.

terraform validate checks syntax, types, references, and provider-required arguments in the initialized directory. It does not call cloud APIs. A valid configuration can still lack permissions, exceed a quota, or request an unavailable name.

Read actions before totals

terraform plan normally refreshes managed objects and compares the configuration with what it reads. It proposes changes without performing them.

SymbolAction
+Create
~Update in place
-Destroy
-/+Destroy, then create a replacement
+/-Create a replacement, then destroy the old object
<=Read a data source

A line marked # forces replacement identifies a property change requiring a new object. A replacement counts once in additions and once in destructions.

For example, a plan updates a web instance's tags, replaces an API instance after an image change, and adds a reports bucket. It totals 2 to add, 1 to change, and 1 to destroy. The reviewer must inspect the API replacement: its identity changes, local data can be lost, and addressing may change. A small-looking code change can therefore need a maintenance window or a different design.

Check every destruction and replacement, data-bearing resource, access change, and unexpected action. Confirm the intended account, environment, workspace, and resource names. Unexpected changes may come from drift or an upgraded provider.

Apply the reviewed decision
terraform plan -out=tfplan
terraform apply tfplan

The second command executes the saved plan without asking again. Terraform rejects a stale saved plan if its state has changed. Keep saved plans protected because they can contain sensitive values. Running terraform apply without a saved plan instead makes a fresh plan and asks for yes. -auto-approve skips that question and belongs in a workflow with another review gate.

Independent operations run in parallel, 10 by default. If apply fails partway, successful operations remain and state records them. Terraform does not automatically undo them. Fix the error, make a fresh plan, and review the remaining work.

Inspect and retire resources

terraform output reads outputs; terraform show displays state or a saved plan. terraform show -json tfplan gives review tools structured input. TF_LOG and TF_LOG_PATH enable detailed logs, which can expose secrets.

terraform plan -destroy previews deletion of managed resources; terraform destroy performs a destroy plan with confirmation. Use -replace=ADDRESS for an intentional replacement. Reserve -target=ADDRESS for exceptional recovery because it leaves the rest of the configuration unreconciled. HCP Terraform can run the same plan/apply process remotely, keeping state and run history and adding approval and policy gates.

Key Takeaways

  • Initialize before validation, and rerun init when dependencies or backend settings change.
  • Validation checks the configuration; a plan checks proposed cloud changes.
  • A replacement adds one creation and one destruction to plan totals.
  • Applying a saved plan executes the reviewed actions without a second prompt.
  • After partial failure, retain state and review a fresh plan; successful changes remain.

2.4 Build and use Terraform modules

A module packages Terraform resources behind inputs and outputs. The root module is the directory where Terraform runs; a module it calls is a child module. Reuse is useful when it captures a coherent design, such as a network with its subnets and outputs.

Call a component through its interface
module "network_dev" {
  source       = "./modules/network"
  cidr_block   = "10.10.0.0/16"
  subnet_count = 2
}
output "dev_subnets" {
  value = module.network_dev.subnet_ids
}

The child declares cidr_block and subnet_count as variables, creates the resources, and declares subnet_ids as an output. The caller cannot directly read a child's internal resources through a cross-module expression. Expose the values callers need through outputs.

Each module has its own variable and local scope. A child cannot read the root's var.environment unless the root passes that value as an argument. Default provider configurations are normally inherited; aliased configurations must be passed explicitly through the module's providers argument.

Work through a reusable network

Suppose the child creates subnets with cidrsubnet(var.cidr_block, 8, count.index) and outputs their IDs. For 10.10.0.0/16 and 2 subnets, indexes 0 and 1 produce 10.10.0.0/24 and 10.10.1.0/24.

A second call for production passes 10.20.0.0/16 and 3 subnets. It produces 10.20.0.0/24, 10.20.1.0/24, and 10.20.2.0/24. The same component design creates five subnets across the two calls, with their environment differences visible at the call sites.

Resources now have module-qualified addresses such as module.network_dev.aws_subnet.private[0]. Moving an existing resource from the root into a child changes its address. Use a moved block to preserve the association with the real object, then verify that the plan shows a move without recreation.

Select sources and versions deliberately
SourceHow it is selected
Local directoryA relative path such as ./modules/network
RegistryA module address plus a version constraint
GitA Git source URL pinned with ?ref=
Private registry or archiveA published source address

The version argument works for registry modules, not Git or local paths. A Git source can pin a tag or commit with ref. Run terraform init after changing a module source. The provider lock file locks providers, not remote module selections, so module source/version control needs its own attention.

Semantic versions use major.minor.patch. A new major version signals a breaking interface or behavior change. Upgrade intentionally and inspect the resulting plan; an unpinned fresh installation can select an unreviewed module release.

Keep a module focused: typed inputs with descriptions, sensible defaults and validation, useful outputs, and an example call. Avoid hard-coded environment values. Separate root directories for development and production can call the same child modules while keeping their inputs, credentials, and state independently controlled.

Key Takeaways

  • Module inputs and outputs form the interface; variables and locals stay scoped to their module.
  • Pass aliased providers explicitly when a child needs them.
  • Use registry version constraints or Git refs to control module upgrades.
  • Moving a resource into a module changes its address and needs a recorded move.
  • Separate environment roots can reuse modules while keeping distinct state.
  • Package a coherent design instead of adding a wrapper with no useful behavior.
3

Manage state and drift

Terraform needs a reliable record linking declarations to real objects. Learn how shared state, locking, and restricted access let a team work on the same infrastructure. Then distinguish adopting an object, changing its address, releasing it from management, and replacing it. Drift checks bring the live environment into the picture, but each detected difference still needs a decision about which system owns the setting.

3.1 Explain, store and protect Terraform state

Terraform state maps each resource address to a real object's ID and records attributes, outputs, and dependency information. A declaration tells Terraform what should exist; state tells it which existing object that declaration manages.

Share one protected record

The default local backend stores terraform.tfstate and a previous backup locally. That is convenient for an individual exercise. A team needs shared storage so colleagues do not apply against separate copies of the same mapping.

A remote backend can use S3, Azure Blob Storage, Google Cloud Storage, or HCP Terraform. An S3 example is:

terraform {
  backend "s3" {
    bucket       = "example-team-state"
    key          = "network/prod.tfstate"
    region       = "eu-central-1"
    use_lockfile = true
  }
}

The bucket must already exist. Enable versioning, encryption, and restricted access. Versioning provides earlier snapshots for recovery; it does not decide which snapshot matches the live resources.

Backend settings cannot refer to input variables or locals. Supply fixed settings in the block or with terraform init -backend-config=.... After changing backend settings, reinitialize. Use init -migrate-state when moving the existing state so the mapping follows the configuration.

Coordinate writers with a lock

State locking prevents concurrent operations from writing the same state. A second operation reports a lock error and its owner. With S3 native locking, use_lockfile = true enables a .tflock object; the older DynamoDB locking approach is deprecated. Azure Blob Storage uses a blob lease, and HCP Terraform coordinates locking automatically.

A lock left after a crashed run can be removed with terraform force-unlock LOCK_ID. First establish that its owning process has stopped. Removing an active lock allows competing writes and can damage the state.

State also carries a serial number and a lineage ID. They help Terraform reject an older or unrelated snapshot being pushed over the current one. Use supported state commands, not hand edits.

Treat state as sensitive data

Ordinary state can contain plaintext passwords and keys. sensitive = true redacts normal output; it does not remove stored values. Keep state out of Git and restrict who can read it. Protect saved plans and detailed logs as well.

Terraform 1.10 introduced ephemeral values and resources, which are omitted from saved plans and state. Ephemeral outputs are supported in child modules, not as root outputs. Terraform 1.11 introduced provider-supported write-only arguments. Reading a secret from a normal data source keeps it out of source code but can still put it in state. An ephemeral read feeding a compatible write-only argument avoids that storage path.

Limit the impact of a mistake

Separate states by environment and by meaningful components, such as network, data, and application. This limits blast radius, the resources an error can affect in one run. Share needed values through resource lookups or remote-state outputs. Reading with terraform_remote_state requires access to the full state snapshot, so it is also an access decision.

CloudFormation keeps its managed-resource record in AWS stacks. ARM deployments use Azure resources and deployment history. Neither needs a team-maintained Terraform backend.

Key Takeaways

  • State binds code addresses to real resource IDs and records deployment information.
  • Use shared, encrypted, versioned state storage with restricted access.
  • Locking coordinates operations; remove a stale lock only after its owner has stopped.
  • Sensitive display flags do not remove secrets from ordinary state.
  • Ephemeral values and supported write-only arguments can keep secrets out of state.
  • Split states to control access and reduce the impact of mistakes.

3.2 Import, move and remove resources in state

A resource's cloud identity and its Terraform address are different things. State operations let you adopt an existing object, record a new address, or stop managing it without rebuilding it.

Inspect before changing ownership

Start with terraform state list to see addresses and terraform state show ADDRESS to inspect a recorded resource. Both read state without changing it. Check the selected environment and workspace before any operation.

Import associates an existing object with a resource address. Configuration-driven import, introduced in Terraform 1.5, can be reviewed through a plan:

import {
  to = aws_s3_bucket.legacy
  id = "example-legacy-media"
}

Add the matching resource configuration, or use terraform plan -generate-config-out=generated.tf to produce a draft. Clean up the generated configuration and inspect its plan. The older terraform import ADDRESS ID needs the resource block already present and writes to state immediately.

Import IDs depend on the resource type: an S3 bucket uses its name, while an Azure resource uses its full resource ID. Importing does not mean the new code matches every real setting. If the plan proposes tag or TLS changes after adoption, decide which differences should be kept and which should be updated. Aim for an understood, no-change baseline before unrelated work.

Record a new address for the same object

Renaming a declaration alone makes Terraform see an old address disappearing and a new address appearing. A moved block records that they represent the same object:

moved {
  from = aws_s3_bucket.logs
  to   = aws_s3_bucket.app_logs
}

The plan can then show a move with no creation or destruction. Moves also support refactoring into a module or changing an indexed instance into a keyed one. Keep migration blocks until every relevant state has passed through the change. terraform state mv is the immediate command alternative, but it changes one state without a shared code record.

Release management without deleting data

A removed block, available from Terraform 1.7, can release a resource:

removed {
  from = aws_s3_bucket.archive
  lifecycle {
    destroy = false
  }
}

terraform state rm also forgets the association immediately. The real object stays. Simply deleting a resource declaration instead makes the next plan propose destruction. By contrast, -replace=ADDRESS keeps the address but creates a new object.

Select state and recover it carefully

CLI workspaces provide separate states for one configuration in the same backend. Commands include workspace new test, workspace select test, and workspace show; terraform.workspace exposes the selected name. Shared code, backend access, and credentials make them weak isolation for production. HCP Terraform workspaces have their own variables, permissions, state, and run history.

If state is lost but objects survive, import them again. If a snapshot is damaged, restore a verified earlier backend version or backup and compare it with reality. state pull reads the current snapshot; state push overwrites it and is a last-resort repair.

Key Takeaways

  • Import adopts a real object at a Terraform address; review differences after adoption.
  • Use moved blocks for address refactoring without recreating the object.
  • Use removed with destroy = false to release management while preserving the resource.
  • CLI workspaces separate state, but share backend access and usually credentials.
  • Confirm the selected state before applying changes or recovery operations.

3.3 Detect and resolve drift

Drift occurs when a managed resource changes outside its IaC workflow. A console edit, another tool, a platform action, or deletion can leave the real settings different from the definition and deployment record.

Compare three things

Think separately about code, the tool's record, and the live resource. Drift checks read the live settings.

Suppose Terraform code sets an Azure machine's size to Standard_B2s, but an incident responder changes it to Standard_D4s_v5. A normal plan proposes changing the real larger size back to the smaller defined size. Applying without review could undo the fix.

  • To keep the larger size, update the code and review a fresh normal plan.
  • To restore the smaller size, review and apply the existing intended setting.
  • If another process legitimately owns size, delegate that attribute through ignore_changes and document the ownership.

terraform plan -refresh-only previews changes to recorded values without proposing cloud corrections. terraform apply -refresh-only saves those live values into state without changing the infrastructure. It does not edit the configuration. If the code still names the smaller size, the next normal plan proposes the smaller size again. The older terraform refresh performs the state update without the same approval step and is deprecated.

Read CloudFormation drift results

CloudFormation drift detection compares supported managed resources with explicit template and parameter values. It reports statuses such as MODIFIED, DELETED, IN_SYNC, and NOT_CHECKED, along with expected and actual settings. Detection itself changes nothing. Unspecified default properties are not checked; unsupported resource types are not fully assessed.

Traditional change sets compare the proposed template with the previous deployed template. They can miss live drift. Drift-aware change sets, introduced in November 2025, also compare supported live settings and can preview reconciliation to the desired template. Adopting an accepted live value means updating the template; reverting means restoring the intended value through a suitable update or direct repair.

Compare Azure templates with live resources

Azure what-if compares the template with live resources. An outside property change appears as a modification when redeployment would overwrite it. Incremental deployment leaves resources absent from the template alone, but reapplies the desired configuration of resources it does define. Deployment-stack deny settings can restrict outside edits to managed resources.

Prevent recurring drift

Restrict ordinary production changes to the code path and keep routine console access read-only. Emergency access needs a recorded procedure that ends with accepted changes in code. Schedule checks and alerts so an opened port or deleted resource is found before the next release.

A clean result has a scope: Terraform manages objects in its state and can ignore chosen attributes; CloudFormation checks supported, explicitly defined properties. Unmanaged neighbors can escape those checks. An inventory or platform policy can catch problems beyond the IaC-managed resources.

Key Takeaways

  • Drift checks report outside changes; resolving them requires an ownership decision.
  • Refresh-only updates Terraform state, not code or infrastructure.
  • Keep an accepted manual change by updating the desired definition.
  • Traditional CloudFormation change sets and live drift checks compare different things.
  • Azure what-if compares the template with live resources.
  • Every drift result is limited by resource ownership and supported property checks.
4

Deploy Azure resources with ARM templates and Bicep

Azure Resource Manager can deploy either JSON templates or Bicep compiled to JSON. Learn to read both forms, pass environment settings, connect resources, and reuse components at the right scope. What-if makes the proposed changes visible before deployment. Deployment modes and stacks then decide what happens to resources that disappear from a definition, a separate question from how an included resource is updated.

4.1 Read and modify an ARM template

An ARM template is JSON describing Azure resources. Azure Resource Manager evaluates its expressions and performs the deployment. Reading its sections first makes an unfamiliar template much easier to modify.

Find inputs, calculations, and resources

The required top-level properties are $schema, contentVersion, and resources. The schema identifies the template kind and scope; contentVersion is the author's own version label. Optional sections include parameters, variables, outputs, and custom functions.

A storage resource declares its type, apiVersion, name, location, and settings. Its type is Microsoft.Storage/storageAccounts; sku, kind, and properties describe its configuration. The API version selects the resource contract, not the author's template revision.

Parameters are deployment inputs. They have types such as string, int, bool, object, or array, with optional defaults and limits. securestring and secureObject hide parameter values in deployment history. Variables compute internal values and cannot be overridden as deployment inputs.

A location parameter and a storage declaration connect like this inside a template:

{
  "parameters": {
    "location": { "type": "string" }
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2023-05-01",
      "name": "[concat('st', uniqueString(resourceGroup().id))]",
      "location": "[parameters('location')]",
      "sku": { "name": "Standard_LRS" },
      "kind": "StorageV2",
      "properties": { "allowBlobPublicAccess": false }
    }
  ]
}

The fragment shows the input and resource sections; the complete template also supplies its schema and contentVersion.

Follow expression evaluation

Expression strings use square brackets. For example, "[parameters('location')]" reads an input, while "[resourceGroup().location]" reads the group's location. Without the brackets, parameters('location') is just text.

"[concat('st', uniqueString(resourceGroup().id))]" builds a storage name. uniqueString returns a deterministic 13-character hash for the same input, so the st prefix gives 15 characters. It keeps the name stable across redeployments to that group. A globally unique name must still be available, and storage account names must contain 3 to 24 lowercase letters and digits.

A JSON parameter file has its own schema, contentVersion, and parameters object. A value such as "skuName": { "value": "Standard_GRS" } changes an environment setting without duplicating the template. A Key Vault reference can supply a secret without placing its value in the file. Keep secrets out of outputs, which are stored with deployment results.

Express order and repetition

Resource Manager can deploy independent resources in parallel. dependsOn orders a resource after another. A reference() or list*() call referring to a resource by name can establish an implicit dependency within the template. Passing a resource ID to the call does not establish that ordering; add dependsOn when it is needed.

A resource copy loop with count 3 and copyIndex() creates indexes 0, 1, and 2. A name made from stlogs, one index digit, and a 13-character hash has 20 characters. A condition can deploy a resource only for production. Outputs publish computed values, such as the new storage endpoint, for later work.

Make and check a modification

Add a parameter for a setting that differs by environment. Check resource documentation before changing an API version, since property contracts can change. Match dependency references to actual resource names, keep JSON valid, and preview with what-if.

Portal export and az group export can provide a starting template from existing resources. Exports can include fixed IDs, fixed names, and non-deployable properties; clean and parameterize them before reuse. Portal resource-group exports are limited to 200 resources.

Key Takeaways

  • Distinguish the deployment schema, author contentVersion, and resource apiVersion.
  • Parameters are external inputs; variables are internal calculations.
  • ARM expression strings require square brackets to be evaluated.
  • Review dependencies, loops, and conditions before changing resources.
  • Clean exported templates and keep secrets out of deployment outputs.

4.2 Write Bicep files and modules

Bicep expresses the same Azure deployment model as ARM JSON with less punctuation and stronger editor support. It compiles to ARM JSON, so resource support comes from Azure's resource APIs.

Write a resource with typed inputs
@allowed(['Standard_LRS', 'Standard_GRS'])
param skuName string = 'Standard_LRS'
param location string = resourceGroup().location
var storageName = 'st${uniqueString(resourceGroup().id)}'

resource stg 'Microsoft.Storage/storageAccounts@2023-05-01' = {
  name: storageName
  location: location
  sku: { name: skuName }
  kind: 'StorageV2'
  properties: {
    allowBlobPublicAccess: false
  }
}
output blobEndpoint string = stg.properties.primaryEndpoints.blob

stg is a symbolic name in the code. The name property names the real storage account. The type string includes the API version after @. Properties use colons, and string literals use single quotes.

Decorators add validation and documentation: @description, @allowed, length and number limits, and @secure() for secret inputs. If a name combines a prefix with the 13-character unique hash, a prefix limited to 11 characters stays within the 24-character storage limit. Apply toLower() as needed; length validation alone does not enforce lowercase letters or exclude punctuation.

Connect and repeat resources

A reference such as stg.id creates an implicit dependency when another resource needs that value. The existing keyword declares a resource managed elsewhere for lookup without deploying it. Child resources can set parent: stg.

A resource collection uses [for name in containerNames: { ... }]. A resource condition uses if (environment == 'prod'); a ternary expression selects a value such as a production storage SKU. These expressions describe the desired deployment, not an imperative sequence.

Reuse a file as a module

A module declaration points to another Bicep file, supplies a deployment name and params, and reads results through network.outputs.subnetId. It runs as a nested ARM deployment. A module can target another resource group through scope: resourceGroup('rg-shared').

Shared modules can come from a private Azure Container Registry with a br: reference or from Azure Verified Modules with a pinned version tag. Explicit versions make upgrades reviewable.

targetScope is resourceGroup by default and can be subscription, managementGroup, or tenant. Creating resource groups needs a subscription-scope deployment. Match the command to the scope; az deployment sub create --location westeurope --template-file main.bicep also sets the deployment record's location.

Build, parameterize, and convert

az bicep build --file main.bicep produces ARM JSON; Azure deployment commands also compile Bicep directly. A .bicepparam file starts with using './main.bicep' and declares parameter values checked against that template. JSON parameter files are also supported.

az bicep decompile --file azuredeploy.json provides a best-effort conversion from JSON. Review warnings and generated names. The linter catches issues such as unused parameters and secret outputs. Bicep does not add a separate state file: deployment still goes through Resource Manager.

Key Takeaways

  • Bicep compiles to ARM JSON and shares its Azure resource support.
  • Symbolic names support references and implicit dependencies.
  • Use existing for lookups and modules for reusable nested deployments.
  • Match targetScope to the deployment command and parameter file.
  • Build and lint before deployment; review decompiled code before reuse.
  • Length validation alone does not enforce every cloud naming rule.

4.3 Deploy, preview and track Azure deployments

An Azure deployment needs the correct scope, template, inputs, and permissions. Its preview must show both intended edits and the consequences of leaving resources or properties out.

Validate and preview at the right scope

A resource-group deployment uses az deployment group create with --resource-group, --template-file, and --parameters. The group must already exist; create it separately or through a subscription deployment. PowerShell offers New-AzResourceGroupDeployment.

Use az deployment group validate for preflight checks and az deployment group what-if for a live preview. Adding --confirm-with-what-if to create shows the preview and asks for confirmation before execution.

What-if reports Create, Delete, Modify, NoChange, and Ignore. Ignore can identify an existing resource outside the template. Deploy or Unsupported means the detailed outcome could not be predicted. Some property differences are preview noise, so examine their meaning before treating them as real changes.

Separate resource omission from property omission
SituationIncremental deployment behavior
A resource is in the templateCreate it or reapply its desired settings
A resource is absent from the templateLeave it in the resource group
A property is omitted from an included resourceIt can reset to the default

Incremental mode is the default and recommended mode. It is not a property patch. Describe the full desired configuration of each included resource, including non-default settings and subnet definitions that must remain.

If the group has A, B, and C, and the template defines A, B, and D, incremental mode leaves A, B, C, and D. Complete mode can delete C, leaving A, B, and D. Complete mode applies only to root resource-group deployments, is unavailable at subscription scope and in the portal, and is being gradually deprecated in favor of deployment stacks. Resource locks and resource-type deletion rules also affect deletion behavior.

Choose stack unmanagement behavior

A deployment stack tracks a resource collection. When a resource leaves its template, the stack's action-on-unmanage decides whether to detach it or delete it. detachAll keeps the objects, deleteResources deletes unmanaged resources, and deleteAll also includes resource groups.

Deny settings govern outside actions: none adds no protection, denyDelete blocks deletion but allows updates, and denyWriteAndDelete blocks both, subject to configured exclusions. Decide lifecycle behavior and outside-access protection separately.

Diagnose deployment results

Deployment history records the name, template, non-secret parameters, operations, status, and outputs. Resource-group history holds up to 800 deployments and automatically removes the oldest as it approaches the limit.

A failed deployment keeps successful changes. Inspect operations for the first useful failure, fix it, and redeploy. --rollback-on-error explicitly requests redeployment of a previous successful deployment. Wrong scope, missing write permissions, an unavailable global name, or an attempt to change an existing resource's type or location can cause failure. Preflight checks can catch some of these, but success still depends on the live deployment.

Key Takeaways

  • Use validation and what-if at the template's actual deployment scope.
  • Incremental mode keeps absent resources but reapplies included resource properties.
  • Complete mode can delete omitted resources; deployment stacks provide explicit lifecycle control.
  • Deployment stacks separate detach/delete behavior from deny settings.
  • Use deployment operations to diagnose partial failure before redeploying.
5

Deploy AWS resources with CloudFormation

CloudFormation turns an AWS template into a stack with a service-managed lifecycle. Learn to read references and resource attributes, then review change sets for replacements, access changes, and data risks. Stack events explain failures and rollback. Reuse choices depend on ownership: nested stacks share a lifecycle, exports connect independent stacks, and StackSets distribute a baseline across accounts and Regions.

5.1 Write a CloudFormation template

A CloudFormation template is JSON or YAML with a required Resources section. Other sections provide Parameters, Mappings, Conditions, Outputs, rules, metadata, and transforms. If present, AWSTemplateFormatVersion uses the fixed value 2010-09-09.

Identify resources and return values

A logical ID such as LogsBucket identifies a resource within the template. Its type, such as AWS::S3::Bucket, determines valid properties. The physical ID is the real AWS name or service-assigned ID. For many named types, CloudFormation generates a name when no custom name is supplied; EC2 instances receive service-assigned instance IDs.

Resources:
  LogsBucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      VersioningConfiguration:
        Status: Enabled
Outputs:
  BucketArn:
    Value: !GetAtt LogsBucket.Arn

!Ref LogsBucket returns the bucket name, while !GetAtt LogsBucket.Arn returns its ARN. Read the resource's return-value documentation before wiring a value into another property. !Ref and !GetAtt also create dependencies. Use DependsOn when a real ordering requirement has no reference, such as waiting for an internet-gateway attachment.

Adapt values without copying templates

Parameters have types and optional defaults, allowed values, patterns, and limits. AWS-specific types can validate selections such as VPC IDs. Systems Manager parameter types can retrieve a value such as an image ID at deployment.

A Mapping stores fixed choices by environment or Region. !FindInMap retrieves one. A Condition such as IsProd: !Equals [!Ref EnvName, prod] can decide whether a resource exists or feed !If to select a value. !Sub inserts parameter, resource, or pseudo-parameter values into strings. Other functions include !Join, !Select, and !GetAZs.

For example, !Sub "example-logs-${EnvName}-${AWS::AccountId}" combines environment and account identity. With prod and account 111122223333, the result is example-logs-prod-111122223333, a 30-character bucket name. AWS::Region and AWS::StackName are also built-in pseudo parameters.

Protect secrets and stored data

NoEcho: true masks a parameter in normal console and describe displays. It does not protect values copied into outputs or metadata. Secrets Manager dynamic references can fetch a secret during deployment without embedding its value in the template.

DeletionPolicy controls deletion of the stack or removal of a resource. UpdateReplacePolicy controls the old object during replacement. Retain preserves the object; Snapshot preserves a final snapshot for supporting types. RetainExceptOnCreate retains a resource except when its initial creation operation rolls back. A retained old bucket is not automatically copied into its replacement.

Validate structure, then review deployment

validate-template checks template syntax; cfn-lint adds resource and property checks against AWS specifications. Permissions, name availability, and quotas can still block execution. Template limits include 500 resources, 200 parameters, and 200 outputs. A direct template body is limited to 51,200 bytes; an S3-hosted template can be up to 1 MB.

Key Takeaways

  • Logical IDs identify declarations; physical IDs identify real AWS resources.
  • Use the documented Ref or GetAtt return value for each consuming property.
  • Parameters, Mappings, Conditions, and intrinsic functions make templates reusable.
  • DeletionPolicy and UpdateReplacePolicy govern different lifecycle events.
  • NoEcho does not protect a secret copied into outputs or metadata.
  • Syntax validation and linting do not guarantee successful deployment.

5.2 Create and update stacks with change sets

A stack is a set of resources CloudFormation manages from a template and parameter values. A change set is a preview of proposed stack operations; creating one does not execute it.

Separate preparation from execution

aws cloudformation create-stack creates a stack directly. aws cloudformation deploy prepares and executes a change set; add --no-execute-changeset to stop for review. The explicit sequence is create-change-set, describe-change-set, then execute-change-set after approval.

Review each resource's action and replacement status. Actions include Add, Modify, Remove, and Import; replacement may be True, False, or Conditional. Look at which property causes a replacement, not just whether the stack update is called a modification.

Follow a replacement through the data

Property documentation describes updates as No interruption, Some interruptions, or Replacement. Changing an EBS-backed instance's type stops and restarts it; changing its image replaces it. A bucket name change also requires replacement.

Suppose a change set adds a reports bucket, modifies a security group without replacement, and replaces a logs bucket after a name change. The new bucket starts empty. CloudFormation creates the replacement, updates references, and cleans up the old object according to its replacement policy. It does not migrate the logs. With default deletion behavior, cleanup of a non-empty old bucket can fail.

Keep the old name or plan an explicit migration and preservation strategy before executing. A replacement that keeps a fixed custom name can also fail because the new object cannot take a name still used by the old one. Generated names can avoid this collision, but do not solve data migration.

Understand statuses and recovery

A successful creation goes from CREATE_IN_PROGRESS to CREATE_COMPLETE. A default failed creation rolls back and can end at ROLLBACK_COMPLETE; delete that failed stack before trying creation again. A successful update ends at UPDATE_COMPLETE. A failed update normally attempts rollback and can finish at UPDATE_ROLLBACK_COMPLETE, leaving the previous stack configuration usable.

Read stack events to identify the failed resource and cause. Rollback is a recovery operation that can also encounter errors; monitor its result. It is not a substitute for reviewing a destructive change before execution.

Apply the right protection

A stack policy can block selected update actions on critical logical resources, such as replacing a production database. Termination protection blocks stack deletion. DeletionPolicy and UpdateReplacePolicy preserve resources or snapshots at their respective lifecycle events. Rollback triggers can monitor CloudWatch alarms during an update.

IAM resources require capability acknowledgment: CAPABILITY_IAM, or CAPABILITY_NAMED_IAM for custom names. Macros can need CAPABILITY_AUTO_EXPAND for direct create/update without first reviewing an expanded change set. These acknowledgments do not grant missing IAM permissions.

An IMPORT change set can adopt supported existing resources, each with a DeletionPolicy. Deleting a stack can still be blocked by non-empty buckets or by exported outputs that another stack imports.

Key Takeaways

  • Prepare and inspect a change set before executing it.
  • A replacement creates a new physical object and does not copy stored data.
  • Use events and status transitions to inspect failure and rollback.
  • Stack policies protect updates; termination protection protects stack deletion.
  • Capability acknowledgment is separate from permission to create IAM resources.

5.3 Reuse templates across stacks, accounts and Regions

Stack boundaries should match ownership and lifecycle. A shared network may change rarely while application resources change daily. Separating them limits the resources affected by an application error and lets each team manage its own release.

Connect independent stacks with exports

A producing stack exports an output under a name. A consuming stack reads it with !ImportValue. Export names are unique within an account and Region, and imports operate within that same account and Region.

While an export is in use, its value or name cannot simply be changed or removed, and the producing stack cannot be deleted. To rename an export safely:

  1. Add a second export with the new name.
  2. Update consumers to import the new name.
  3. Confirm nothing imports the old name, then remove it.

This overlap lets consumers migrate without breaking the existing connection. It is a dependency between independently deployed stacks, not shared ownership of the same resource.

Keep one deployment together with nested stacks

A nested stack is an AWS::CloudFormation::Stack resource. Its TemplateURL points to an S3 template, and its Parameters pass input values. The parent can read !GetAtt NetworkStack.Outputs.VpcId.

Nested components share the root stack's lifecycle. Update them through the root so CloudFormation can coordinate the whole deployment. aws cloudformation package uploads local nested templates and rewrites their paths for deployment.

NeedSuitable structure
One reusable component in a shared lifecycleNested stack
Separate owners sharing a few valuesIndependent stacks with exports
A looser value lookup without export locksSystems Manager Parameter Store

A Parameter Store lookup removes CloudFormation's export dependency lock, so teams must handle value changes and consumer coordination themselves.

Distribute a baseline with StackSets

A StackSet deploys one template as stack instances across accounts and Regions. Self-managed permissions require prepared IAM roles. Service-managed permissions integrate with AWS Organizations and can target an organizational unit, including automatic deployment to new accounts.

Concurrency, failure tolerance, and Region order control rollout. A baseline deployed to 12 accounts in 3 Regions gives 36 account-Region stack instances. The multiplication counts targets, not resources inside each stack.

Reuse inputs and authoring layers

Use Parameters, Mappings, and Conditions to adapt one template to development and production. Copying the whole template per environment makes future corrections drift apart. If a component needs more than the 500-resource template limit or a different owner, introduce a deliberate stack boundary.

AWS SAM uses the AWS::Serverless-2016-10-31 transform to expand compact serverless declarations. AWS CDK synthesizes a template with cdk synth. Both still deploy through CloudFormation stacks. Registry modules package reusable resource groups as resource types. Each layer changes how the template is authored; stack lifecycle and change review still matter.

Key Takeaways

  • Choose stack boundaries by owner, lifecycle, size, and blast radius.
  • An imported export locks the producing export against incompatible change or removal.
  • Nested stacks share a root lifecycle and should be updated through the root.
  • StackSets distribute a template across account-Region targets.
  • SAM and CDK change authoring while retaining CloudFormation deployment behavior.
6

Enforce standards with policy as code

Organizational rules become more dependable when they are versioned, tested, and checked automatically. Learn where policy checks run, how preventive and detective controls differ, and why a platform guardrail still matters after a clean template scan. Then follow a saved plan into a policy engine, interpret a finding, and test the rule itself so a faulty check does not block good changes or silently accept bad ones.

6.1 Explain policy as code and where policies run

Policy as code expresses organizational rules in machine-readable files that are versioned, tested, and evaluated automatically. Rules can cover security, cost, naming, and compliance: require owner tags, approved regions, blocked public storage, or database backups of at least 7 days.

Place checks where they can act
PositionWhat it checksTypical role
Before deploymentDefinitions or planned changesFast feedback and review gates
At deploymentRequests or a managed runReject a disallowed operation
After deploymentLive resource configurationFind drift and trigger remediation

A template scan sees the code submitted to it. It cannot stop a person making an unrelated console change. A deployment gate such as an Azure Policy deny rule can reject a matching request even when it comes from a different tool. Continuous evaluation can later detect changes or existing violations. Combining these positions provides defense in depth.

Preventive controls block changes; detective controls report them. Remediation changes an existing resource or adds something missing. An audit finding does not by itself mean the system repaired anything.

Understand a platform guardrail

Azure Policy has three main pieces. A definition describes the condition and effect. An initiative groups definitions. An assignment applies a definition or initiative to a scope, with parameters and possible exclusions.

A rule can test whether a resource is a storage account and whether allowBlobPublicAccess is true, then apply deny. Requests through the portal, CLI, Terraform, or Bicep all reach Azure Resource Manager's control plane and face the assignment. Uploading a blob or reading a secret uses a service's data plane and is not evaluated through that same ARM request path.

Effects include audit, deny, append, modify, auditIfNotExists, deployIfNotExists, denyAction, manual, and disabled. Modify and deployIfNotExists can remediate, but existing resources need a remediation task. AWS Organizations service control policies set permission ceilings for member-account identities; AWS Config rules evaluate live resources and can trigger remediation.

Roll out rules without hiding exceptions

Start by reporting violations, fix existing problems, then enforce. Azure DoNotEnforce keeps evaluation and reporting while disabling enforcement. In HCP Terraform, Sentinel advisory policies warn, soft-mandatory policies can be overridden by authorized users, and hard-mandatory policies block without override. OPA checks also support advisory and mandatory enforcement.

Use a narrow, recorded exception when a justified case cannot meet a rule. Azure exemptions can be Waiver or Mitigated, optionally with an expiry. Scanner skip comments should identify the rule and reason. Give each exception an owner and review date instead of disabling the rule for everyone.

A passing policy result means the checked evidence meets the rules that were written. Reviewers still judge architecture, requested behavior, cost, and operational effects. Rules automate repeatable checks, not the entire engineering decision.

Key Takeaways

  • Run policy checks before, at, and after deployment to cover different paths.
  • Preventive controls block; detective controls report; remediation changes resources.
  • Azure Policy definitions, initiatives, and assignments separate rule, grouping, and scope.
  • Platform guardrails evaluate supported requests from different provisioning tools.
  • Roll out blocking gradually and keep exceptions narrow, owned, and reviewable.

6.2 Check templates and plans before deployment

A pre-deployment policy check needs both useful evidence and a tested rule. Source scanners catch familiar configuration problems quickly. Plan checks can evaluate concrete input and module results before infrastructure changes.

Choose the evidence

Checkov, Trivy, KICS, and PSRule for Azure scan supported infrastructure formats and report findings with rule IDs, locations, and severities. cfn-lint checks CloudFormation correctness; a security policy scanner asks whether valid settings meet organizational rules. Trivy has absorbed the earlier tfsec scanner.

For Terraform, prepare a saved plan and its JSON form:

terraform plan -out=tfplan
terraform show -json tfplan > tfplan.json

The resource_changes entries include an address, type, actions, and planned after values. A replacement can contain both delete and create. Plan values may be more informative than unresolved source expressions, but some remain unknown until apply.

Read a small Rego rule

Open Policy Agent, or OPA, evaluates JSON with the Rego language. This Rego v1 rule finds creations missing an owner tag:

package terraform.tags

deny contains msg if {
  rc := input.resource_changes[_]
  "create" in rc.change.actions
  not rc.change.after.tags.owner
  msg := sprintf("%s is missing the owner tag", [rc.address])
}

The rule examines each resource change. It selects actions containing create, tests the tag, and emits a message naming the resource. Conftest can run it with conftest test tfplan.json --namespace terraform.tags. A pipeline or local gate treats nonempty deny results as failure.

If a bucket, database, and queue are being created and only the database has an owner, the result has two messages. Add the missing tags, regenerate the plan, and rerun the check. This rule checks missing tags on creations; it does not establish that existing tags have valid owners or that every update is covered.

Use the native policy options

Sentinel policy sets in HCP Terraform or Terraform Enterprise run between plan and apply. Advisory failures warn; soft-mandatory failures require an authorized, logged override; hard-mandatory failures stop the run without override. HCP Terraform can also run OPA checks.

CloudFormation Guard evaluates JSON or YAML against rules such as:

Resources.*[ Type == 'AWS::S3::Bucket' ] {
  Properties.VersioningConfiguration.Status == 'Enabled'
}

It selects S3 buckets and requires enabled versioning. Run cfn-guard validate --data template.yaml --rules s3.guard. Guard rules can also be used through CloudFormation Hooks at deployment.

Test policies and act on findings

Every rule needs a passing fixture and a failing fixture, run with tools such as opa test, sentinel test, or cfn-guard test. Tests catch a condition that accidentally approves everything or rejects every deployment. Review policy changes like infrastructure changes.

Run checks locally, on proposed changes, and at the apply gate. Prioritize serious findings, fix the definition, then make and check a fresh plan. Tune false positives and record justified exceptions. A scanner cannot assess an unknown value as a known-safe value or see an unrelated console edit. Keep live platform enforcement alongside early feedback.

Key Takeaways

  • Use source scans for fast feedback and plan JSON for resolved deployment evidence.
  • Check resource action arrays and after values when evaluating planned changes.
  • OPA/Rego, Sentinel, and Guard offer different policy execution paths.
  • Test each policy with both passing and failing examples.
  • Regenerate the plan after a correction and evaluate the new artifact.
  • Use platform enforcement and live checks for gaps a pre-deployment scan cannot see.

Infrastructure as Code examples

6 Walkthroughs

1

Choose a repeatable infrastructure workflow

12 steps
Follow a team from manual setup to a reviewed desired-state deployment, then choose the appropriate tool.
  1. 1
    IntroductionMake a design reproducible

    A team needs several environments for the same web application. Console instructions are already diverging: one environment has a different subnet setting and another has an extra machine.

    Infrastructure as code puts those choices into machine-readable definitions. You will follow how the team records intent, previews a change, and chooses a deployment tool.

  2. 2
    ExampleShare the definition, vary the inputs

    The application needs a network, two subnets, storage, and virtual machines. The team writes one definition and passes environment inputs: a name prefix and the required machine count.

    Development uses 1 machine; production uses 3. A new load-test environment uses the same design with another input set, so the team can inspect the actual differences instead of repeating console steps.

  3. 3
    TipReview consequences before applying

    The definition goes into Git. A pull request shows both the code edit and a preview of the operations that would reach the cloud.

    The team checks syntax, previews, reviews, applies, and verifies. A commit reversal restores an earlier definition, but it still needs a deployment; it does not recover deleted application data. Data-bearing resources need their own protection and backups.

  4. 4
    ChallengeKeep an emergency change

    During an incident, an administrator changes a managed firewall rule in the console. The team decides the new rule should remain. What must happen before the next normal deployment?

    ---reveal---

    Update the desired definition to include the accepted rule and review a fresh preview. The console edit created drift. A ticket records the event, but unchanged code can still cause a future deployment to restore the old rule.

  5. 5
    ExampleDistinguish a count from an action

    An imperative command says to launch 2 new instances. Run it twice successfully and it launches 4.

    A declarative resource count of 2 describes the intended number of managed instances. Reapplying the unchanged definition leaves 2. This illustrates idempotency: repeating an operation with the same input leaves the same resulting state as one run.

  6. 6
    ExplanationFollow the references

    A subnet declaration refers to its network. The tool adds an edge to its dependency graph and creates the network first. Another independent resource can be created at the same time.

    The order of declarations in the file does not determine this schedule. The graph also does not remove API failures: missing permissions, quotas, or an unavailable name can still stop the deployment.

  7. 7
    ChallengeClassify a program by its output

    A Python program uses loops to synthesize a CloudFormation template. Does the presence of loops make its provisioning imperative? Explain your decision.

    ---reveal---

    No. The program produces a desired-state template, and CloudFormation chooses the resource operations from that model. Programming-language syntax does not decide the infrastructure style; the important question is whether the deployed model describes desired resources or ordered actions.

  8. 8
    ExplanationCompare platform reach

    Terraform providers connect one workflow to different platforms, including cloud, DNS, and monitoring services. Bicep compiles to ARM JSON and targets Azure Resource Manager. CloudFormation manages AWS resources as a stack.

    Inputs, outputs, and reusable components exist in all three. The main choice is how their platform reach, deployment record, and operating model fit the team.

  9. 9
    ConnectionCompare failure recovery

    A partial Terraform apply keeps successful changes and records them in state. Azure normally keeps successful deployment operations too. CloudFormation normally attempts rollback of a failed stack operation.

    A team must therefore know which objects can remain after an error and where to inspect the record. Native deployment records remove the need for a Terraform backend, not the need to investigate failures.

  10. 10
    ChallengeChoose for external services

    A team manages Azure compute and DNS at an external provider. It wants both in one IaC workflow. What tool family fits, and does that make its Azure resources portable to AWS?

    ---reveal---

    Terraform can use providers for both platforms. The workflow is shared, but each resource type remains platform-specific. Moving the compute design to AWS needs AWS resource types and a suitable design; provider support does not make one resource declaration universal.

  11. 11
    ChallengeJudge a proposed shortcut

    A colleague proposes copying a production definition for each environment and applying edits without a preview because the tool is declarative. What two changes would improve this workflow?

    ---reveal---

    Use one reusable design with explicit environment inputs, and preview and review each deployment before apply. Copies can diverge, while a declarative model can still contain a destructive error. The shared design and review gate address different problems.

  12. 12
    RecapCarry intent into review

    A reliable workflow keeps the intended design, environment inputs, and deployment preview connected. Declarative tools calculate how to reach desired state; imperative commands still help with investigation and operational actions.

    Choose a tool by platform support, team skills, managed records, and recovery behavior. Keep accepted manual changes in the definition so the next run preserves the intended result.

2

Build and review a reusable Terraform change

19 steps
Connect declarations and inputs, trace stable identities, read a plan, and preserve resources while introducing a module.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionBuild toward a reviewable plan
  2. 2
    ExampleChoose a provider deliberately
  3. 3
    ExampleSeparate a label from a cloud name
  4. 4
    ChallengeSelect an allowed provider
  5. 5
    ExampleDeclare a typed input
  6. 6
    ExampleResolve competing input sources
  7. 7
    Key InsightKeep named objects stable
  8. 8
    ChallengePredict a keyed removal
  9. 9
    TipControl lifecycle without hiding intent
  10. 10
    ExplanationPrepare and validate
  11. 11
    ExampleRead the actions in a plan
  12. 12
    ExampleBuild the plan total
  13. 13
    ChallengeSpot a destructive total
  14. 14
    TipApply the reviewed artifact
  15. 15
    ExamplePackage a clear interface
  16. 16
    ExampleReuse the subnet calculation
  17. 17
    ChallengeChoose the source pin
  18. 18
    ChallengeRefactor without recreation
  19. 19
    RecapReview identity as well as values
3

Keep resource identity and resolve drift

16 steps
Follow a resource through state protection, import, refactoring, and an accepted manual change.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionKnow which record you are changing
  2. 2
    ExplanationProtect the shared mapping
  3. 3
    TipRead the lock before removing it
  4. 4
    Key InsightSeparate redaction from omission
  5. 5
    ChallengeAssess the secret path
  6. 6
    ExampleAdopt an existing bucket
  7. 7
    ExampleEstablish the baseline
  8. 8
    ExampleMove the address, keep the object
  9. 9
    ChallengeRelease ownership deliberately
  10. 10
    TipCheck the selected environment
  11. 11
    ExampleTrace a manual resize
  12. 12
    ExampleUnderstand refresh-only
  13. 13
    ChallengePredict the next normal plan
  14. 14
    ChallengeChoose the right comparison
  15. 15
    ChallengeConnect a move with an accepted change
  16. 16
    RecapChoose what should remain
4

Preview an Azure deployment at the right scope

17 steps
Read ARM and Bicep expressions, build reusable inputs, and decide what omission or unmanagement will do.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSeparate authoring from deployment
  2. 2
    ExplanationFind the template sections
  3. 3
    ExampleEvaluate the expression
  4. 4
    ChallengeOrder a resource-ID lookup
  5. 5
    TipReuse an exported definition
  6. 6
    ExampleRead the shorter Bicep form
  7. 7
    Key InsightUse the symbolic reference
  8. 8
    ExampleFit a generated name
  9. 9
    ExplanationCall a component at its scope
  10. 10
    ChallengeChoose inputs for production
  11. 11
    ExplanationRead the live preview
  12. 12
    ExampleKeep absent resources
  13. 13
    Key InsightDo not confuse omission levels
  14. 14
    ChallengePredict an omitted setting
  15. 15
    ExplanationSeparate lifecycle and protection
  16. 16
    ChallengeReview a handoff
  17. 17
    RecapRead the result and the history
5

Review a CloudFormation replacement and its dependencies

16 steps
Trace template values, protect a data resource, and choose stack boundaries that match ownership.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow the stack lifecycle
  2. 2
    ExampleIdentify the two names
  3. 3
    ExampleDeclare the preservation rules
  4. 4
    ChallengeChoose the return value
  5. 5
    TipValidate values and secrets
  6. 6
    ExplanationStop at the review gate
  7. 7
    ExampleTrace the new object
  8. 8
    ExampleCheck cleanup as well as creation
  9. 9
    ChallengeEvaluate a retention shortcut
  10. 10
    Key InsightMatch protection to the action
  11. 11
    ExplanationRead rollback through events
  12. 12
    ExplanationChoose a lifecycle boundary
  13. 13
    ExampleMigrate an export name
  14. 14
    ConnectionDistribute a baseline
  15. 15
    ChallengeReview a boundary change
  16. 16
    RecapApprove the actual lifecycle change
6

Turn a standard into a tested deployment gate

12 steps
Place a rule at the right lifecycle stages, evaluate planned values, and test the policy before enforcing it.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake a rule repeatable
  2. 2
    ExplanationGive each check a job
  3. 3
    ExampleApply a rule beyond one tool
  4. 4
    ChallengeClose a console gap
  5. 5
    TipRoll out and record exceptions
  6. 6
    ExamplePrepare concrete plan evidence
  7. 7
    ExampleFollow a creation rule
  8. 8
    ChallengeRead action arrays accurately
  9. 9
    ConnectionChoose enforcement deliberately
  10. 10
    TipTest both outcomes
  11. 11
    ChallengeReview a proposed apply
  12. 12
    RecapKeep evidence and enforcement connected

Infrastructure as Code practice questions

60 Practice Questions in 6 sets

Set 1: Parameterize, review, and reuse Terraform10 Practice Questions

Question 1 of 10

A local CLI run has a variable default of "test", TF_VAR_environment="stage", and terraform.tfvars setting environment = "prod". No other values are supplied. What value is used?
  1. "test".
  2. "stage".
  3. The run rejects the three differing values.
  4. "prod".
Show answerHide answer
Answer: D
For a local CLI run, terraform.tfvars outranks TF_VAR_ environment values and the variable default. Differing values are resolved by precedence, not treated as a conflict. The environment value would apply if no higher-precedence source supplied this variable.

Question 2 of 10

A Terraform plan has 2 new resources, 1 in-place update, and 2 replacements. What are its action totals?
  1. 2 to add, 3 to change, 2 to destroy.
  2. 4 to add, 1 to change, 2 to destroy.
  3. 4 to add, 3 to change, 0 to destroy.
  4. 2 to add, 1 to change, 4 to destroy.
Show answerHide answer
Answer: B
Each replacement counts as one new object and one destruction. The two replacements therefore add two to the two ordinary creations and contribute two destructions; the in-place update remains one change. Counting replacements as ordinary updates hides their destructive effect.

Question 3 of 10

A Terraform bucket collection is keyed with for_each by "audit", "assets", and "archive". The next definition removes only "assets". What happens to the remaining instance addresses?
  1. The archive address shifts into the former assets position.
  2. Both remaining addresses change as the collection shrinks.
  3. The audit and archive addresses keep their existing keys.
  4. The audit and archive addresses become indexes 0 and 1.
Show answerHide answer
Answer: C
With for_each, each instance is identified by its map or set key, so unrelated keys remain stable when one is removed. Shifting positions is the problem associated with count-driven lists. A keyed collection does not automatically turn into numeric indexes after deletion.

Question 4 of 10

Three uniquely named buckets use count with names from ["audit", "assets", "archive"]. Bucket-name changes require replacement. The middle name is removed, and no migration blocks are added. What plan follows?
  1. 0 to add, 0 to change, 1 to destroy.
  2. 1 to add, 0 to change, 2 to destroy.
  3. 1 to add, 1 to change, 1 to destroy.
  4. 2 to add, 0 to change, 1 to destroy.
Show answerHide answer
Answer: B
Index 1 changes from assets to archive, requiring replacement, while old index 2 disappears and is destroyed. That gives one addition and two destructions. Destroying only assets would require stable keyed identities or an appropriate migration; numeric positions have shifted here.

Question 5 of 10

A reviewer approves a saved Terraform plan. Another run then changes the same state before the approved plan is applied. What should happen?
  1. Terraform rejects the saved plan as stale; create and review a fresh plan.
  2. Terraform silently regenerates the plan and applies any newly discovered actions.
  3. Terraform applies the old actions and overwrites the newer state snapshot.
  4. Terraform accepts the plan if the configuration files have not changed.
Show answerHide answer
Answer: A
A saved plan is tied to the state it was created against. A newer state makes it stale even if the configuration files are unchanged. Silently substituting a fresh plan would bypass the approval, so a new result needs review before execution.

Question 6 of 10

A root sets environment = "prod", but a child module declares its own environment variable with default "dev". The module call passes no environment argument. What value does the child use?
  1. "prod", inherited from the root variable.
  2. The selected CLI workspace name, regardless of either variable.
  3. "dev", from its own variable default.
  4. An error, because child modules cannot declare defaults.
Show answerHide answer
Answer: C
Variables are scoped to their module, so the child uses its declared default. A matching variable name does not inherit the root value. To use production, the caller must pass the root value as the child's environment argument; workspaces do not replace that interface.

Question 7 of 10

A plan replaces one data-bearing server using -/+. The team needs uninterrupted service and must preserve its local files. What review decision addresses both requirements?
  1. Create the replacement first and copy files; switch traffic immediately when creation returns.
  2. Keep destroy-before-create and migrate files; resume traffic after the replacement starts.
  3. Create the replacement first and verify readiness; remove the old server before copying its files.
  4. Redesign readiness, traffic movement, and data migration before approving replacement.
Show answerHide answer
Answer: D
Replacement changes the object, so uninterrupted service needs a ready replacement and traffic handling, while local files need preservation or migration. Creating first only changes operation order. It neither copies files nor establishes that the replacement can safely serve traffic.

Question 8 of 10

A module moves a managed subnet from the root into a child and also moves its provider to an alias for the same account and region. What should be present before review?
  1. A moved block for the address change and explicit passing of the provider alias.
  2. A moved block for the address change, relying on automatic inheritance of the alias.
  3. An import at the new address while keeping the old mapping, plus explicit passing of the alias.
  4. Explicit passing of the alias, with a direct address rename and no migration record.
Show answerHide answer
Answer: A
The module path changes the subnet address, so a move preserves the existing object association. Aliased providers also require explicit passing to the child. An output does not migrate state, and an alias is not controlled by a module release-version argument.

Question 9 of 10

A team deletes a database resource block that contained prevent_destroy = true. Why can the next plan still propose deleting the database?
  1. The rule blocks only explicit destroy commands, not normal applies.
  2. The lifecycle protection disappeared with the resource declaration.
  3. The rule covers in-place updates only, never replacements or deletions.
  4. The rule stays permanent in state but is ignored for removed blocks.
Show answerHide answer
Answer: B
The lifecycle rule is part of the resource configuration; removing that entire block removes the rule as well. The old state still records a managed object whose declaration has gone, so deletion can be proposed. Use a deliberate preservation or release-of-management workflow instead of relying on the removed rule.

Question 10 of 10

A colleague runs terraform init using a committed provider lock file whose selection still satisfies the constraints. What provider behavior is expected?
  1. Reuse the locked selection unless an upgrade is requested.
  2. Choose the newest allowed provider on every initialization.
  3. Use the lock file to select the latest registry module release.
  4. Reject the lock file because constraints must specify one exact version.
Show answerHide answer
Answer: A
Normal initialization reuses a compatible locked provider version and verifies its checksums. init -upgrade is the deliberate route to a newer allowed selection. The lock file records provider dependencies; it does not pin registry module releases or require an exact version constraint.
Set 2: Choose an approach and read Terraform declarations10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A team keeps losing track of the console steps used to build test environments. What change most directly makes those environments reproducible?
  1. Keep the final resource names in a shared spreadsheet for administrators.
  2. Give every administrator the same console permissions in the test account.
  3. Put the resource definitions and environment inputs in version control.
  4. Write a release note after each manually completed environment build.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A successful command adds 3 new machines each time it runs. How many machines has it added after two runs?
  1. 3 machines.
  2. 6 machines.
  3. 9 machines.
  4. 2 machines.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A deployment file lists a subnet before its network, but the subnet refers to the network ID. How should a declarative tool schedule their creation?
  1. Create the network first, then create the dependent subnet.
  2. Create the subnet first, following the order of the declarations.
  3. Start both together, because all desired-state operations run in parallel.
  4. Require the author to move the network declaration above the subnet.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

One team must manage Azure resources, an external DNS service, and a monitoring service. What approach best provides one IaC workflow across all three?
  1. Bicep modules deployed for every external service.
  2. CloudFormation stacks with exports for Azure resources.
  3. One generic Terraform provider translating every resource.
  4. Terraform with a provider for each supported platform.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

An administrator enlarges a managed machine during an incident and the team decides to keep that size. What should happen before routine deployments resume?
  1. Keep the previous code and document only the console action in the ticket.
  2. Revert the last Git commit and assume the machine now has the accepted size.
  3. Remove all machine settings from the definition so future deployments skip it.
  4. Update the desired definition and review a fresh deployment preview.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A TypeScript program uses loops, then synthesizes a CloudFormation template that AWS deploys. Why is the infrastructure workflow declarative?
  1. Any program using loops becomes declarative when it runs against cloud APIs.
  2. The deployed artifact describes desired resources for CloudFormation to reconcile.
  3. The order of TypeScript statements directly controls every resource API call.
  4. The template prevents quotas and permission errors during resource creation.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A Terraform apply creates two resources successfully, then a third operation fails. What should the operator expect?
  1. The successful changes remain recorded in state for a fresh plan.
  2. The successful changes are automatically deleted to restore the old state.
  3. The state must be deleted before the same configuration can be used again.
  4. The failed resource is treated as created because the whole apply was approved.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A Terraform declaration uses resource "aws_s3_bucket" "audit" and sets bucket = "example-audit-data". What is its resource address?
  1. aws_s3_bucket.example-audit-data.
  2. aws.audit.bucket.
  3. aws_s3_bucket.audit.
  4. data.aws_s3_bucket.audit.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A provider constraint is ~> 6.18.0. There is no lock selection, and the available versions are 6.18.2, 6.19.1, and 7.0.0. Which version can initialization select?
  1. 6.19.1.
  2. 6.18.2.
  3. 7.0.0.
  4. 6.18.0 only.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An application needs an IAM policy attachment to finish before its server starts, but the server references only the role ID. The role and attachment are separate resources. How should the author represent this requirement?
  1. Keep only the role reference because it also waits for every role-related object.
  2. Place the attachment block before the server block and remove the role reference.
  3. Keep the role reference and add a dependency on the policy attachment.
  4. Add a dependency from the attachment to the server while keeping the role reference.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Protect state and reconcile outside changes10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What Terraform record associates a resource address with the real cloud object ID?
  1. The state snapshot.
  2. The provider lock file.
  3. The format settings.
  4. The variables file.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A second apply reports that another process holds the state lock. What should the operator do first?
  1. Force-unlock immediately and rerun the second apply against the same state.
  2. Delete the remote snapshot and let the second apply rebuild all mappings.
  3. Identify the owning run and determine whether it is still active.
  4. Disable locking and let both applies reconcile against the shared backend.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A resource is renamed in code from aws_s3_bucket.receipts to aws_s3_bucket.invoices, but should keep the same real bucket. What change should accompany the rename?
  1. A removed block that destroys the old address first.
  2. A new bucket name to create under the new resource address.
  3. A new CLI workspace so each address has separate state.
  4. A moved block from the old address to the new address.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A machine is resized manually and a refresh-only apply records the larger size. The code still requests the smaller size. What does a normal plan propose next?
  1. Keep the larger size, since refresh-only rewrote the desired code.
  2. Reconcile the machine back toward the smaller configured size.
  3. Create a second machine since refresh-only dropped the first.
  4. Ignore the size from now on, as refresh-only delegated that field.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

An existing bucket is imported at a root address. The team then wants it inside a module and wants another organization to manage it later, without deletion. Which sequence fits those separate stages?
  1. Reconcile after import, record a move into the module, then delete its declaration at handoff.
  2. Reconcile after import, record a move into the module, then release with destroy = false.
  3. Import into root and child addresses together, then forget both mappings at the later handoff.
  4. Reconcile after import, replace the bucket during the module move, then release with destroy = false.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A secret is read through an ordinary data source, marked sensitive, and passed to a normal password argument. Policy requires that its value never be saved in plans or state. What must change?
  1. Keep the ordinary lookup, hide the output, and encrypt the remote backend.
  2. Keep the ordinary lookup but pass its saved result to a write-only password argument.
  3. Use a supported ephemeral secret path into a compatible write-only argument.
  4. Use an ephemeral lookup but keep an ordinary password argument and mark it sensitive.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A removed block uses destroy = false for a managed archive bucket. What happens to the real bucket after the reviewed removal is applied?
  1. It remains, while Terraform releases its management association.
  2. It is deleted along with the removed resource declaration.
  3. It remains and still gets normal updates at its original address.
  4. Only a final snapshot remains, since releasing state snapshots data.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A CloudFormation stack reports IN_SYNC. One resource type does not support drift checking, and a security property on another resource was never set in the template. What can the team conclude?
  1. All properties matched, including those of unsupported resource types.
  2. Only the unsupported type needs checking; defaults were compared.
  3. Only the default property needs checking; IN_SYNC covered the rest.
  4. The checked properties matched; both gaps need separate verification.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Production and test need different cloud credentials and different state-read permissions. A proposal uses two CLI workspaces in one root with the same backend access and credentials. What design better meets the requirement?
  1. Two CLI workspaces in the same backend, keeping its shared credentials and permissions.
  2. Separate roots with separate credentials, but identical shared access to both state snapshots.
  3. Separate environment roots and state access, with each using its own credentials.
  4. Separate state access, but one shared credential with the same production rights for both runs.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An Azure resource group contains a manually created storage account absent from a proposed incremental template. What should the team expect from that deployment?
  1. The storage account is deleted because the template is the desired group inventory.
  2. The storage account is automatically imported into the template with its live settings.
  3. The deployment fails until every resource in the group is added to the template.
  4. The absent storage account remains outside that template's managed configuration.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Read and safely deploy Azure definitions10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A group contains resources K, L, and M. An incremental template defines K, L, and N. What resources remain after a successful deployment?
  1. K, L, M, and N.
  2. K, L, and N only.
  3. K, L, and M only.
  4. N only.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An ARM resource has apiVersion: "2023-05-01", while its template has contentVersion: "2.0.0.0". What does the resource API version select?
  1. The author's chosen revision number for the whole template.
  2. The resource contract and properties available for that type.
  3. The number of previous successful deployments kept in history.
  4. The deployment mode used to remove absent resource definitions.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

An ARM property is set to the JSON string "parameters('location')", and Resource Manager treats it as literal text. What change makes it an evaluated parameter reference?
  1. Use "{parameters('location')}" as the property value.
  2. Use "parameters.location" as the property value.
  3. Use "contentVersion('location')" as the property value.
  4. Use "[parameters('location')]" as the property value.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A Bicep template creates resource groups. It declares targetScope = 'subscription'. What command family matches that deployment?
  1. az deployment group create with any existing resource group.
  2. az deployment tenant create with a storage account location.
  3. az deployment sub create with a deployment-record location.
  4. az group export with a subscription-wide deployment name.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

An ARM NIC must wait for a network resource in the same template. Its only lookup calls reference() with the network resource ID, and no dependency is declared. Intermittent creation errors occur. What change best addresses the ordering gap?
  1. Keep the resource-ID lookup and move the NIC text below the network text.
  2. Add the needed dependency, or use a supported name-based reference that creates it.
  3. Keep the resource-ID lookup and make only the API version of both resources match.
  4. Add a dependency from the network to the NIC, leaving the NIC lookup unchanged.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A Bicep storage name is built from an input prefix plus a 13-character hash. The prefix can be 12 mixed-case letters or digits. What change meets the documented character and length constraints?
  1. Limit the prefix to 11 allowed characters and lowercase the complete name.
  2. Keep 12 characters, lowercase the name, and rely on the hash to shorten it.
  3. Limit the prefix to 11 characters but preserve uppercase letters in the name.
  4. Keep the prefix unchanged and mark it secure to bypass the name validation.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An included Azure resource has a manually configured non-default property that the incremental template omits. Why must the reviewer check that property before redeployment?
  1. Incremental mode always preserves every property missing from the template.
  2. Incremental mode automatically moves the omitted property into an output.
  3. The property causes every other resource in the group to be deleted first.
  4. An included resource's omitted property can reset to its default.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A Bicep file must read the ID of a Key Vault owned by another deployment without redeploying it. What declaration fits?
  1. A normal resource declaration with empty properties.
  2. A module creating a second vault with that name.
  3. An existing resource declaration for the vault.
  4. An output of the vault's symbolic-name text.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A deployment stack must keep a resource after it leaves the template. While it is managed, outside updates must be allowed but outside deletion blocked. Which settings meet both requirements?
  1. Use deleteResources with denyDelete.
  2. Use detachAll with denyWriteAndDelete.
  3. Use detachAll with denyDelete.
  4. Use deleteAll with denyWriteAndDelete.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A validated Azure deployment creates a network, then fails creating a storage account because of permissions. What is the appropriate next action?
  1. Correct permissions and retry immediately, assuming the earlier validation is still enough review.
  2. Inspect the failed operation, correct permissions, and review a fresh preview before retrying.
  3. Request rollback and retry without inspecting operations, assuming successful changes were undone.
  4. Delete the successful network and retry with the same permissions so the operation starts fresh.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Review AWS stacks and reuse boundaries10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A CloudFormation policy property needs the ARN of an S3 bucket with logical ID EvidenceBucket. What expression supplies it?
  1. !Ref EvidenceBucket.
  2. !Sub "EvidenceBucket".
  3. !GetAtt EvidenceBucket.Arn.
  4. !Ref AWS::StackName.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A data resource must be preserved both when removed from its template and when replaced during an update. Which resource attributes should express those choices?
  1. DeletionPolicy: Retain and UpdateReplacePolicy: Retain.
  2. DeletionPolicy: Retain and NoEcho: true on an input.
  3. UpdateReplacePolicy: Retain and a descriptive logical ID.
  4. Termination protection and NoEcho: true on an input.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A change set reports Modify with Replacement True for a bucket after its custom name changes. What happens to the stored objects automatically?
  1. They move into the new bucket before the old one is deleted.
  2. They are not copied into the new bucket by replacement.
  3. They are copied over because the action is labeled Modify.
  4. They are kept as a final snapshot of the old bucket.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Two independent application stacks import shared-net-v1. The network team wants the same value exported as shared-net-v2 and to remove the old export without interrupting either application. What sequence fits?
  1. Rename v1 to v2, then update each consumer at its next release.
  2. Delete v1 first, migrate both consumers, then add v2 with its value.
  3. Move one consumer to v2, delete v1, then migrate the other later.
  4. Add v2, migrate both imports, verify v1 is unused, then remove v1.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A password parameter has NoEcho: true and its value is also copied into Outputs. What should a security reviewer conclude?
  1. The output can expose the secret despite the masked parameter display.
  2. The output is masked because NoEcho applies transitively to every template use.
  3. The output is encrypted because every parameter value is stored in Secrets Manager.
  4. The output is omitted automatically because secure parameters cannot be referenced.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A database update needs replacement. The resource uses a fixed custom name that is unchanged, and both deletion and replacement policies are Retain. The team also needs existing records in the new database. What blocks approval?
  1. Retention avoids the name collision, but an explicit record migration is still required.
  2. The fixed name blocks creation, but retention transfers the records once that is fixed.
  3. Retention resolves both issues, but termination protection must be disabled for replacement.
  4. The unchanged name can block replacement creation, and retention does not migrate records.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A baseline StackSet targets 8 accounts in 4 Regions. How many account-Region stack instances are targeted?
  1. 12 stack instances.
  2. 32 stack instances.
  3. 8 stack instances.
  4. 4 stack instances.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A failed stack creation finishes at ROLLBACK_COMPLETE, and the team has corrected the template. What should it do with this failed stack before retrying creation?
  1. Apply an ordinary update to the failed stack as if it were CREATE_COMPLETE.
  2. Wait for UPDATE_COMPLETE because ROLLBACK_COMPLETE is still an active update.
  3. Delete the failed stack, then create it with the corrected template.
  4. Re-execute the failed creation change set without deleting the failed stack.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A shared network has its own owner and release schedule. An application has two reusable components that must be created and deleted together. What structure best matches both lifecycles?
  1. Keep the network and application components under one root with separately named nested stacks.
  2. Keep the network independent with exports; use nested stacks for the application components.
  3. Keep the network independent, but update the application nested stacks directly outside their root.
  4. Keep the network independent, but use StackSets to give each application component its own lifecycle.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An expanded template creates named IAM roles. The deployer acknowledges CAPABILITY_NAMED_IAM, but the execution role lacks permission to create those roles. What should happen, and why?
  1. The operation can fail; acknowledgment does not grant the missing role-creation permission.
  2. The operation succeeds because capability acknowledgment temporarily grants role-creation rights.
  3. The request succeeds after changing to CAPABILITY_AUTO_EXPAND to grant the missing rights.
  4. The update succeeds after changing to CAPABILITY_IAM because that avoids checking custom names.
Show answerHide answer

Save this lesson to see this answer.

Set 6: Enforce policies and diagnose evidence gaps10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A policy reports an unapproved region but allows the request to complete. What kind of control is it?
  1. A preventive control.
  2. A remediation action.
  3. A state migration.
  4. A detective control.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A policy selects planned resource changes containing create and emits a denial when their owner tag is missing. A plan creates 4 resources; 3 have owner tags. How many denial messages does it emit?
  1. 4 denial messages.
  2. 3 denial messages.
  3. 1 denial message.
  4. 0 denial messages.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A repository scanner passes, but someone later enables public storage access in the portal. The team needs early feedback and protection for future equivalent console changes. What control combination addresses both paths?
  1. Keep the scanner and assign a matching platform deny guardrail.
  2. Keep the scanner and add a platform audit rule that only reports.
  3. Keep the scanner and add a nightly job that reverts public access.
  4. Keep the scanner and rerun it on the repository after portal changes.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A Sentinel policy must block a run with no possibility of an authorized override. Which enforcement level fits?
  1. Advisory.
  2. Hard-mandatory.
  3. Soft-mandatory.
  4. DoNotEnforce.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A tag rule checks only changes whose actions contain create. One plan entry has actions ["delete", "create"] without an owner; another has ["update"] without an owner. What result follows from that rule alone?
  1. Both are denied because a missing owner triggers the rule regardless of the action filter.
  2. The replacement is denied; the update is outside this rule's selected actions.
  3. Neither is denied because the action array must equal create alone to satisfy membership.
  4. Only the update is denied because replacements are treated as existing resources for tag checks.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A new mandatory rule would block many existing projects. One project has a justified temporary exception. What rollout preserves accountability and avoids blocking every team immediately?
  1. Disable the rule everywhere, record the project name, and skip future evaluation.
  2. Enforce everywhere immediately, then let every project add an unexplained skip comment.
  3. Report first, repair violations, record a scoped expiring exception, then enforce.
  4. Delete the failing fixtures, enforce the rule, and treat all remaining failures as overrides.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A policy says storage must not be public. In a Terraform plan, the relevant value is unknown until apply. The scan currently treats a missing known value as passing. What should reviewers change?
  1. Assume unknown means false because a completed plan contains every final property value.
  2. Apply once with public access and count a later passing scan as pre-deployment assurance.
  3. Ignore the property in state so it can no longer appear as a policy violation.
  4. Handle unknown evidence deliberately and enforce the rule at a later supported gate.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An Azure Policy assignment uses deny for storage accounts allowing public blob access. Does changing the authoring tool from Bicep to Terraform avoid that control?
  1. No; matching ARM control-plane requests are evaluated from either tool.
  2. Yes; the assignment evaluates only templates compiled from Bicep.
  3. Yes; Terraform bypasses Resource Manager when it creates storage accounts.
  4. No; because the same assignment also evaluates every blob upload payload.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A policy gate approved a saved plan. An author then fixes a different finding in code and proposes applying the old saved plan because the source scan now passes. What must happen before apply?
  1. Apply the old saved plan because it automatically incorporates the current source edits.
  2. Generate a fresh plan, check that artifact, and obtain the required review.
  3. Keep the old saved plan and attach the new source-scan output without replanning.
  4. Make a fresh plan but reuse the old policy result because only the source text changed.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A custom rule passes its compliant fixture but also passes a fixture deliberately missing the required owner tag. What should the team do?
  1. Fix the rule or fixture expectation before making it an enforcement gate.
  2. Enforce it immediately because a passing compliant fixture proves the rule is useful.
  3. Delete the failing-case fixture because actual infrastructure will contain the tag.
  4. Lower the finding severity and assume the rule will reject violations during apply.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

97 Key Terms, each with its definition

A

API version
An API version selects the Azure resource contract for a declaration, including supported properties and their expected deployment behavior.
Before changing apiVersion, the author checks whether the new contract changes a property name or shape.
ARM template
An ARM template is a JSON desired-state description that Azure Resource Manager evaluates to deploy resources at the template's chosen scope.
A parameterized template builds a storage account with different redundancy settings for each environment.
AWS CDK
AWS CDK is an infrastructure authoring framework whose programs synthesize CloudFormation templates for declarative stack deployment.
A TypeScript program uses a loop, then cdk synth produces the template that CloudFormation deploys.
AWS SAM
AWS SAM is an authoring framework that expands compact serverless declarations through a transform into resources managed by CloudFormation.
A serverless function declaration expands into a Lambda function, its role, and related stack resources.
Azure Resource Manager
Azure Resource Manager is Azure's control-plane service for deploying and managing resource definitions at resource-group and broader scopes.
Both a Bicep deployment and a portal request to create a storage account reach Resource Manager.

B

Backend
A backend defines where Terraform stores state and how supported state operations, including coordination and locking, are handled.
An S3 backend uses a chosen bucket and key for the production network's shared state snapshot.
Bicep
Bicep is Azure's domain-specific authoring language that compiles to ARM JSON and supports typed inputs, symbolic resources, and modules.
A deployment command accepts a Bicep file and compiles it before sending the template to Resource Manager.
Bicep module
A Bicep module is a reusable Bicep deployment called with inputs and exposed outputs, which can also target a different Azure scope.
A subscription deployment calls a resource-group module and reads its resulting subnet ID.
Blast radius
Blast radius is the range of infrastructure that a mistake or failure can affect within a particular operation or management boundary.
Separating application state from shared network state limits what an application deployment can destroy.
Break-glass procedure
A break-glass procedure provides controlled emergency access and a record of urgent changes that must later be reconciled with infrastructure code.
After emergency network access is closed, the responder records the final accepted rule in the definition.

C

Capability acknowledgment
A capability acknowledgment explicitly accepts sensitive CloudFormation template behavior, such as creating IAM resources or expanding macros.
The deployer acknowledges named IAM resources but still needs permission to create those roles.
Change set
A change set is CloudFormation's preview of proposed stack actions and replacement requirements, prepared before the operations are executed.
The reviewer stops a change set after seeing that a simple name edit would replace the data bucket.
Child module
A child module is a Terraform configuration called by another module through declared inputs, outputs, and provider configuration relationships.
A root passes a network range to a child and reads its exported subnet IDs for the application.
CLI workspace
A CLI workspace selects one of several Terraform states for the same configuration and backend, usually sharing its access and credentials.
An operator checks the selected workspace before planning changes intended for a temporary test environment.
CloudFormation Guard
CloudFormation Guard is a rule tool for checking JSON or YAML infrastructure data against conditions written in its policy language.
A Guard rule selects every S3 bucket in a template and requires its versioning status to be Enabled.
Complete mode
Complete mode is an Azure root resource-group deployment mode that can delete resources absent from the template and is being deprecated for stacks.
A reviewer checks deletion predictions before a complete deployment to a group containing shared resources.
Configuration management
Configuration management installs and maintains software and settings inside existing servers, often after a provisioning tool creates them.
Terraform creates the machines, and an Ansible playbook configures the application software inside them.
Copy loop
A copy loop repeats an ARM resource declaration a chosen number of times, using an index to compute each instance's distinct settings.
A count of 3 produces indexes 0, 1, and 2 that can be included in the generated storage account names.
count
The count meta-argument creates Terraform instances addressed by zero-based numeric indexes, often for interchangeable or optional resources.
Removing a middle list item can shift the values assigned to later count-based resource indexes.
Cross-stack reference
A cross-stack reference lets one CloudFormation stack consume an exported output from another stack in the same AWS account and Region.
An application imports a shared network ID, preventing removal of that export until the dependency is removed.

D

Data source
A data source is a Terraform lookup that reads existing information without managing the lifecycle of the object or service it queries.
A zone data source supplies available locations without giving Terraform ownership of those zones.
Declarative provisioning
Declarative provisioning describes the desired infrastructure state and lets a tool determine the operations needed to reach it.
Changing the desired managed instance count from 4 to 5 makes the tool plan one additional instance.
Decompilation
Decompilation converts ARM JSON into a best-effort Bicep starting point that still needs review, cleanup, and meaningful symbolic names.
The team resolves conversion warnings before turning an exported JSON deployment into a shared module.
Decorator
A decorator adds validation, security handling, or documentation to a Bicep declaration, such as an allowed input list or maximum string length.
A prefix parameter has a maximum length so its generated storage name fits the service's total name limit.
DeletionPolicy
DeletionPolicy is a CloudFormation resource attribute deciding what happens when the stack is deleted or that resource leaves its template.
An archive bucket remains after stack deletion when its resource declaration uses the Retain policy.
Deny settings
Deny settings restrict outside actions on Azure deployment-stack resources, with modes for deletion alone or both writing and deletion.
A stack with denyDelete still permits outside updates unless another control rejects them.
Dependency graph
A dependency graph is a model of which resources need others first, allowing a deployment tool to order dependent operations and parallelize others.
The subnet waits for its network, while an unrelated storage resource can be created in parallel.
Dependency lock file
A dependency lock file records selected Terraform provider versions and checksums so repeated initialization can reuse the same providers.
A team commits .terraform.lock.hcl and reviews its changes when deliberately upgrading a provider.
Deployment history
Deployment history records Azure deployment templates, non-secret inputs, results, operations, and outputs at the deployment's scope.
An administrator reads a failed operation to identify the missing permission before retrying the deployment.
Deployment stack
A deployment stack tracks Azure resources as a collection with explicit behavior for unmanagement and optional deny settings for outside actions.
Removing a resource from its template can detach it or delete it according to the stack's chosen action.
Detective control
A detective control evaluates available evidence and reports a violation without itself blocking or repairing the non-compliant resource.
An audit rule reports a missing owner tag so the responsible team can decide how to correct it.
Drift
Drift is a difference caused by outside changes between a managed resource's real configuration and its IaC definition or deployment record.
An incident responder enlarges a machine in the portal while the code still specifies its original size.
Drift-aware change set
A drift-aware change set compares supported CloudFormation live resources, previous deployment settings, and the proposed desired template.
A reviewer sees whether an update would reverse a manual incident-response change before executing it.

E

Ephemeral value
An ephemeral value is a Terraform value available during a run but omitted from saved state and plans, subject to supported usage contexts.
A child module passes a temporary credential to a provider-supported write-only argument.

F

for_each
The for_each meta-argument creates a Terraform instance for each map entry or set member, using a stable key as the instance's identity.
In a bucket map keyed by logs and reports, removing the reports key leaves the logs bucket's instance address unchanged.

H

HCL
HCL is the configuration language used by Terraform to express blocks, arguments, references, and the desired relationships between resources.
A resource block uses labels for its type and local name, with arguments written as name = value.
HCP Terraform
HCP Terraform is HashiCorp's managed service for Terraform runs, state, history, and controls such as approvals and policy checks.
A workspace stores the environment's inputs and state while reviewers approve a remote plan before apply.

I

Idempotency
Idempotency is the property of an operation that leaves the same resulting state when repeated with the same input as when run once.
Applying an unchanged desired machine count again leaves the existing managed count unchanged.
ignore_changes
The ignore_changes lifecycle setting delegates selected Terraform resource attributes by excluding their differences from ordinary update planning.
A team delegates autoscaling capacity to another controller while still managing the group's other settings.
Immutable infrastructure
Immutable infrastructure is infrastructure updated by replacing existing instances with new instances built from an updated image or definition.
A team builds new application machines from the revised image and then shifts traffic to them.
Imperative provisioning
Imperative provisioning describes an ordered sequence of actions that creates or changes infrastructure from its current starting condition.
A script creates a network, then creates its subnet, then launches a machine using that subnet.
Import
Import associates an existing cloud object with a managed infrastructure declaration so the IaC tool can track its lifecycle from that point.
After importing a manually created bucket, the team reviews differences between its settings and the code.
Incremental mode
Incremental mode creates or updates resources in an Azure template while leaving resources absent from the template in the resource group.
An unrelated bucket stays, but an omitted setting on an included resource can still reset to its default.
Infrastructure as code
Infrastructure as code is the practice of defining infrastructure in machine-readable files and using tools to manage resources from those files.
A team reviews a network definition before applying the proposed subnet and access-rule changes.
Input variable
An input variable is a named, typed value supplied to a Terraform module to customize its configuration without changing the resource design.
A root module accepts an environment name and validates it against the allowed deployment environments.
Intrinsic function
An intrinsic function is a CloudFormation operation that resolves references, builds values, or chooses template values during deployment.
!GetAtt LogsBucket.Arn supplies an ARN where !Ref LogsBucket would supply only a bucket name.

L

Lifecycle rule
A lifecycle rule customizes how Terraform treats a resource's replacement, destruction, or selected attribute changes during reconciliation.
A database uses prevent_destroy while its resource declaration and protection rule remain present.
Local value
A local value is a name for a computed expression inside a Terraform module, allowing the expression to be reused without making it an input.
A shared tag map is merged with each resource's specific tags through a named local value.
Logical ID
A logical ID is a resource's unique identifier within a CloudFormation template, separate from the real object's name or service-assigned ID.
The template refers to LogsBucket while AWS assigns that bucket its physical name during deployment.

M

Module interface
A module interface is the declared set of inputs and outputs through which a Terraform caller supplies settings and obtains component results.
The child exposes a VPC ID without requiring its caller to know every internal resource address.
Module source
A module source identifies where Terraform obtains a child module, such as a local directory, a registry address, or a pinned Git repository.
A registry module uses a version constraint, while a Git source uses ref in its source URL.
Moved block
A moved block records a change from one Terraform resource address to another while keeping its association with the same real object.
A resource moved into a module can retain its bucket instead of being destroyed and recreated.
Mutable infrastructure
Mutable infrastructure is infrastructure maintained by changing existing instances in place, including their software or settings.
An administrator updates the configuration on an existing server while preserving that server's identity.

N

Nested stack
A nested stack is a CloudFormation stack declared as a resource of another stack so the root coordinates its deployment and lifecycle.
The parent passes network inputs into a nested template and reads its VPC ID from the nested outputs.

O

OPA
OPA is a general-purpose policy engine that evaluates structured input with Rego rules and returns decisions for an integrating tool to enforce.
A plan-review gate fails when OPA produces denial messages for resources missing required tags.
OpenTofu
OpenTofu is an open-source fork of Terraform, created in 2023, that follows a familiar HCL configuration and state-based provisioning workflow.
A team considering OpenTofu still needs provider-specific resources and protected state storage.
Output
An output is a declared result of an infrastructure definition that exposes a value to a caller or to later deployment work.
A network module publishes subnet IDs so an application module can attach resources to those subnets.

P

Parameter file
A parameter file supplies environment-specific input values separately from a shared infrastructure template so the design can be reused.
Production selects its storage SKU through inputs while using the same resource definition as test.
Physical ID
A physical ID is the actual AWS name or identifier of a resource that CloudFormation associates with a template's logical resource.
Replacing an instance changes its physical instance ID even though the template's logical ID stays the same.
Plan
A plan is Terraform's proposed set of resource operations after comparing the desired configuration with its state and refreshed cloud information.
A reviewer checks replacement details before authorizing an image update for the application machines.
Policy as code
Policy as code expresses organizational rules as machine-readable, version-controlled policies evaluated automatically against infrastructure evidence.
A proposed storage change fails a rule requiring public access to remain blocked in production.
Policy assignment
A policy assignment applies an Azure Policy definition or initiative to a chosen scope with inputs and possible exclusions.
The same rule is assigned to several subscriptions, each with its own approved-region parameter values.
Policy exemption
A policy exemption records a scoped Azure exception, categorized as Waiver or Mitigated, with a reason and optional expiration.
A temporary exception names the responsible team and an end date instead of disabling the rule globally.
Policy fixture
A policy fixture is a sample input with an expected check result, used to test that a rule accepts compliant cases and rejects violations.
The rule suite includes one plan with required owner tags and another with a deliberately missing tag.
Policy initiative
A policy initiative groups several Azure Policy definitions so related organizational standards can be assigned and managed together.
A baseline initiative groups storage-access and tagging rules while each definition keeps its own condition.
Preventive control
A preventive control blocks an operation that violates its rules before the disallowed change completes through the controlled deployment path.
An Azure deny policy rejects an unapproved-region resource request from either Bicep or Terraform.
Provider
A provider is a Terraform plugin that defines platform-specific resource types and translates their operations into calls to that platform's API.
A configuration uses one provider for cloud storage and another for an external DNS service.
Provider alias
A provider alias names an additional configuration of one Terraform provider, such as a connection to a second account or region.
A backup bucket selects aws.backup to use the alternate provider configuration for its region.
Pseudo parameter
A pseudo parameter is a built-in CloudFormation value, such as the AWS account ID, Region, or stack name, available without an input declaration.
A name expression combines the environment input with AWS::AccountId to distinguish accounts.

R

Refresh-only run
A refresh-only run reads Terraform-managed objects and proposes or saves changes to state without reconciling infrastructure toward the code.
Recording a manual resize in state still leaves a normal plan free to propose the size specified in code.
Rego
Rego is OPA's policy language for querying structured data and expressing decisions, such as sets of denial messages from a Terraform plan.
A rule selects creation actions and names each resource whose planned owner tag is missing.
Removed block
A removed block records that Terraform should stop managing a resource, with lifecycle settings deciding whether to destroy or preserve it.
Using destroy = false releases an archive bucket from management while leaving its data in place.
Repeatability
Repeatability is the ability to run a defined infrastructure process again and reproduce its intended environment from the same design.
A replacement test environment is built from the reviewed definition with its saved environment inputs.
Replacement
A replacement deletes an existing managed object and creates a new object for the same declaration because an in-place change is unsuitable.
Changing an immutable resource property can produce one addition and one destruction in plan totals.
Resource address
A resource address identifies a Terraform declaration or instance, including its module path and instance key when those apply.
The address module.storage.aws_s3_bucket.logs differs from the cloud bucket's actual name.
Rollback
Rollback is CloudFormation's attempt to reverse a failed stack operation toward its prior stable configuration, with progress recorded in events.
A failed update finishes rollback and leaves the stack ready for a corrected, newly reviewed update.
Root module
A root module is the Terraform configuration in the directory where commands run, including all of that directory's Terraform configuration files.
Splitting declarations across several .tf files leaves them part of the same root module.

S

Saved plan
A saved plan is an executable Terraform planning result that can be reviewed and then supplied to apply without another confirmation prompt.
The team applies the saved artifact it reviewed instead of producing a different plan at execution time.
Semantic versioning
Semantic versioning labels releases as major.minor.patch, using the major part to signal a breaking interface or behavior change.
A caller reviews the upgrade to a new major network-module release before adopting its changed inputs.
Sentinel
Sentinel is HashiCorp's policy language used by HCP Terraform and Terraform Enterprise to evaluate plans before approved changes are applied.
A soft-mandatory failure pauses the run until the rule passes or an authorized override is recorded.
Stack
A stack is a group of AWS resources that CloudFormation tracks and manages together from a template and its parameter values.
An application stack owns a queue and a function, so their lifecycle is coordinated by CloudFormation.
Stack instance
A stack instance is a StackSet's deployment at a particular account and Region target, distinct from individual resources inside that stack.
Seven accounts targeted in two Regions produce fourteen stack instances before counting their resources.
Stack policy
A stack policy restricts selected CloudFormation update actions on specified stack resources, such as replacement of a critical database.
When a stack policy denies replacing a database, an application update can proceed only if it avoids that replacement.
StackSet
A StackSet distributes one CloudFormation template as stack instances across selected AWS accounts and Regions with rollout controls.
A logging baseline targets an organizational unit and can extend to newly added member accounts.
State
State is Terraform's record linking managed resource addresses to real object IDs, together with stored attributes, outputs, and other metadata.
Without the mapping, a fresh configuration cannot recognize an existing bucket as its managed object.
State lineage
State lineage is the identity assigned to a Terraform state history, helping detect an unrelated snapshot being written over the current state.
A recovery operator checks lineage and serial safeguards before considering a last-resort state push.
State locking
State locking coordinates access so competing Terraform operations cannot write the same state simultaneously and corrupt their shared record.
A second apply waits or reports the lock owner instead of independently updating the same mapping.
State snapshot
A state snapshot is one recorded version of Terraform's resource mappings and values, which may differ from the current live infrastructure.
Restoring yesterday's snapshot requires checking whether today's successful deployment created more resources.
Static analysis
Static analysis examines infrastructure definitions without deploying them, reporting issues such as invalid settings or rule violations.
A developer scans a proposed template locally before producing a reviewed deployment preview.
Symbolic name
A symbolic name identifies a Bicep declaration in code so other declarations can read its attributes and express dependencies through references.
A dependent resource reads stg.id even though the cloud storage account has a different actual name.

T

Targeted run
A targeted run restricts Terraform's work to selected resources and their dependencies, leaving other parts of the configuration unreconciled.
An operator uses -target for exceptional recovery, then reviews a full plan for the whole environment.
targetScope
The targetScope setting selects whether a Bicep file deploys at resource-group, subscription, management-group, or tenant scope.
A file that creates resource groups uses subscription scope and a matching subscription deployment command.
Template expression
A template expression is a bracketed ARM string evaluated during deployment to read parameters, compute values, or reference resource properties.
[resourceGroup().location] supplies the deployment group's location instead of the literal expression text.
Termination protection
Termination protection blocks deletion of a CloudFormation stack, providing a different safeguard from policies that restrict resource updates.
An attempted stack deletion is refused even though ordinary resource updates may still be permitted.

U

UpdateReplacePolicy
UpdateReplacePolicy is a CloudFormation resource attribute deciding whether to delete, retain, or snapshot the old object during replacement.
A new database can be created while the old database is retained for a separately planned data migration.

W

What-if
What-if is Azure Resource Manager's preview that compares a proposed template with live resources and reports predicted resource and property changes.
The preview shows whether redeploying a defined machine would overwrite its manually changed settings.
Write-only argument
A write-only argument sends a supported resource value to a provider without persisting that argument's value in Terraform state or saved plans.
A supported database password argument receives a temporary secret without storing it in the snapshot.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started