Configuration Management¶
Configuration management is how a hardening baseline stays applied after the day you applied it. Without it, every manual fix, vendor install script and 03:00 troubleshooting session slowly moves servers away from the baseline — and scanners and auditors find the difference.
Three jobs:
- Define the desired state as code (versioned, reviewed).
- Detect when reality differs (drift).
- Correct — either automatically, or by deciding the code is what's wrong and updating it.
Contents¶
- Drift: what it is and where it comes from
- Choosing tools
- Repository layout and workflow
- Ansible
- PowerShell DSC
- Azure Machine Configuration
- Group Policy
- Intune and Defender for Endpoint security settings management
- Detecting drift
- Auto-correct or alert?
- Handling a drift event
- Testing configuration code
- Secrets in configuration
- Golden images and configuration management together
Drift: what it is and where it comes from¶
Drift is any difference between the declared state and the actual state of a server.
| Source | Example | Usually… |
|---|---|---|
| Emergency manual change | Firewall rule opened during an incident, never closed | Unauthorised-ish; revert or codify |
| Vendor installer | App install disables a security setting or adds a service | Codify an exception or fix installer |
| Package update | Upgrade replaces a config file or re-enables a default | Make config management own the file |
| Troubleshooting leftovers | Debug logging left on, test user created | Revert |
| Another management tool | GPO and DSC both manage the same setting with different values | Pick one owner per setting |
| Malicious change | Persistence via scheduled task, new admin account | Security incident, not drift |
The last row is why drift detection is a security control: a sudden change in local administrators or SSH authorized keys should page someone, not just appear in a weekly report.
Choosing tools¶
| Tool | Platforms | Model | Strengths | Weaknesses |
|---|---|---|---|---|
| Ansible | Linux, Windows (WinRM/SSH), network gear | Push (agentless), idempotent tasks | Huge module ecosystem; --check --diff makes drift detection easy; works anywhere SSH reaches |
No continuous enforcement unless scheduled; Windows support is good but less natural than DSC |
| PowerShell DSC 1.1 / 2.0 (PSDSC) | Windows (1.1 built into Windows PowerShell 5.1), PS 7 for 2.0 | Declarative; Local Configuration Manager (LCM) can auto-correct | Native Windows resources; continuous ApplyAndAutoCorrect |
Legacy; MOF compilation; pull server retired in Azure (see below) |
Microsoft DSC v3 (dsc) |
Windows, Linux, macOS | Declarative CLI (JSON/YAML), no LCM service | Modern, cross-platform, written in Rust, can use existing PSDSC resources via adapters; v3.3 released September 2026 | Bring your own scheduling/orchestration |
| Azure Machine Configuration (Azure Policy) | Azure VMs + Arc servers, Windows and Linux | Policy-driven audit or auto-correct | Compliance in Azure Policy; works on Arc; replaces Azure Automation State Configuration | Authoring custom packages is more involved; billed on Arc unless covered |
| Group Policy | Domain-joined Windows | Pull, periodic refresh (~90 min ± 30; security settings re-applied every 16h by default) | Ubiquitous; CIS and Microsoft baselines ship as GPOs | Windows/domain only; weak reporting; drift visibility limited |
| Intune + Defender for Endpoint security settings management | Windows clients; servers for endpoint-security policies via MDE | Cloud policy | Manage AV/firewall/ASR/EDR policy on servers from Intune without MDM enrolment | Not a general server config tool |
Retirement dates that affect choices¶
- Azure Automation State Configuration retires September 30, 2027 — migrate to Azure Machine Configuration.
- DSC extension for Azure VMs retires March 31, 2028.
- Azure Automation DSC for Linux and the Linux DSC extension already retired (September 2023).
A sensible split for a hybrid estate¶
| Layer | Owner tool |
|---|---|
| Linux OS baseline (CIS), packages, services, users, sshd, sysctl, auditd | Ansible |
| Windows domain members: security policy, user rights, audit policy | GPO (CIS/Microsoft baseline GPOs) |
| Windows non-domain / workgroup / Arc-only servers | DSC (v3 or PSDSC via Machine Configuration) or Ansible |
| Compliance reporting across both (Azure + Arc) | Azure Machine Configuration in audit mode |
| Endpoint protection policy (AV, firewall, ASR) | Intune via MDE security settings management, or GPO |
| Application config | App deployment pipeline (not the OS config tool) |
Rule: one owner per setting. If GPO and Ansible both set SMB signing, one of them will eventually lose an argument with the other at 3 a.m. Document the owner per setting family.
Repository layout and workflow¶
infra-config/
├── README.md
├── inventories/
│ ├── azure_rm.yml # dynamic inventory for Azure VMs
│ ├── arc.py # Resource Graph-driven inventory for Arc machines
│ └── onprem/hosts.yml
├── group_vars/
│ ├── all.yml
│ ├── env_prod.yml
│ └── role_web.yml
├── roles/
│ ├── baseline_linux/ # CIS L1 + local deviations
│ ├── baseline_windows/
│ ├── sshd/
│ ├── auditd/
│ └── ...
├── playbooks/
│ ├── baseline.yml
│ └── drift-report.yml
├── dsc/
│ ├── windows-baseline.dsc.yaml # DSC v3
│ └── machine-configuration/ # packages for Azure Machine Configuration
├── molecule/ # role tests
└── .gitlab-ci.yml
Workflow:
- Change proposed as a merge request (linked to finding, exception, or change ticket).
- CI runs lint + tests (ansible-lint, Molecule, PSScriptAnalyzer,
dsc config testagainst test VMs). - Peer review; security review for baseline changes.
- Merge → deploy to non-prod ring → drift report clean → promote to prod ring (same rings as patching).
- Scheduled drift detection runs continuously against main.
Ansible¶
Inventory for a hybrid estate¶
Azure VMs with the azure.azcollection.azure_rm inventory plugin:
# inventories/azure_rm.yml
plugin: azure.azcollection.azure_rm
auth_source: auto
include_vm_resource_groups:
- "*"
conditional_groups:
linux: "os_profile.system == 'linux'"
windows: "os_profile.system == 'windows'"
keyed_groups:
- prefix: env
key: tags.env | default('none')
- prefix: patch_group
key: tags['patch-group'] | default('none')
- prefix: role
key: tags.role | default('none')
hostvar_expressions:
ansible_host: private_ipv4_addresses[0]
Arc-enabled servers aren't Azure VMs, so generate inventory from Resource Graph (or keep on-prem hosts in a static inventory that your CMDB exports):
#!/usr/bin/env python3
# inventories/arc.py — minimal dynamic inventory for Arc machines via Azure Resource Graph
import json, subprocess, sys
q = """resources
| where type =~ 'microsoft.hybridcompute/machines'
| project name, os = tostring(properties.osType), status = tostring(properties.status),
fqdn = tostring(properties.dnsFqdn), env = tostring(tags.env), role = tostring(tags.role)"""
rows = json.loads(subprocess.check_output(
["az", "graph", "query", "-q", q, "--first", "1000", "-o", "json"]))["data"]
inv = {"_meta": {"hostvars": {}}, "arc": {"hosts": []}}
for r in rows:
if r["status"] != "Connected":
continue
h = r["name"]
inv["arc"]["hosts"].append(h)
for g in (f"env_{r['env'] or 'none'}", f"role_{r['role'] or 'none'}", r["os"].lower()):
inv.setdefault(g, {"hosts": []})["hosts"].append(h)
inv["_meta"]["hostvars"][h] = {"ansible_host": r["fqdn"] or h}
if len(sys.argv) > 1 and sys.argv[1] == "--host":
print("{}")
else:
print(json.dumps(inv))
Baseline role excerpts¶
# roles/sshd/tasks/main.yml
- name: Deploy hardened sshd drop-in
ansible.builtin.template:
src: 50-hardening.conf.j2
dest: /etc/ssh/sshd_config.d/50-hardening.conf
owner: root
group: root
mode: "0600"
validate: /usr/sbin/sshd -t -f %s
notify: Restart sshd
- name: Ensure sshd_config includes drop-ins
ansible.builtin.lineinfile:
path: /etc/ssh/sshd_config
regexp: '^Include /etc/ssh/sshd_config.d/\*\.conf'
line: "Include /etc/ssh/sshd_config.d/*.conf"
insertbefore: BOF
validate: /usr/sbin/sshd -t -f %s
notify: Restart sshd
# roles/sshd/templates/50-hardening.conf.j2
# Managed by Ansible — manual changes will be reverted. Baseline: CIS L1.
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
X11Forwarding no
MaxAuthTries 4
LoginGraceTime 60
ClientAliveInterval 300
ClientAliveCountMax 3
AllowGroups {{ sshd_allow_groups | join(' ') }}
Ciphers {{ sshd_ciphers | join(',') }}
MACs {{ sshd_macs | join(',') }}
KexAlgorithms {{ sshd_kex | join(',') }}
# roles/baseline_linux/tasks/sysctl.yml
- name: Kernel network hardening
ansible.posix.sysctl:
name: "{{ item.key }}"
value: "{{ item.value }}"
sysctl_file: /etc/sysctl.d/60-baseline.conf
reload: true
loop: "{{ baseline_sysctl | dict2items }}"
vars:
baseline_sysctl:
net.ipv4.conf.all.accept_redirects: 0
net.ipv4.conf.default.accept_redirects: 0
net.ipv4.conf.all.send_redirects: 0
net.ipv4.conf.all.rp_filter: 1
net.ipv4.tcp_syncookies: 1
kernel.randomize_va_space: 2
fs.suid_dumpable: 0
Use community CIS roles (ansible-lockdown/*-CIS) as a starting point; vendor them into your repo at a pinned version, and switch off rules with their variables rather than editing tasks — that keeps upgrades manageable and makes deviations explicit (and linkable to exceptions).
Windows with Ansible¶
- name: Windows baseline (excerpt)
hosts: windows
tasks:
- name: Require SMB signing (server)
ansible.windows.win_regedit:
path: HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters
name: RequireSecuritySignature
data: 1
type: dword
- name: Disable SMBv1 feature
ansible.windows.win_optional_feature:
name: SMB1Protocol
state: absent
- name: Apply a DSC resource from Ansible
ansible.windows.win_dsc:
resource_name: AuditPolicySubcategory
Name: "Logon"
AuditFlag: "Failure"
Ensure: Present
Prefer WinRM over HTTPS with certificate or Kerberos auth, or OpenSSH on Windows Server 2019+.
Scheduled enforcement¶
Ansible only enforces when it runs. Options:
- AWX / Ansible Automation Platform schedules (with job templates per environment).
- CI scheduled pipelines (GitLab schedules) running from a runner with network reach.
ansible-pullvia systemd timer on each Linux host (pulls the repo and applies locally — good for disconnected sites).
# /etc/systemd/system/ansible-pull.timer
[Unit]
Description=Apply configuration baseline
[Timer]
OnCalendar=*-*-* 02,08,14,20:15:00
RandomizedDelaySec=900
Persistent=true
[Install]
WantedBy=timers.target
PowerShell DSC¶
PSDSC (Windows PowerShell 5.1, DSC 1.1)¶
Still widely used for Windows servers. The LCM can be configured to monitor or auto-correct:
[DSCLocalConfigurationManager()]
Configuration LcmSettings {
Node localhost {
Settings {
ConfigurationMode = 'ApplyAndAutoCorrect' # or ApplyAndMonitor
ConfigurationModeFrequencyMins = 30
RefreshMode = 'Push'
RebootNodeIfNeeded = $false
}
}
}
LcmSettings -OutputPath .\lcm
Set-DscLocalConfigurationManager -Path .\lcm -Verbose
Configuration ServerBaseline {
Import-DscResource -ModuleName PSDesiredStateConfiguration
Import-DscResource -ModuleName AuditPolicyDsc
Import-DscResource -ModuleName SecurityPolicyDsc
Node localhost {
Registry SmbServerSigning {
Key = 'HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters'
ValueName = 'RequireSecuritySignature'
ValueType = 'Dword'
ValueData = '1'
Ensure = 'Present'
}
Service Spooler {
Name = 'Spooler'
StartupType = 'Disabled'
State = 'Stopped'
}
AuditPolicySubcategory LogonFailure {
Name = 'Logon'
AuditFlag = 'Failure'
Ensure = 'Present'
}
UserRightsAssignment DenyNetworkLogonGuests {
Policy = 'Deny_access_to_this_computer_from_the_network'
Identity = 'Guests'
}
}
}
ServerBaseline -OutputPath .\mof
Start-DscConfiguration -Path .\mof -Wait -Verbose -Force
# Drift check
Test-DscConfiguration -Detailed | Select-Object -ExpandProperty ResourcesNotInDesiredState
Microsoft DSC v3¶
DSC v3 is a standalone, cross-platform CLI (dsc) with JSON/YAML configuration documents, no LCM, no MOF. It can call existing PSDSC resources through adapters (PowerShell 7.2+ for the PowerShell adapter).
winget install Microsoft.DSC # Windows
# Linux/macOS: download release archive from github.com/PowerShell/DSC and add to PATH
# dsc/windows-baseline.dsc.yaml
$schema: https://aka.ms/dsc/schemas/v3/bundled/config/document.json
resources:
- name: SMB server signing required
type: Microsoft.Windows/Registry
properties:
keyPath: HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters
valueName: RequireSecuritySignature
valueData:
DWord: 1
- name: SMBv1 server disabled
type: Microsoft.Windows/Registry
properties:
keyPath: HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters
valueName: SMB1
valueData:
DWord: 0
dsc config test --file .\dsc\windows-baseline.dsc.yaml # drift report (JSON)
dsc config set --file .\dsc\windows-baseline.dsc.yaml # enforce
dsc resource list # available resources
dsc config test returns structured JSON with inDesiredState per resource — easy to feed into a pipeline or monitoring. Because there's no LCM, scheduling is yours: a scheduled task, Ansible, or Azure Machine Configuration.
Azure Machine Configuration¶
Machine configuration (part of Azure Policy) evaluates configuration inside Azure VMs and Arc servers roughly every 15 minutes and reports per-resource compliance. Assignments can be:
| Assignment type | Behaviour |
|---|---|
Audit |
Report only |
ApplyAndMonitor |
Apply once; report drift but don't fix |
ApplyAndAutoCorrect |
Apply and re-apply whenever drift is detected |
Authoring a custom package (Windows example)¶
Install-Module GuestConfiguration -Scope CurrentUser
Install-Module PSDscResources -Scope CurrentUser
# 1. Compile a PSDSC configuration to MOF (ServerBaseline from above, using PSDscResources)
ServerBaseline -OutputPath .\SmbHardening
# 2. Package it
New-GuestConfigurationPackage `
-Name 'SmbHardening' `
-Configuration '.\SmbHardening\localhost.mof' `
-Type AuditAndSet `
-Force
# 3. Test locally before publishing
Get-GuestConfigurationPackageComplianceStatus -Path .\SmbHardening.zip
Start-GuestConfigurationPackageRemediation -Path .\SmbHardening.zip
# 4. Upload to a storage account (private container + SAS, or managed identity access)
$uri = '<blob URL with SAS or accessible via managed identity>'
# 5. Generate a policy definition
New-GuestConfigurationPolicy `
-PolicyId (New-Guid) `
-ContentUri $uri `
-DisplayName 'Server baseline: SMB hardening' `
-Description 'Requires SMB signing and disables SMBv1' `
-Path .\policies `
-Platform Windows `
-PolicyVersion 1.0.0 `
-Mode ApplyAndAutoCorrect
New-AzPolicyDefinition -Name 'smb-hardening' -Policy .\policies\SmbHardening_DeployIfNotExists.json
Assign the definition at management-group scope with a managed identity for remediation, and create a remediation task for existing machines.
Migrating from Azure Automation State Configuration¶
- Export configurations and node assignments from the Automation account.
- Recompile against
PSDscResources(not the inboxPSDesiredStateConfigurationresources, which machine configuration doesn't support in packages). - Package per configuration; test with the
GuestConfigurationmodule locally. - Assign in
ApplyAndMonitorfirst, compare reports with the old service, then switch toApplyAndAutoCorrect. - Unregister nodes from Automation DSC before September 30, 2027.
Known gaps: reboot handling and credential-based resources behave differently; validate any configuration that depends on them.
Group Policy¶
For domain-joined Windows servers, GPO is the default enforcement layer for security settings.
- Keep baseline GPOs as code: back them up (
Backup-GPO) into Git after each change, and diff the XML reports (Get-GPOReport -ReportType Xml) in merge requests. - Use Policy Analyzer (Security Compliance Toolkit) to compare GPO sets against the CIS or Microsoft baseline and detect conflicts.
- Use security filtering / WMI filters sparingly; they make "what actually applies?" hard to answer.
- Verify effective settings with
gpresult /h report.htmlandGet-GPResultantSetOfPolicy. - GPO re-applies security settings periodically, which gives a form of auto-correct for those settings, but it won't tell you drift happened. Pair it with Machine Configuration audit or scanner compliance checks.
Intune and Defender for Endpoint security settings management¶
Windows Server isn't normally enrolled in Intune MDM. What does work for servers is Defender for Endpoint security settings management: servers onboarded to Defender for Endpoint (including via Defender for Servers on Azure and Arc) can receive Intune endpoint security policies — antivirus, firewall, firewall rules, attack surface reduction, EDR — without MDM enrolment.
Use it for: consistent Defender AV/ASR/firewall policy across Azure, Arc and on-prem servers from one console.
Don't use it for: general OS configuration, services, registry baselines — that's GPO, DSC, Ansible, or Machine Configuration.
Watch for conflicts: if GPO also configures Defender or Windows Firewall, decide which one wins and remove the other.
Detecting drift¶
Ansible check mode¶
#!/usr/bin/env bash
# drift-report.sh — report hosts that would change
set -euo pipefail
export ANSIBLE_STDOUT_CALLBACK=ansible.posix.json
ansible-playbook -i inventories/ playbooks/baseline.yml --check --diff > /tmp/drift.json || true
jq -r '
.stats | to_entries[]
| select(.value.changed > 0 or .value.failures > 0 or .value.unreachable > 0)
| "\(.key)\tchanged=\(.value.changed)\tfailed=\(.value.failures)\tunreachable=\(.value.unreachable)"
' /tmp/drift.json
# Detail: which tasks would change on which host
jq -r '
.plays[].tasks[] as $t
| $t.hosts | to_entries[]
| select(.value.changed == true)
| "\(.key)\t\($t.task.name)"
' /tmp/drift.json | sort
Tasks must be check-mode safe for this to be accurate: avoid command/shell tasks that always report changed, or give them changed_when and check_mode: false where they're pure reads.
DSC¶
- PSDSC:
Test-DscConfiguration -Detailed(or LCM inApplyAndMonitorwrites drift to the event log: Microsoft-Windows-DSC/Operational). - DSC v3:
dsc config testJSON output.
Azure Policy / Machine Configuration¶
guestconfigurationresources
| extend compliance = tostring(properties.complianceStatus),
assignment = name,
machine = tostring(split(properties.targetResourceId, "/")[8]),
lastChecked = todatetime(properties.lastComplianceStatusChecked)
| where compliance != "Compliant"
| project machine, assignment, compliance, lastChecked
Per-setting reasons are in properties.latestAssignmentReport.resources[].reasons.
Change Tracking and Inventory¶
Azure Change Tracking and Inventory (using the Azure Monitor Agent) records changes to files, registry keys, software, services/daemons on Azure VMs and Arc machines into Log Analytics (ConfigurationChange table). It doesn't know desired state, but it tells you when something changed and what — invaluable when drift is detected and you need to know whether it was a person, a package, or a payload.
ConfigurationChange
| where TimeGenerated > ago(24h)
| where ConfigChangeType in ("Files", "Registry", "WindowsServices", "Daemons")
| summarize changes = count() by Computer, ConfigChangeType
| order by changes desc
High-signal drift to alert on immediately¶
- Local Administrators /
sudo/wheelmembership changes - New
authorized_keysentries for privileged accounts - New services, scheduled tasks, systemd units, cron jobs
- Security tooling stopped or uninstalled (EDR, auditd, AMA)
- Firewall disabled or default policy changed
- Audit policy reduced
These go to the SOC/SIEM as security events, not to a weekly drift report.
Auto-correct or alert?¶
| Setting type | Recommendation |
|---|---|
| Security baseline settings with no app impact (SMB signing, TLS protocols, password policy, audit policy) | Auto-correct — drift is never legitimate |
| Service state for security agents | Auto-correct + alert — the alert matters more than the fix |
| Settings that apps legitimately vary (ports, firewall rules for app traffic, kernel params tuned per workload) | Alert, then codify or revert |
| Anything that can break production if reverted mid-incident | Alert; correct during the next window |
| Privileged group membership / keys | Alert as a security event; correct after investigation (auto-correct destroys evidence) |
Start in monitor/check mode everywhere. Promote setting families to auto-correct once the drift report has been clean for several weeks.
Handling a drift event¶
1. Detect → drift report / policy non-compliance / change tracking alert
2. Classify → authorised-but-not-in-code | unauthorised | tool conflict | malicious
3. Decide
authorised-but-not-in-code → update the code (MR), reference the change ticket
unauthorised → revert (auto or next run); notify the person/team
tool conflict → assign one owner for the setting; remove from the other tool
malicious → incident response; preserve evidence; do NOT auto-revert first
4. Root cause → why was a manual change needed? missing automation? missing access path?
5. Close → drift report clean on the next run
Track recurring drift per setting. If the same setting drifts every month, the process (or the baseline) is wrong.
Testing configuration code¶
| Tool | What it tests |
|---|---|
ansible-lint |
Style, deprecated modules, risky patterns |
yamllint |
YAML syntax |
| Molecule (with Docker/Podman or cloud drivers) | Role converges, is idempotent (second run = zero changes), verifies end state (Testinfra/Ansible verifier) |
| PSScriptAnalyzer | PowerShell/DSC configuration code |
| Pester | Assertions on Windows state after applying DSC |
dsc config test in CI against an ephemeral VM |
DSC v3 documents |
| Scanner compliance on a test VM | End-to-end: does the baseline actually pass CIS-CAT/MDVM/USG? |
Molecule idempotence is the single most valuable test: a role that reports changes on the second run will make every drift report noisy and train people to ignore it.
# .gitlab-ci.yml (excerpt)
stages: [lint, test]
ansible-lint:
stage: lint
image: python:3.13-slim
script:
- pip install --quiet ansible-core ansible-lint yamllint
- yamllint .
- ansible-lint
molecule:
stage: test
image: python:3.13-slim
services: [docker:dind]
variables:
DOCKER_HOST: tcp://docker:2375
script:
- pip install --quiet ansible-core molecule molecule-plugins[docker]
- cd roles/baseline_linux && molecule test
Secrets in configuration¶
- Never commit secrets — use Ansible Vault (with the vault password from CI secrets) or lookups against Azure Key Vault (
azure.azcollection.azure_keyvault_secretlookup) at run time. - DSC: avoid credentials in configurations where possible; Machine Configuration doesn't support the same credential patterns as Automation DSC — prefer managed identities and gMSAs.
- Mark sensitive Ansible tasks
no_log: true. - Run secret scanning (gitleaks) in CI on the config repo as well as app repos.
Golden images and configuration management together¶
Configuration management corrects drift; images prevent it from starting. Use both:
Packer / Azure Image Builder
└─ base OS + latest patches + baseline role applied + agents installed
│
▼
Azure Compute Gallery (versioned image) ──► new VMs start compliant
│
▼
Config management keeps them compliant over time
Scanner + Machine Configuration verify
Rebuild images monthly (after Patch Tuesday) so new servers don't boot already a month behind — and so autoscaling doesn't reintroduce fixed vulnerabilities.
References¶
- Azure Machine Configuration overview and authoring — Microsoft Learn
- Azure Automation State Configuration retirement (September 30, 2027) — Microsoft Learn
- Microsoft DSC v3 documentation — learn.microsoft.com/powershell/dsc
- Ansible Azure inventory plugin —
azure.azcollection.azure_rm - Molecule — ansible.readthedocs.io/projects/molecule
- Defender for Endpoint security settings management — Microsoft Learn
- Change Tracking and Inventory with Azure Monitor Agent — Microsoft Learn