7.4 Server Scripting and Configuration Automation

Key Takeaways

  • Infrastructure as Code (IaC) and configuration automation eliminate configuration drift, enforcing deterministic consistency and rapid scalability across enterprise server fleets through idempotent operations.
  • Windows PowerShell operates on a structured .NET object pipeline using standardized Verb-Noun cmdlets, where execution policies (such as RemoteSigned) enforce script security without disabling automation.
  • Linux Bash scripting utilizes the shebang (#!/bin/bash), POSIX exit status codes ($?), and defensive flags (set -euo pipefail) to ensure reliable, fail-safe procedural execution.
  • Scheduled automation relies on the Linux cron daemon (5-field syntax) or systemd timers (.timer units with dependency and resource controls) on Linux, and Windows Task Scheduler (schtasks.exe) on Windows.
  • Configuration management tools enforce declarative states: Ansible leverages an agentless YAML-over-SSH/WinRM architecture, Puppet utilizes a master-agent model with Ruby-based declarative DSL, and Chef organizes configurations into recipes and cookbooks.
Last updated: September 2026

Server Scripting and Configuration Automation

Core Automation Principle: In modern enterprise server environments, manual administration is obsolete. Managing hundreds or thousands of physical servers, virtual machines, and cloud instances through graphical user interfaces (GUIs) or manual CLI keystrokes is slow, unrepeatable, and inevitably introduces Configuration Drift—the gradual, undocumented deviation of server configurations from established baselines. Automation transforms server operations into repeatable, auditable, and scalable code, ensuring deterministic environments and immediate recovery.

Systems administrators preparing for CompTIA Server+ (SK0-005) must understand the core scripting frameworks powering Windows and Linux environments, task scheduling mechanics, Infrastructure as Code (IaC) principles, and enterprise configuration management platforms.


The Imperative for Server Automation and Infrastructure as Code

Enterprise server automation replaces ad-hoc manual intervention with structured, programmatic execution, delivering four transformative benefits:

+-----------------------------------------------------------------------------+
|                        Benefits of Server Automation                        |
|                                                                             |
|   1. REPEATABILITY & DETERMINISM:                                           |
|   * Identical execution every time; eliminates human keyboard error.        |
|                                                                             |
|   2. ERADICATION OF CONFIGURATION DRIFT:                                    |
|   * Continuous state enforcement ensures servers match authorized baselines.|
|                                                                             |
|   3. RAPID SCALE & RAPID TIME-TO-MARKET:                                    |
|   * Provisioning 500 servers takes the same administrative effort as 1.     |
|                                                                             |
|   4. AUDITABILITY & RECOVERY:                                               |
|   * Scripts and playbooks are version-controlled in Git, providing complete |
|     change attribution, peer review, and disaster recovery rebuilding.      |
+-----------------------------------------------------------------------------+
  • Eradicating Configuration Drift: Over months of operation, administrators make undocumented "quick fixes" on individual servers—adjusting a registry key, modifying a file permission, or manually restarting a daemon. Over time, servers that were originally identical diverge into unique, fragile "snowflakes". When patches or security updates are applied, these drifted servers fail unpredictably. Automated configuration management continually audits and enforces the desired state, automatically correcting drifted parameters back to baseline.
  • Infrastructure as Code (IaC): Treating infrastructure configuration identical to software application code. Infrastructure topologies, server build specifications, firewall rules, and storage attachments are defined in machine-readable configuration files (YAML, JSON, or declarative DSLs) stored within version control repositories (Git). Changes undergo automated testing, branch merging, and peer review before programmatic deployment.

Windows PowerShell Scripting Architecture

PowerShell is a task-based command-line shell and scripting framework engineered by Microsoft, built directly upon the .NET Common Language Runtime (CLR).

+-----------------------------------------------------------------------------+
|                   PowerShell Object Pipeline vs. Text Pipe                  |
|                                                                             |
|   TRADITIONAL TEXT-BASED SHELL PIPELINE:                                    |
|   [Command A] === Raw Characters / Text Stream ===> [Command B (grep/awk)]  |
|   * Brittle: Column positions, spaces, or formatting changes break parser!  |
|                                                                             |
|   POWERSHELL OBJECT PIPELINE (.NET CLR):                                    |
|   [Get-Service] === Structured Objects (Properties & Methods) ===> [Where]  |
|   * Robust: Filter directly on object properties ($_.Status, $_.Name);      |
|     no string slicing or text parsing required!                             |
+-----------------------------------------------------------------------------+

The Object-Oriented Pipeline

Unlike traditional Unix shells that pass unstructured streams of raw ASCII text from one command to the next, PowerShell commands pass strongly typed .NET objects down the pipeline (|).

  • When an administrator executes Get-Service, the command does not emit text rows. It outputs a collection of System.ServiceProcess.ServiceController objects.
  • Downstream cmdlets can directly inspect, filter, or invoke methods on the object's properties (e.g., .Status, .DisplayName, .DependentServices) without fragile string manipulation or regex parsing.

Verb-Noun Cmdlet Syntax

PowerShell enforces a strict, predictable Verb-Noun naming convention for all built-in commands (cmdlets):

  • Approved Verbs: Represent specific actions (e.g., Get, Set, New, Remove, Start, Stop, Restart).
  • Singular Nouns: Represent the targeted operational entity (e.g., Service, Process, NetIPAddress, VM, Item).
PowerShell CmdletOperational FunctionEquivalent Linux Command
Get-ServiceRetrieves status of system servicessystemctl status
Restart-Service -Name W3SVCGracefully cycles a Windows servicesystemctl restart nginx
Set-NetIPAddressConfigures IP, subnet, and interfaceip addr add
Get-ProcessQueries active processes and resource usageps aux / top
Test-NetConnection -Port 443Diagnostics and TCP socket connectivity testnc -zv / curl -I

PowerShell Execution Policies

To prevent the unauthorized or accidental execution of malicious scripts, PowerShell incorporates an Execution Policy security control (managed via Get-ExecutionPolicy and Set-ExecutionPolicy):

# Query active execution policy across scopes
Get-ExecutionPolicy -List

# Configure enterprise standard RemoteSigned policy
Set-ExecutionPolicy RemoteSigned -Scope LocalMachine -Force
  • Restricted: The default policy on Windows client workstations. Permits individual interactive commands in the console, but blocks all script files (.ps1) from executing.
  • AllSigned: Permits script execution only if the script file has been digitally signed with a cryptographic signature from a trusted code-signing Certificate Authority (CA).
  • RemoteSigned: The enterprise standard for Windows Servers. Scripts authored locally on the server can execute without a digital signature. However, any script downloaded from an external network or the Internet (tagged with an NTFS Alternate Data Stream zone identifier) must be signed by a trusted publisher or explicitly unblocked using the Unblock-File cmdlet.
  • Unrestricted: Runs all scripts. Warns the user before executing downloaded scripts.
  • Bypass: Disables all execution policy checks and prompts. Widely utilized by automated deployment agents and scheduled tasks.

Pipeline Filtering and Iteration

PowerShell provides powerful cmdlets to filter and iterate across object collections:

# Filter: Identify stopped services set to Automatic startup, then start them
Get-Service | Where-Object { $_.Status -eq 'Stopped' -and $_.StartType -eq 'Automatic' } | Start-Service

# Projection: Select specific properties and format as a clean table
Get-Process | Where-Object { $_.CPU -gt 50 } | Select-Object -Property Name, Id, CPU, WorkingSet64 | Format-Table

# Iteration: Iterate through a list of servers and query BIOS serial numbers
$ServerList = @("web01", "web02", "db01")
$ServerList | ForEach-Object {
    Get-CimInstance -ClassName Win32_BIOS -ComputerName $_ | Select-Object PSComputerName, SerialNumber
}

Linux Bash Shell Scripting and Administration

The Bourne Again Shell (Bash) is the ubiquitous default command-line interpreter across enterprise Linux distributions (Red Hat Enterprise Linux, SUSE, Ubuntu Server).

#!/bin/bash
# Enterprise Server Health Audit Script (audit_server.sh)
set -euo pipefail

LOG_FILE="/var/log/server_audit.log"
THRESHOLD=85

echo "Starting system health check at $(date)" | tee -a "$LOG_FILE"

# Query root filesystem utilization percentage
DISK_USAGE=$(df -h / | awk 'NR==2 {print $5}' | tr -d '%')

if [ "$DISK_USAGE" -ge "$THRESHOLD" ]; then
    echo "[CRITICAL] Root disk usage is at ${DISK_USAGE}%!" | tee -a "$LOG_FILE"
    systemctl clean --vacuum-size=500M
else
    echo "[OK] Disk usage is nominal at ${DISK_USAGE}%." | tee -a "$LOG_FILE"
fi

exit 0

Core Syntax and Constructs

  • The Shebang (#!/bin/bash): Placed on the absolute first line of the script. Specifies the programmatic path to the binary interpreter that the operating system kernel must spawn to execute the file. If omitted, the script executes within the user's current shell, risking syntax incompatibilities.
  • Defensive Shell Flags (set -euo pipefail): Crucial for production automation scripts:
    • set -e: Exits the script immediately if any command exits with a non-zero (failure) status.
    • set -u: Treats unset or uninitialized variables as an error, exiting immediately rather than expanding to empty strings.
    • set -o pipefail: Prevents pipeline errors from being masked; the pipeline return code reflects the last non-zero exit code.
  • Command Substitution ($(command)): Executes a command in a subshell and captures its standard output directly into a variable (e.g., CURRENT_USER=$(whoami)), superseding legacy backtick syntax (`command`).
  • Conditional Execution (if [ condition ]; then ... fi): Evaluates boolean and mathematical expressions:
    • Integer Comparisons: -eq (equal), -ne (not equal), -lt (less than), -gt (greater than), -le (less than or equal), -ge (greater than or equal).
    • String Comparisons: = or == (equal), != (not equal), -z (string is null/empty), -n (string is not empty).
    • Filesystem Tests: -f (is a regular file), -d (is a directory), -e (file exists), -s (file exists and size is greater than zero).
  • Exit Status Codes ($?): Every POSIX command emits an integer exit code between 0 and 255 upon termination:
    • 0: Success / Normal completion.
    • 1 - 255: Error or specific exit conditions (e.g., 1 for general error, 127 for command not found).
    • The special parameter $? inspects the exit status of the immediately preceding command.

Scheduled Task Automation: Cron, Systemd Timers, and Task Scheduler

Enterprise servers execute background maintenance routines—log rotation, database backups, telemetry shipping, certificate renewals—using specialized scheduling daemons.

+-----------------------------------------------------------------------------+
|                        Linux Crontab 5-Field Syntax                         |
|                                                                             |
|    *       *       *       *       *       command_to_execute               |
|    -       -       -       -       -                                        |
|    |       |       |       |       |                                        |
|    |       |       |       |       +----- Day of Week (0 - 6, 0 = Sunday)   |
|    |       |       |       +------------- Month (1 - 12)                    |
|    |       |       +--------------------- Day of Month (1 - 31)             |
|    |       +----------------------------- Hour (0 - 23, 24-Hour Format)     |
|    +------------------------------------- Minute (0 - 59)                   |
+-----------------------------------------------------------------------------+

Linux Cron Daemon (crond)

The cron daemon executes scheduled jobs defined in crontab tables (edited via crontab -e and listed via crontab -l).

  • Field Operators:
    • * (Asterisk): Match all values in the field (every minute, every hour).
    • , (Comma): Specify a discrete list of values (e.g., 1,15,30 in the minute field).
    • - (Hyphen): Specify an inclusive range (e.g., 1-5 in the day-of-week field for Monday through Friday).
    • / (Slash): Specify step intervals (e.g., */15 in the minute field runs every 15 minutes).
Crontab Syntax ExampleExecution Schedule Description
0 2 * * * /opt/backup.shEvery day at exactly 02:00 (2:00 AM)
*/15 * * * * /usr/bin/check_healthEvery 15 minutes, every hour, every day
30 23 * * 1-5 /opt/db_dump.shAt 23:30 (11:30 PM) Monday through Friday
0 0 1,15 * * /opt/bi_weekly.shAt midnight on the 1st and 15th of every month
0 4 * * 0 /opt/weekly_scrub.shEvery Sunday at 04:00 (4:00 AM)

Modern Linux: Systemd Timers (.timer Units)

Modern enterprise distributions increasingly replace or augment cron with systemd timers. A systemd timer is defined using two paired unit files: a service unit (backup.service) that defines what command executes, and a timer unit (backup.timer) that defines when it executes.

  • Monotonic Timers: Run relative to specific system events (e.g., OnBootSec=15min executes 15 minutes after kernel boot; OnUnitActiveSec=1h executes 1 hour after the service was last activated).
  • Realtime (Calendar) Timers: Run on absolute calendar dates and times (e.g., OnCalendar=*-*-* 03:00:00 runs daily at 03:00).
  • Advantages over Cron: Seamless integration with the systemd journal (journalctl -u backup.service), precise microsecond execution triggers, execution history tracking (systemctl list-timers), and fine-grained resource control via Linux control groups (cgroups) to throttle CPU and memory consumption during backup jobs.
# /etc/systemd/system/db-backup.timer
[Unit]
Description=Trigger Daily Database Backup Service

[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true

[Install]
WantedBy=timers.target

Windows Task Scheduler (schtasks.exe)

Windows Server schedules automated jobs through the Task Scheduler service (managed via the graphical taskschd.msc, the CLI utility schtasks.exe, or the PowerShell ScheduledTasks module).

  • Security Contexts: Scheduled tasks can execute under the local security context of NT AUTHORITY\SYSTEM, an enterprise Group Managed Service Account (gMSA), or a dedicated service account assigned the "Log on as a batch job" user rights assignment.
  • Advanced Triggers: Supports execution on calendar schedules, at system startup, upon user logon, or dynamically triggered by specific Windows Event Log IDs (e.g., launching an alert script whenever Event ID 1074 [System Shutdown] appears in the System log).
# PowerShell: Registering a scheduled task running daily at 3:00 AM
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\Scripts\Archive-Logs.ps1"
$Trigger = New-ScheduledTaskTrigger -Daily -At 3am
$Principal = New-ScheduledTaskPrincipal -UserId "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount
Register-ScheduledTask -TaskName "ArchiveServerLogs" -Action $Action -Trigger $Trigger -Principal $Principal

Configuration Management and Infrastructure as Code Fundamentals

Modern server administration enforces state using Configuration Management platforms governed by two foundational paradigms:

+-----------------------------------------------------------------------------+
|                  Imperative Scripting vs. Declarative IaC                   |
|                                                                             |
|   IMPERATIVE MODEL ("The How" - Traditional Scripting):                     |
|   1. Check if nginx package exists.                                         |
|   2. If not, run 'apt-get install nginx'.                                   |
|   3. Edit configuration file line 42.                                       |
|   4. Start nginx service.                                                   |
|   * Flaw: If run twice, may throw errors or duplicate configuration lines!  |
|                                                                             |
|   DECLARATIVE MODEL ("The What" - Configuration Management):                |
|   package { 'nginx': state => 'installed' }                                 |
|   service { 'nginx': state => 'running', enable => true }                   |
|   * IDEMPOTENT: Engine inspects current state; applies changes ONLY if     |
|     target has drifted from desired state. Running 100 times produces       |
|     the identical, perfect result without side effects!                     |
+-----------------------------------------------------------------------------+

Declarative vs. Imperative Models

  • Imperative Model: Focuses on how to achieve a result. The administrator writes step-by-step sequential instructions (e.g., standard Bash or PowerShell scripts). If intermediate steps fail or prerequisites change, imperative scripts often crash or execute unintended actions.
  • Declarative Model: Focuses on what the final operational state should be. The administrator writes a manifest specifying: "The Apache web service must be installed, its configuration file must match this template, and the service must be running." The underlying configuration management engine inspects the target server's current reality, calculates the delta, and executes only the specific actions required to achieve the desired state.

The Idempotency Principle

Idempotency is the defining requirement of enterprise configuration management. An operation is idempotent if executing it multiple times produces the exact same outcome as executing it once, with zero unintended side effects.

  • Non-Idempotent Example: An imperative script executing echo "10.0.0.5 db-server" >> /etc/hosts. Every time the script executes, it appends another duplicate line to /etc/hosts. After ten executions, the file contains ten duplicate entries.
  • Idempotent Example: An Ansible task or Puppet resource managing /etc/hosts. The engine inspects /etc/hosts. If 10.0.0.5 db-server is already present, the engine reports OK (Unchanged) and does nothing. If the entry is missing or points to the wrong IP, the engine updates it. Running the playbook 1,000 times results in exactly one correct line.

Enterprise Configuration Management Tools Overview

Three primary configuration management platforms dominate enterprise server infrastructure: Ansible, Puppet, and Chef.

+-----------------------------------------------------------------------------+
|                 Configuration Management Platform Comparison                |
|                                                                             |
|   ANSIBLE (Agentless Push Model):                                           |
|   [Control Node] === SSH / WinRM ===> [Managed Servers (Zero Agent!)]       |
|   * Playbooks written in human-readable YAML.                               |
|   * Uses native OpenSSH for Linux and WinRM for Windows.                    |
|                                                                             |
|   PUPPET (Master-Agent Pull Model):                                         |
|   [Puppet Server] <=== Pulls Catalog (Port 8140) === [Puppet Agent Daemon]  |
|   * Declarative Ruby-based Domain-Specific Language (DSL).                  |
|   * Facter gathers host facts; agent automatically corrects drift every 30m.|
|                                                                             |
|   CHEF (Client-Server Pull Model):                                          |
|   [Chef Server] <=== Pulls Cookbooks === [Chef Client Daemon]               |
|   * Pure Ruby-based procedural/declarative Recipes and Cookbooks.           |
+-----------------------------------------------------------------------------+

1. Ansible

  • Architecture: Agentless. Ansible requires no proprietary background daemon or client software installed on the target nodes. The central Ansible Control Node connects to managed target servers using standard, ubiquitous enterprise remote management protocols: OpenSSH for Linux/Unix and Windows Remote Management (WinRM) for Windows.
  • Language and Structure: Playbooks are authored in human-readable YAML (YAML Ain't Markup Language). Modules (such as ansible.builtin.yum, ansible.builtin.service, or ansible.windows.win_updates) execute idempotent actions.
  • Operational Flow: Operates primarily on a push model. An administrator or CI/CD pipeline triggers an Ansible execution, which compiles tasks, connects to targets, executes Python scripts (on Linux) or PowerShell scripts (on Windows) in temporary directories, captures results, and cleans up.
# Sample Ansible Playbook (web_cluster.yml)
---
- name: Deploy and Harden Production NGINX Web Cluster
  hosts: webservers
  become: yes
  tasks:
    - name: Ensure NGINX package is installed
      ansible.builtin.yum:
        name: nginx
        state: present

    - name: Ensure NGINX service is started and enabled at boot
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: yes

    - name: Deploy hardened NGINX configuration
      ansible.builtin.copy:
        src: files/nginx.conf
        dest: /etc/nginx/nginx.conf
        owner: root
        group: root
        mode: '0644'
      notify: Reload NGINX

  handlers:
    - name: Reload NGINX
      ansible.builtin.service:
        name: nginx
        state: reloaded

2. Puppet

  • Architecture: Master-Agent architecture (historically termed Puppet Master, now Puppet Server). A persistent background daemon (Puppet Agent) is installed on every managed endpoint, communicating with the server over encrypted TLS on TCP Port 8140.
  • Language and Structure: Uses a proprietary declarative Ruby-based Domain-Specific Language (DSL). Configuration manifests (.pp files) declare desired resources (users, packages, files, services).
  • Operational Flow: Operates on a pull model. Every 30 minutes (by default), the local Puppet agent invokes Facter (an embedded tool that gathers local operating system attributes, IP addresses, and hardware facts). The agent sends these facts to the Puppet Server. The server compiles a customized, declarative machine-level Catalog and transmits it back. The agent evaluates the catalog, applies any necessary remediation to resolve configuration drift, and transmits a compliance report back to the master.

3. Chef

  • Architecture: Client-Server architecture comprising a Chef Server, managed endpoints running the Chef Infra Client, and administrator workstations using the Chef Workstation CLI tools.
  • Language and Structure: Written in pure, flexible Ruby. Infrastructure policies are declared in Recipes, which are aggregated into modular packages called Cookbooks.
  • Operational Flow: Operates on a pull model. The Chef client boots, uses Ohai to gather comprehensive system profile attributes, queries the Chef Server for assigned Run-lists, downloads necessary cookbooks, compiles the execution collection, and executes recipes to configure the local operating system.
FeatureAnsiblePuppetChef
Agent RequirementAgentless (Zero target software)Agent-based (Puppet Agent daemon)Agent-based (Chef Infra Client)
Transport ProtocolNative OpenSSH (Linux) / WinRM (Windows)HTTPS / TLS (TCP Port 8140)HTTPS / REST API (TCP Port 443)
Configuration LanguageDeclarative YAMLDeclarative Puppet DSL (Ruby-based)Procedural/Declarative Ruby
Execution ParadigmPush (Control node pushes changes)Pull (Agent polls server every 30m)Pull (Client polls server per run-list)
State Inspection ToolAnsible Setup Module (ansible_facts)FacterOhai
Ease of DeploymentFastest (runs immediately over SSH)Moderate (requires agent PKI certs)Moderate (requires workstation/agent setup)

Legacy Windows Script Types: Batch and VBScript

PowerShell and Bash carry modern server automation, but SK0-005 lists four script types, and the two legacy Windows formats still appear on the exam and in real environments.

TypeExtensionInterpreterComment SyntaxStatus
Batch.bat, .cmdcmd.exeREM or ::Supported; ubiquitous in logon scripts and installers
VBScript (VBS).vbscscript.exe (console) / wscript.exe (GUI)' (apostrophe) or REMDeprecated by Microsoft; being retired
PowerShell.ps1powershell.exe / pwsh# and <# … #>Current standard
Bash.sh/bin/bash#Current standard on Linux

Batch files run in the cmd.exe shell and remain the lowest-common-denominator automation on Windows: they need no execution policy, no runtime, and no signing, which is exactly why they persist in Group Policy logon scripts, scheduled maintenance jobs, and vendor installers. They are also strictly text-oriented — every value is a string, control flow is limited to IF, FOR, GOTO, and CALL, and error handling depends on inspecting %ERRORLEVEL% after each command.

VBScript was the scripting language that preceded PowerShell, driven through the Windows Script Host with cscript.exe for console output or wscript.exe for dialog boxes, and it reached deep into system management through WMI and COM objects. Microsoft has since deprecated VBScript and published a three-phase retirement. In the current phase it ships as a Feature on Demand that is still installed and enabled by default in Windows 11 and Windows Server 2025, so existing scripts continue to run. Microsoft has stated that the FOD will become disabled by default around 2027, requiring manual re-enablement, and that VBScript will be removed from Windows entirely in a later release. The operational consequence is a dated migration deadline rather than an immediate break: legacy .vbs maintenance jobs work today, will fail silently after the phase that disables the feature, and should be ported to PowerShell now rather than re-enabled later.

Note that the comment character is one of the most reliably tested details across all four types: REM or :: in batch, an apostrophe in VBScript, and # in both PowerShell and Bash.

Test Your Knowledge

A systems administrator develops an automation script named 'Configure-ServerRoles.ps1' on a Windows Server 2022 management workstation. When attempting to run the script in the local PowerShell console, the system returns an error stating: 'File Configure-ServerRoles.ps1 cannot be loaded because running scripts is disabled on this system.' Corporate security guidelines permit executing internally authored automation scripts on local servers but mandate that any script downloaded from the internet must be digitally signed by a trusted internal enterprise Certificate Authority (CA). Which PowerShell command should the administrator execute to establish this compliant configuration?

A
B
C
D
Test Your Knowledge

A Linux database administrator needs to schedule an automated database maintenance script (/usr/local/bin/db-backup.sh) to execute every weekday evening (Monday through Friday) at exactly 11:30 PM (23:30). Which crontab line correctly configures this automated schedule?

A
B
C
D
Test Your Knowledge

An enterprise systems engineering team is tasked with implementing a configuration management solution to enforce standardized configuration baselines across 800 Linux and Windows servers. The security compliance team mandates that no additional third-party background software agents or persistent service daemons may be installed on the managed target servers. Furthermore, all configuration definitions must be written in declarative, human-readable YAML files and execute over existing native administrative network protocols. Which configuration management platform satisfies all of these operational and security constraints?

A
B
C
D