- Learn
- Computer Science & IT
- Information Technology
- Cloud Architecture and Administration
- Infrastructure as Code
Infrastructure as Code
IntermediateLesson 7 of 8 in Cloud Architecture and Administration Course
What you will learn
- 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 solvesExplain 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 provisioningTell 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 suitCompare 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.
- Describe infrastructure as code and the problems it solves
- 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 HCLWrite 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 expressionsParameterize 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 applyingInitialize, 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 modulesPackage resources into modules with clear inputs and outputs, call them from local paths, registries and Git, and control which module version each environment uses.
- Declare providers, resources and data sources in HCL
- 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 stateDescribe 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 stateBring existing resources under Terraform management, rename or restructure code without recreating resources, use workspaces with care, and recover state.
- Detect and resolve driftRecognize drift between code and real resources, find it with each tool's checks, and decide whether to revert, adopt or ignore each change.
- Explain, store and protect Terraform state
- 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 templateIdentify the sections of an ARM JSON template, follow its expressions, loops and dependencies, and change it without breaking the deployment.
- Write Bicep files and modulesWrite 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 deploymentsDeploy templates at the right scope, preview changes with what-if, choose a deployment mode, and manage resources as a unit with deployment stacks.
- Read and modify an ARM template
- Write CloudFormation templates, create and update stacks through reviewed change sets, and reuse templates across stacks, accounts and Regions.
- Write a CloudFormation templateUse 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 setsFollow 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 RegionsSplit infrastructure into stacks that work together, nest reusable templates, deploy one template to many accounts and Regions, and use the tools built on CloudFormation.
- Write a CloudFormation template
- Write rules that check infrastructure definitions and deployments automatically, and place them before, during and after deployment.
- Explain policy as code and where policies runDescribe 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 deploymentScan IaC files with ready-made rule sets, write and test custom rules for Terraform plans and CloudFormation templates, and act on the findings.
- Explain policy as code and where policies run
Infrastructure as Code study guide
1Explain 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:
- Edit the definition and the environment's inputs.
- Check syntax, types, and formatting.
- Preview the resulting creates, updates, and deletions.
- Review the preview, including data and access changes.
- 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
| Approach | What the author supplies | How work is chosen |
|---|---|---|
| Imperative | Ordered commands | The script encodes the steps and checks |
| Declarative | Desired resources and settings | The 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
| Tool | Definition and platform | Deployment record | Preview |
|---|---|---|---|
| Terraform | HCL; provider plugins for many platforms | State maintained by the team or HCP Terraform | Plan |
| ARM/Bicep | ARM JSON or Bicep compiled to JSON; Azure | Azure resources and deployment history | What-if |
| CloudFormation | JSON or YAML; AWS | Stack managed by AWS | Change 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.
2Write 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.
| Symbol | Action |
|---|---|
+ | 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
| Source | How it is selected |
|---|---|
| Local directory | A relative path such as ./modules/network |
| Registry | A module address plus a version constraint |
| Git | A Git source URL pinned with ?ref= |
| Private registry or archive | A 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.
3Manage 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_changesand 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.
4Deploy 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
| Situation | Incremental deployment behavior |
|---|---|
| A resource is in the template | Create it or reapply its desired settings |
| A resource is absent from the template | Leave it in the resource group |
| A property is omitted from an included resource | It 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.
5Deploy 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:
- Add a second export with the new name.
- Update consumers to import the new name.
- 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.
| Need | Suitable structure |
|---|---|
| One reusable component in a shared lifecycle | Nested stack |
| Separate owners sharing a few values | Independent stacks with exports |
| A looser value lookup without export locks | Systems 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.
6Enforce 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
| Position | What it checks | Typical role |
|---|---|---|
| Before deployment | Definitions or planned changes | Fast feedback and review gates |
| At deployment | Requests or a managed run | Reject a disallowed operation |
| After deployment | Live resource configuration | Find 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
1Choose a repeatable infrastructure workflow
12 steps
- 1IntroductionMake 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.
- 2ExampleShare 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.
- 3TipReview 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.
- 4ChallengeKeep 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.
- 5ExampleDistinguish 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.
- 6ExplanationFollow 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.
- 7ChallengeClassify 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.
- 8ExplanationCompare 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.
- 9ConnectionCompare 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.
- 10ChallengeChoose 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.
- 11ChallengeJudge 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.
- 12RecapCarry 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.
2Build and review a reusable Terraform change
19 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionBuild toward a reviewable plan
- 2ExampleChoose a provider deliberately
- 3ExampleSeparate a label from a cloud name
- 4ChallengeSelect an allowed provider
- 5ExampleDeclare a typed input
- 6ExampleResolve competing input sources
- 7Key InsightKeep named objects stable
- 8ChallengePredict a keyed removal
- 9TipControl lifecycle without hiding intent
- 10ExplanationPrepare and validate
- 11ExampleRead the actions in a plan
- 12ExampleBuild the plan total
- 13ChallengeSpot a destructive total
- 14TipApply the reviewed artifact
- 15ExamplePackage a clear interface
- 16ExampleReuse the subnet calculation
- 17ChallengeChoose the source pin
- 18ChallengeRefactor without recreation
- 19RecapReview identity as well as values
3Keep resource identity and resolve drift
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionKnow which record you are changing
- 2ExplanationProtect the shared mapping
- 3TipRead the lock before removing it
- 4Key InsightSeparate redaction from omission
- 5ChallengeAssess the secret path
- 6ExampleAdopt an existing bucket
- 7ExampleEstablish the baseline
- 8ExampleMove the address, keep the object
- 9ChallengeRelease ownership deliberately
- 10TipCheck the selected environment
- 11ExampleTrace a manual resize
- 12ExampleUnderstand refresh-only
- 13ChallengePredict the next normal plan
- 14ChallengeChoose the right comparison
- 15ChallengeConnect a move with an accepted change
- 16RecapChoose what should remain
4Preview an Azure deployment at the right scope
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSeparate authoring from deployment
- 2ExplanationFind the template sections
- 3ExampleEvaluate the expression
- 4ChallengeOrder a resource-ID lookup
- 5TipReuse an exported definition
- 6ExampleRead the shorter Bicep form
- 7Key InsightUse the symbolic reference
- 8ExampleFit a generated name
- 9ExplanationCall a component at its scope
- 10ChallengeChoose inputs for production
- 11ExplanationRead the live preview
- 12ExampleKeep absent resources
- 13Key InsightDo not confuse omission levels
- 14ChallengePredict an omitted setting
- 15ExplanationSeparate lifecycle and protection
- 16ChallengeReview a handoff
- 17RecapRead the result and the history
5Review a CloudFormation replacement and its dependencies
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow the stack lifecycle
- 2ExampleIdentify the two names
- 3ExampleDeclare the preservation rules
- 4ChallengeChoose the return value
- 5TipValidate values and secrets
- 6ExplanationStop at the review gate
- 7ExampleTrace the new object
- 8ExampleCheck cleanup as well as creation
- 9ChallengeEvaluate a retention shortcut
- 10Key InsightMatch protection to the action
- 11ExplanationRead rollback through events
- 12ExplanationChoose a lifecycle boundary
- 13ExampleMigrate an export name
- 14ConnectionDistribute a baseline
- 15ChallengeReview a boundary change
- 16RecapApprove the actual lifecycle change
6Turn a standard into a tested deployment gate
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake a rule repeatable
- 2ExplanationGive each check a job
- 3ExampleApply a rule beyond one tool
- 4ChallengeClose a console gap
- 5TipRoll out and record exceptions
- 6ExamplePrepare concrete plan evidence
- 7ExampleFollow a creation rule
- 8ChallengeRead action arrays accurately
- 9ConnectionChoose enforcement deliberately
- 10TipTest both outcomes
- 11ChallengeReview a proposed apply
- 12RecapKeep evidence and enforcement connected
Infrastructure as Code practice questions
Set 1: Parameterize, review, and reuse Terraform10 Practice Questions
Question 1 of 10
"test", TF_VAR_environment="stage", and terraform.tfvars setting environment = "prod". No other values are supplied. What value is used?Show answerHide answer
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
Show answerHide answer
Question 3 of 10
for_each by "audit", "assets", and "archive". The next definition removes only "assets". What happens to the remaining instance addresses?Show answerHide answer
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
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?Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
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?Show answerHide answer
Question 7 of 10
-/+. The team needs uninterrupted service and must preserve its local files. What review decision addresses both requirements?Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
prevent_destroy = true. Why can the next plan still propose deleting the database?Show answerHide answer
Question 10 of 10
terraform init using a committed provider lock file whose selection still satisfies the constraints. What provider behavior is expected?Show answerHide answer
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
resource "aws_s3_bucket" "audit" and sets bucket = "example-audit-data". What is its resource address?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
~> 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?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
aws_s3_bucket.receipts to aws_s3_bucket.invoices, but should keep the same real bucket. What change should accompany the rename?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
destroy = false for a managed archive bucket. What happens to the real bucket after the reviewed removal is applied?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
apiVersion: "2023-05-01", while its template has contentVersion: "2.0.0.0". What does the resource API version select?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
"parameters('location')", and Resource Manager treats it as literal text. What change makes it an evaluated parameter reference?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
targetScope = 'subscription'. What command family matches that deployment?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
reference() with the network resource ID, and no dependency is declared. Intermittent creation errors occur. What change best addresses the ordering gap?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
EvidenceBucket. What expression supplies it?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
NoEcho: true and its value is also copied into Outputs. What should a security reviewer conclude?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
ROLLBACK_COMPLETE, and the team has corrected the template. What should it do with this failed stack before retrying creation?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
CAPABILITY_NAMED_IAM, but the execution role lacks permission to create those roles. What should happen, and why?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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
create. One plan entry has actions ["delete", "create"] without an owner; another has ["update"] without an owner. What result follows from that rule alone?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
API version
apiVersion, the author checks whether the new contract changes a property name or shape.ARM template
AWS CDK
cdk synth produces the template that CloudFormation deploys.AWS SAM
Azure Resource Manager
B
Backend
Bicep
Bicep module
Blast radius
Break-glass procedure
C
Capability acknowledgment
Change set
Child module
CLI workspace
CloudFormation Guard
Complete mode
Configuration management
Copy loop
count
count meta-argument creates Terraform instances addressed by zero-based numeric indexes, often for interchangeable or optional resources.Cross-stack reference
D
Data source
Declarative provisioning
Decompilation
Decorator
DeletionPolicy
Deny settings
denyDelete still permits outside updates unless another control rejects them.Dependency graph
Dependency lock file
.terraform.lock.hcl and reviews its changes when deliberately upgrading a provider.Deployment history
Deployment stack
Detective control
Drift
Drift-aware change set
E
Ephemeral value
F
for_each
for_each meta-argument creates a Terraform instance for each map entry or set member, using a stable key as the instance's identity.logs and reports, removing the reports key leaves the logs bucket's instance address unchanged.H
HCL
name = value.HCP Terraform
I
Idempotency
ignore_changes
ignore_changes lifecycle setting delegates selected Terraform resource attributes by excluding their differences from ordinary update planning.Immutable infrastructure
Imperative provisioning
Import
Incremental mode
Infrastructure as code
Input variable
Intrinsic function
!GetAtt LogsBucket.Arn supplies an ARN where !Ref LogsBucket would supply only a bucket name.L
Lifecycle rule
prevent_destroy while its resource declaration and protection rule remain present.Local value
Logical ID
LogsBucket while AWS assigns that bucket its physical name during deployment.M
Module interface
Module source
version constraint, while a Git source uses ref in its source URL.Moved block
Mutable infrastructure
N
Nested stack
O
OPA
OpenTofu
Output
P
Parameter file
Physical ID
Plan
Policy as code
Policy assignment
Policy exemption
Policy fixture
Policy initiative
Preventive control
Provider
Provider alias
aws.backup to use the alternate provider configuration for its region.Pseudo parameter
AWS::AccountId to distinguish accounts.R
Refresh-only run
Rego
Removed block
destroy = false releases an archive bucket from management while leaving its data in place.Repeatability
Replacement
Resource address
module.storage.aws_s3_bucket.logs differs from the cloud bucket's actual name.Rollback
Root module
.tf files leaves them part of the same root module.S
Saved plan
Semantic versioning
Sentinel
Stack
Stack instance
Stack policy
StackSet
State
State lineage
State locking
State snapshot
Static analysis
Symbolic name
stg.id even though the cloud storage account has a different actual name.T
Targeted run
-target for exceptional recovery, then reviews a full plan for the whole environment.targetScope
targetScope setting selects whether a Bicep file deploys at resource-group, subscription, management-group, or tenant scope.Template expression
[resourceGroup().location] supplies the deployment group's location instead of the literal expression text.Termination protection
U
UpdateReplacePolicy
W
What-if
Write-only argument
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.