Project Goal
Operate a small fleet like a real operations team: enforce a security baseline with Puppet, patch servers safely with Bolt, and prove compliance with a report built from PuppetDB.
text
Control repo (hardening profile) ──r10k──► Puppet Server ──► agents (noop first, then enforce)
│
reports ──► PuppetDB ──► compliance script ──► Slack/email + weekly CSV
Bolt project (patch plans) ──ssh──► nodes in batches, drain / patch / reboot / verify
Part A: A Hardening Baseline in Safe Stages
Use the hardening profile from the security lesson. Roll it out in stages: noop, canary, group, all.
puppet
# site-modules/profile/manifests/baseline.pp
class profile::baseline (
Boolean $enforce = false, # false = only report (noop), true = apply changes
) {
# The agent noop setting is stored in puppet.conf (inifile module)
ini_setting { 'agent noop':
ensure => present,
path => '/etc/puppetlabs/puppet/puppet.conf',
section => 'agent',
setting => 'noop',
value => $enforce ? { true => 'false', default => 'true' },
}
include profile::hardening
}
Noop applies from the next run: The noop setting is read when the agent starts a run, so it takes effect on the following run. Test the flow in a lab and confirm the report says noop before you rely on it. Single resources can also use the noop => true metaparameter.
yaml
# data/common.yaml
profile::baseline::enforce: false # report only everywhere to begin with
# data/nodes/web02.lab.local.yaml (canary)
profile::baseline::enforce: true
Workflow: 1) deploy with enforce: false and look at the noop reports for two days. 2) Fix surprises (for example, a service that needs a port that the firewall would close). 3) Enable enforce: true for the canary. 4) Enable by role or group. 5) Enable everywhere.
Part B: What Would Change? Query the Reports
bash
# Noop events: resources Puppet WOULD change, latest reports only
curl -s -G http://puppetdb.lab.local:8080/pdb/query/v4 --data-urlencode \
'query=events[certname, resource_type, resource_title, property, new_value] { latest_report? = true and status = "noop" }' \
| jq -r '.[] | [.certname, .resource_type, .resource_title, .property] | @tsv' | sort | head -40
Part C: A Rolling Patch Plan with Bolt
yaml
# bolt-project.yaml
name: ops
modules:
- name: puppetlabs-package
- name: puppetlabs-reboot
- name: puppetlabs-puppet_agent
# inventory.yaml (shortened)
groups:
- name: web
targets: [web01.lab.local, web02.lab.local, web03.lab.local]
config: { ssh: { user: deploy, run-as: root } }
- name: db
targets: [db01.lab.local]
puppet
# modules/ops/plans/patch.pp
plan ops::patch (
TargetSpec $targets,
Integer $batch_size = 1,
Boolean $reboot = true,
String $ticket = 'none',
) {
$nodes = get_targets($targets)
out::message("Patch ticket ${ticket}: ${nodes.length} servers, batch size ${batch_size}")
$nodes.slice($batch_size).each |$batch| {
out::message("Batch: ${batch.map |$t| { $t.name }.join(', ')}")
run_command('/opt/puppetlabs/bin/puppet agent --disable "patching ${ticket}"', $batch)
run_task('ops::lb_drain', $batch, '_catch_errors' => true) # replace with your load balancer step, or remove
run_task('package', $batch, 'action' => 'upgrade', 'name' => '*')
if $reboot {
run_task('reboot', $batch, 'timeout' => 300)
wait_until_available($batch, 'wait_time' => 300)
}
$check = run_command('systemctl is-system-running --wait || true; systemctl --failed --no-legend | wc -l', $batch)
$failed_units = $check.map |$r| { $r['stdout'].strip.split("\n").last }
if $failed_units.any |$n| { $n != '0' } {
fail_plan("Failed units after patching in batch ${batch.map |$t| { $t.name }}", 'ops/post-patch')
}
run_command('/opt/puppetlabs/bin/puppet agent --enable', $batch)
run_command('/opt/puppetlabs/bin/puppet agent -t', $batch, '_catch_errors' => true)
run_task('ops::lb_enable', $batch, '_catch_errors' => true)
}
return "Patched ${nodes.length} servers (ticket ${ticket})"
}
bash
bolt plan run ops::patch targets=web batch_size=1 ticket=CHG-1042 --log-level info --format human | tee patch-CHG-1042.log
Adapt it: The lb_drain and lb_enable tasks are placeholders for your load balancer. Remove them if you test with a lab that has no load balancer. The check at the end is intentionally simple, so add your own health checks (HTTP status, database ping).
Part D: Compliance Report Script
python
#!/usr/bin/env python3
"""compliance_report.py: summarise fleet state from PuppetDB (read only)."""
import csv, json, sys, urllib.parse, urllib.request, datetime
PDB = "http://puppetdb.lab.local:8080/pdb/query/v4"
def pql(q):
url = PDB + "?" + urllib.parse.urlencode({"query": q})
with urllib.request.urlopen(url, timeout=30) as r:
return json.load(r)
def main():
nodes = pql('nodes[certname, latest_report_status, report_timestamp, catalog_environment]{}')
now = datetime.datetime.now(datetime.timezone.utc)
rows, failed, stale = [], [], []
for n in nodes:
ts = datetime.datetime.fromisoformat(n["report_timestamp"].replace("Z", "+00:00")) if n["report_timestamp"] else None
age_h = round((now - ts).total_seconds() / 3600, 1) if ts else None
status = n["latest_report_status"]
if status == "failed":
failed.append(n["certname"])
if age_h is None or age_h > 3:
stale.append(n["certname"])
rows.append([n["certname"], n["catalog_environment"], status, age_h])
corrective = pql('events[certname, resource_type, resource_title]{ latest_report? = true and corrective_change = true }')
noop = pql('events[certname]{ latest_report? = true and status = "noop" }')
with open("compliance.csv", "w", newline="") as f:
w = csv.writer(f)
w.writerow(["node", "environment", "last_status", "report_age_hours"])
w.writerows(rows)
print(f"Nodes: {len(nodes)}")
print(f"Failed last run: {len(failed)} -> {', '.join(failed) or '-'}")
print(f"No report in 3h: {len(stale)} -> {', '.join(stale) or '-'}")
print(f"Corrective changes (possible manual edits): {len(corrective)}")
print(f"Pending noop changes: {len(noop)}")
return 1 if failed or stale else 0
if __name__ == "__main__":
sys.exit(main())
bash
python3 compliance_report.py
# Run weekly (and daily for the failed/stale part) with cron or CI, and post the output to chat
0 7 * * 1-5 /usr/local/bin/compliance_report.py | mail -s "Puppet compliance report" ops@example.com
Corrective changes: A corrective change means Puppet reverted something that was changed outside Puppet. A server with repeated corrective changes needs a conversation, or a decision to manage that setting in a different way.
Part E: Runbook
Write down how your team works. A short, tested runbook is part of the project.
| Topic | Contents |
| Change process | Branch, review, noop on canary, staging, production, who approves |
| Patch window | Which servers when, batch size, health checks, who is on call |
| Rollback | Revert commit and redeploy, snapshot restore, package downgrade steps |
| Failed run response | Check report, puppet agent -t --noop --debug, fix forward or revert |
| Emergency stop | bolt command run 'puppet agent --disable emergency' --targets all |
| Secrets rotation | Who rotates, how Hiera data is updated, how to confirm all nodes updated |
| Contacts | Team chat channel, on-call, vendor contacts |
Acceptance Checklist
| Check | Done? |
| Hardening runs in noop first and produces a report | |
| Canary enforced and healthy for two days | |
| All servers enforced, zero failed runs | |
| Patch plan tested with batch size 1 on lab servers | |
| Compliance script runs from cron or CI and sends results | |
| Runbook reviewed by another person | |
Conclusion
Operate with stages: report first, enforce on a canary, then roll out. Use Puppet for continuous state, Bolt for orchestrated actions like patching, and PuppetDB queries for reports that prove the fleet is healthy.
Quick Summary: noop first; canary then group; Bolt rolling patch with disable/enable agent; PuppetDB script for failed/stale/corrective; runbook.