Split every automation into stages: a read-only check of the current state, a preview that lists the exact changes, an approval, a small first batch that records what it changed, and an independent check afterwards. Decide the way back for each kind of change before the first real run: replaying a saved record, redeploying the previous version, or - for data deletion and other one-way actions - a restore-tested backup or no automation at all. Treat a preview as a prediction to review, not a guarantee.
What a preview can and cannot tell you
A dry run is a run of the automation that reads the current state and reports what it would change, without changing anything. Every tool has its own name for it: -WhatIf in PowerShell, check mode in Ansible, a plan in Terraform, a change set in AWS CloudFormation. The value is simple. The first mistake lands in a report someone can read, rather than in production.
The catch is that a preview is a prediction, and its accuracy depends on the tool and on every module or command inside it. Ansible's own documentation calls check mode a simulation, says modules without check mode support do nothing and report nothing, and warns that tasks depending on results from earlier tasks may produce no useful output. AWS states that change sets do not guarantee a stack update will succeed. Terraform notes that other changes to the target system can alter the outcome between a plan and the apply that follows.
So design for a preview that can be wrong. Use it as a review document, back it with checks before and after the change, and settle the recovery route in advance. A script that has only ever been run for real is a hypothesis with admin rights.
Before you begin
You do not need a large programme to start. You need a handful of practical things in place:
- A safe place to try it: a test machine, a spare folder, a non-production resource group or a small pilot group. A preview is only as good as the state it reads, so the test target should resemble the real one.
- The automation's source kept in version control, or at least in dated copies, so the previous working version can be found again.
- Where the platform allows it, a read-only account for previews. Many previews only need to read the live system, and an account that cannot change anything cannot make a bad preview worse.
- A named person who approves the preview before a real run, and somewhere to keep the preview output and the record of what the real run did.
The stages a safely changeable automation goes through
Whether the tool is a ten-line script or a deployment pipeline, the order is the same. The point of separating the stages is that each one can stop the run before the next one starts. The automation should also be idempotent, meaning that running it twice leaves the same end state as running it once; that makes re-runs after an interruption far less alarming.
- Check the starting state without changing anything. Gather what the automation is about to touch and save it. Stop if the picture is not what you expected, for example the target list is empty, or ten times longer than usual.
- Produce the preview. It should list each individual change in words a person can read: this file, this account, this setting, from this value to that one. Keep the output with the run record.
- Approve it. A person compares the preview with what they meant to do. Add a rule-based guard as well, such as refusing to continue if the preview contains more changes than a stated maximum. People skim long lists; a limit does not.
- Apply in small batches, a pilot item or group first. Write a record as each item changes: what it was, what it became, when and under which account. That record is also the raw material for rollback.
- Verify by asking the system, not the script. A script reporting success only tells you it finished. Query the target and compare the result with what the preview promised.
- Decide whether to roll back or roll forward. Rolling back restores the earlier state. Rolling forward means leaving the change in place and fixing it with a further change, which is often the only honest option when the original change cannot be reversed.
Add a preview and a guard to a PowerShell script
PowerShell has the preview built in. Add SupportsShouldProcess to a function's CmdletBinding and PowerShell supplies -WhatIf and -Confirm for you. Your code then asks $PSCmdlet.ShouldProcess before each change; under -WhatIf it returns false after printing what would have happened. Microsoft recommends placing that call as close to the change as possible, so the gathering and validation code still runs during a preview and shows its errors.
The example below moves old export files into an archive folder and writes a manifest, a plain CSV list of what went where, so the move can be reversed. It reads the source folder, creates files only in the archive folder and moves files only after ShouldProcess allows it. Try it on a test folder first. Run it as a standard user with access to just those two folders.
Why the explicit -Confirm:$false on the inner commands? Microsoft's guidance is to suppress nested prompts once you have already handled confirmation, otherwise a reader who passes -Confirm gets asked twice for every file.
- Save the function below as Move-StaleExport.ps1 on a test machine. It stops before touching anything if the archive folder does not exist or if more files qualify than the MaximumFiles limit allows, and both checks still run during a preview.
function Move-StaleExport { [CmdletBinding(SupportsShouldProcess)] param( [Parameter(Mandatory)] [string]$SourcePath, [Parameter(Mandatory)] [string]$ArchivePath, [int]$OlderThanDays = 90, [int]$MaximumFiles = 50 ) if (-not (Test-Path -LiteralPath $ArchivePath -PathType Container)) { throw "Archive folder not found: $ArchivePath" } $manifest = Join-Path $ArchivePath 'manifest.csv' $cutoff = (Get-Date).AddDays(-$OlderThanDays) $candidates = @( Get-ChildItem -LiteralPath $SourcePath -File | Where-Object { $_.LastWriteTime -lt $cutoff } ) if ($candidates.Count -gt $MaximumFiles) { throw "$($candidates.Count) files qualify, which is more than the limit of $MaximumFiles. Stopping." } foreach ($file in $candidates) { $destination = Join-Path $ArchivePath $file.Name if (Test-Path -LiteralPath $destination) { Write-Warning "Skipping $($file.Name): a file with that name is already in the archive." continue } if ($PSCmdlet.ShouldProcess($file.FullName, "Move to $ArchivePath")) { Move-Item -LiteralPath $file.FullName -Destination $destination -ErrorAction Stop -Confirm:$false [pscustomobject]@{ Original = $file.FullName Moved = $destination When = (Get-Date -Format 'o') RunBy = $env:USERNAME } | Export-Csv -Path $manifest -Append -NoTypeInformation -Confirm:$false } } } - Create two empty test folders and a few old test files, then load the function and run it with -WhatIf. Replace the folder paths with your own test folders. This run only reads: the output should show lines beginning What if: for each file that would be moved. Check that no file has moved and that no manifest.csv has appeared in the archive folder.
. .\Move-StaleExport.ps1 Move-StaleExport -SourcePath 'C:\AutomationTest\Exports' -ArchivePath 'C:\AutomationTest\Archive' -OlderThanDays 90 -WhatIf - Read the list. If it matches what you expected, run the same command again without -WhatIf. Each qualifying file moves to the archive folder and one line per file is added to manifest.csv. Open the manifest and the source folder to confirm they agree.
Move-StaleExport -SourcePath 'C:\AutomationTest\Exports' -ArchivePath 'C:\AutomationTest\Archive' -OlderThanDays 90 - Do not assume the preview reaches everything the function calls. Microsoft's documentation says -WhatIf and -Confirm settings are not reliably inherited when a function in one script module calls a function in another script module, and advises testing rather than trusting. Before relying on a preview in any larger script, run it with -WhatIf against a harmless target and confirm nothing changes.
Previewing changes in Ansible, Terraform and CloudFormation
The same discipline applies to configuration tools, with a different set of traps. In each case, read the whole preview rather than the summary line at the bottom.
- Ansible: --check runs the playbook as a simulation and --diff shows before-and-after comparisons where a module supports them. Limit the run to one test host, because diff output gets long. Confirm in each module's documentation that it supports check mode, since modules that do not simply do nothing and report nothing. Tasks that gather information you need later can be forced to run in check mode with check_mode: false, and diff: false hides output that might contain secrets. Treat shell and command tasks as unpreviewed until you have confirmed otherwise.
ansible-playbook site.yml --check --diff --limit YOUR_TEST_HOST - Terraform: terraform plan -out saves the plan to a file and terraform apply with that file carries out exactly what was recorded, without asking for confirmation, so passing the file is your approval. Treat the saved file as sensitive because it holds variable values, including sensitive ones, in clear text. If the state has changed since the plan was made, expect Terraform to reject the old plan and ask for a fresh one. Options such as -refresh=false and -target can hide drift, meaning changes made to the real system outside Terraform, and can produce incomplete plans. Reserve them for exceptional cases.
terraform plan -out=tfplan terraform show tfplanterraform apply tfplan - CloudFormation: create a change set for the stack, read the list of resources it would add, modify or replace, and only then execute it. The preview checks for common failure causes such as syntax errors, name conflicts and service quotas, but failures caused by runtime conditions can still happen when the change set executes. Pay particular attention to anything marked as a replacement or deletion.
Decide how each change comes back
Rollback is not one feature. It depends on what kind of change you made, and generic advice here does mislead. Sort each action your automation takes into one of these groups before the first real run:
- Restorable from a record. Moves, renames, setting changes and group memberships can be reversed if the automation saved the before-state, which is what the manifest in the PowerShell example is for.
- Restorable by redeploying the previous version. Configuration held in version control can be re-applied from an earlier commit. Terraform does not automatically roll back a partially completed apply, so after a failed run you fix the error and apply again, and re-applying an older configuration is itself a change that deserves its own plan. Read it before approving it, particularly for anything created since.
- Rolled back by the platform. CloudFormation can roll back a stack operation when a CloudWatch alarm you nominate goes into the ALARM state, and it watches during the update and for a monitoring period afterwards of up to 180 minutes. Alarms you have not created cannot trigger anything, so this only works if you decide in advance what a bad outcome looks like.
- Not undoable. Deleted data, sent messages, reset credentials and anything that affects people outside your organisation cannot be pulled back by re-running a script. For these, require explicit human approval, take a backup you have restored from at least once, or leave them out of automation. NCSC guidance advises regularly testing that backups work as expected and scanning them for malware before restoring. Where no clean undo exists, plan to roll forward with a corrective change.
- Use the manifest to preview the reversal of the PowerShell example. This reads the manifest and only reports what it would move back, using -WhatIf. It skips any file where something already exists at the original location, so it cannot overwrite newer work. Replace the path with the one for your test archive.
Import-Csv -Path 'C:\AutomationTest\Archive\manifest.csv' | ForEach-Object { if (Test-Path -LiteralPath $_.Original) { Write-Warning "Not restoring $($_.Original): a file already exists there." } else { Move-Item -LiteralPath $_.Moved -Destination $_.Original -WhatIf } } - If the preview lists exactly the files you expect, run the same command again with -WhatIf removed. The files return to their original folder. Check the source folder to confirm they are back, then compare the count with the manifest.
Import-Csv -Path 'C:\AutomationTest\Archive\manifest.csv' | ForEach-Object { if (Test-Path -LiteralPath $_.Original) { Write-Warning "Not restoring $($_.Original): a file already exists there." } else { Move-Item -LiteralPath $_.Moved -Destination $_.Original } }
Assess an automation someone else built
If you are a business owner or manager rather than the person writing the script, you do not need to read the code. You need to see evidence that the stages above exist. This works for something a colleague, supplier or contractor has built, and it keeps everyone safe because each step is read-only until the pilot.
- Ask for the preview output from the most recent run and the record of what the last real run changed. If neither exists, that is your answer: the automation cannot currently be reviewed before it acts or reconstructed afterwards.
- Have an administrator run the preview against a test scope using a read-only account if the platform allows one. Compare the list it produces with the list you expected, and ask what the preview cannot see, such as tasks or modules without preview support.
- Check the guard. In the test environment, point the automation at a deliberately oversized scope and confirm it refuses to continue rather than ploughing on. If there is no limit on how many things one run can change, ask for one.
- Run a single pilot item for real, verify it by looking at the target system directly, then run the rollback for that item and verify that it returned to its original state. An undo that has never been used is a belief, not a control.
- Check the logs. NCSC guidance on administering systems says to log administration activities so you can check that only legitimate, approved actions took place, with each entry showing who acted, when, from where and what they did. It also says logs should be protected against unexpected modification, so the account the automation runs as should not be able to edit its own history.
If the preview and the real run disagree
Some mismatch is normal. These are the usual causes and what to do about each:
- The preview was clean but the real run failed part-way. Runtime conditions such as permissions, locks, quotas or a service that was briefly unavailable are outside what most previews can see. Add precondition checks at the start, run in small batches and make sure the record shows which items completed.
- The preview showed nothing, but something changed. Look for tasks that cannot preview, such as modules without check mode support, or scripts that call external commands that do their own thing regardless of -WhatIf. Add an explicit check or guard around them, or run them as a separate, manually approved step.
- The plan was approved but the environment moved on. Other people and automations change the same systems. If time has passed since the preview, or a saved plan is rejected, produce a fresh preview and re-approve it rather than forcing the old one through.
- A rollback finds something unexpected. If another change has touched the same objects since the original run, replaying the saved record can overwrite newer work. Compare the current state with the record first, and prefer a small corrective change when the original state no longer applies.
Technical terms explained
- change set
- An AWS CloudFormation preview that lists what an update would add, modify or delete in a stack. Nothing changes until you choose to execute it.
- check mode
- Ansible's preview mode, started with --check. It simulates a playbook, but only modules that support it can report what they would do.
- drift
- Differences between what your automation or configuration says should exist and what is actually there, usually because someone changed the live system directly.
- dry run
- A run of an automation that reports what it would change without changing anything. Names differ by tool: -WhatIf in PowerShell, check mode in Ansible, plan in Terraform and change set in CloudFormation.
- idempotent
- Safe to run more than once: after the first run, repeating it leaves the system in the same state rather than making further changes.
- manifest
- A simple record, here a CSV file, of what an automation changed, so the changes can be reviewed or reversed.
- roll forward
- Fixing a bad change by making a further corrective change, instead of restoring the previous state. Often the only option when the original change cannot be reversed.
- ShouldProcess
- The PowerShell mechanism behind -WhatIf and -Confirm. A function asks it before each change; during a preview it reports the change and tells the function not to proceed.
Sources and further reading
- Everything you wanted to know about ShouldProcess - Microsoft Learn
- about_CommonParameters (WhatIf and Confirm) - Microsoft Learn
- Validating tasks: check mode and diff mode - Ansible documentation
- terraform plan command reference - HashiCorp Developer
- terraform apply command reference - HashiCorp Developer
- Update CloudFormation stacks using change sets - AWS Documentation
- Roll back your CloudFormation stack on alarm breach with rollback triggers - AWS Documentation
- Log and audit administration activities - NCSC secure system administration
- Mitigating malware and ransomware attacks - NCSC