This chapter covers Infrastructure as Code (IaC) as applied to network configuration and management, a key topic within CompTIA Network+ N10-009 Domain 1.0 (Networking Concepts), specifically Objective 1.7: 'Explain the importance of planning and implementing network automation and orchestration'. IaC represents a paradigm shift from manual device-by-device configuration to programmatic, version-controlled, and repeatable network deployments. Approximately 5-10% of exam questions will touch on automation concepts, with IaC being a fundamental pillar. You will learn the core principles, tools, workflows, and how IaC integrates with version control, continuous integration/continuous deployment (CI/CD) pipelines, and monitoring to create self-documenting, auditable, and resilient network infrastructures.
Jump to a section
Think of Infrastructure as Code (IaC) like a master recipe book for a large restaurant chain. Instead of each chef (network engineer) manually chopping vegetables, setting oven temperatures, and plating dishes every time a customer orders, the head chef writes a recipe that specifies exact ingredients, quantities, temperatures, and timings. This recipe is stored in a central book (version control). When a new location opens, the manager (automation tool) reads the recipe and executes each step precisely: preheat oven to 350°F (configure VLAN), chop 2 cups of onions (allocate IP subnet), bake for 30 minutes (apply ACL). If a customer complains about saltiness (network issue), the manager checks the recipe version, not the chef's memory. If the recipe says '1 tsp salt' but the dish is salty, they know the recipe needs updating, not the chef's technique. The recipe book ensures every location serves identical food, can be audited, and changes are reviewed before being cooked. Just as a recipe eliminates guesswork and inconsistency, IaC eliminates manual configuration drift and enables repeatable, version-controlled network deployments.
What is Infrastructure as Code (IaC)?
Infrastructure as Code (IaC) is the practice of managing and provisioning network infrastructure through machine-readable definition files, rather than physical hardware configuration or interactive configuration tools. Instead of manually SSH-ing into a switch and typing vlan 10, you define the VLAN in a YAML or JSON file, store it in a Git repository, and apply it via an automation tool like Ansible, Terraform, or Puppet. This approach brings software development practices—version control, code review, automated testing, and continuous delivery—to network operations.
Why IaC Exists
Traditional network configuration is fragile, error-prone, and non-scalable. Manual changes cause configuration drift—where devices deviate from intended state over time. Auditing requires parsing CLI outputs or comparing running-configs. Rollbacks are painful and slow. IaC solves these problems by:
Declarative or imperative definitions: Declarative (e.g., Terraform) specifies the desired end state; imperative (e.g., Ansible playbooks) specifies steps to achieve it.
Idempotency: Applying the same configuration multiple times yields the same result, no matter the starting state.
Version control: Every change is tracked, with history, diffs, and rollback capability.
Automation: Reduces human error and speeds up deployments.
How IaC Works Internally
At its core, IaC relies on a desired state model. The engineer writes a configuration file that describes the network should look like. An automation tool then:
Fetches the desired state from the file (or version control).
Connects to the target devices (via SSH, NETCONF, REST API, etc.).
Retrieves the current state of each device (running-config, operational data).
Compares desired vs. current state.
Generates a list of changes needed (add, remove, modify).
Applies changes, typically in a transactional manner (all-or-nothing).
Reports success/failure.
For example, an Ansible playbook to configure a VLAN on a Cisco switch might look like:
---
- name: Configure VLAN 10
hosts: switches
gather_facts: no
tasks:
- name: Ensure VLAN 10 exists
cisco.ios.ios_vlan:
vlan_id: 10
name: Engineering
state: presentWhen executed, Ansible connects to each switch in the switches inventory, checks if VLAN 10 exists, and creates it if missing. Because the module is idempotent, running it again does nothing unless the VLAN was deleted.
Key Components, Values, Defaults, and Timers
Configuration files: Typically YAML, JSON, HCL (HashiCorp Configuration Language), or XML. YAML is most common in Ansible; HCL in Terraform.
State files: In declarative tools like Terraform, a state file (.tfstate) tracks the real-world resources. This file is critical; losing it can cause resource duplication or deletion. Default location is local, but remote backends (S3, Azure Storage) are recommended for team use.
Idempotency guarantee: Not all modules are fully idempotent. Check module documentation. For example, the ios_config module in Ansible is idempotent for most commands, but some commands (like copy running-config startup-config) are not.
Connection parameters: SSH port defaults to 22, NETCONF to 830, REST API to 443. Timeouts: default SSH timeout is 10 seconds (Ansible timeout parameter).
Retry and backoff: Most tools implement exponential backoff for failed connections. Ansible has retries (default 3) and delay (default 5 seconds).
Configuration and Verification Commands
Ansible (imperative, agentless):
- ansible-playbook site.yml – run playbook
- ansible-inventory --list – view inventory
- ansible all -m ping – test connectivity
Terraform (declarative, stateful):
- terraform init – initialize working directory, download providers
- terraform plan – show changes without applying
- terraform apply – apply changes
- terraform destroy – tear down resources
- terraform state list – list resources in state
Puppet (declarative, agent-based):
- puppet apply manifest.pp – apply manifest locally
- puppet agent --test – run agent once
Chef (imperative, agent-based):
- chef-client --local-mode – run locally
- knife cookbook upload <cookbook> – upload to server
How IaC Interacts with Related Technologies
Version Control (Git): IaC files are stored in Git repositories. Branches represent environments (dev, staging, prod). Pull requests allow code review before applying changes. Git hooks can trigger CI/CD pipelines.
CI/CD Pipelines (Jenkins, GitLab CI, GitHub Actions): On every commit, a pipeline can run terraform plan or ansible-playbook --check to validate syntax and preview changes. After approval, the pipeline applies the configuration automatically.
Monitoring and Observability: Tools like Prometheus, Nagios, or SNMP collectors feed data back. IaC can define monitoring configurations (e.g., alert thresholds, dashboard definitions).
Configuration Management Databases (CMDB): IaC state files or inventories serve as a source of truth, updating CMDBs automatically.
Trap Patterns
Confusing declarative vs. imperative: The exam may ask which tool is declarative. Terraform is declarative; Ansible is primarily imperative (though some modules are declarative).
Idempotency misunderstanding: Candidates think all automation is idempotent. Not true. For example, a script that appends a line to a file without checking if it exists is not idempotent.
State file neglect: Losing the Terraform state file is a common mistake. The exam may ask about state file management.
Configuration drift: Even with IaC, drift can occur if someone manually changes a device. The exam tests that IaC detects drift via terraform plan or ansible-playbook --check.
Define Desired State in Code
The network engineer writes a configuration file (e.g., main.tf for Terraform, site.yml for Ansible) that describes the desired network state. This includes VLANs, interfaces, routing protocols, ACLs, and more. The file is written in a human-readable language like YAML or HCL. The engineer uses a text editor or IDE, often with syntax highlighting and validation plugins. The file is saved locally and then committed to a Git repository. This step is critical because the code becomes the single source of truth. Any deviation from this code is considered a defect.
Store Code in Version Control
The configuration files are pushed to a Git repository (e.g., GitHub, GitLab, Bitbucket). A typical repository has branches for different environments: main (production), staging, dev. Each change goes through a pull request, where team members review the code for errors, security issues, and compliance. The pull request triggers automated checks (linting, syntax validation) via CI/CD. Once approved, the code is merged into the target branch. This ensures every change is tracked, auditable, and reversible.
Run Automation Tool to Apply Configuration
An automation tool (Ansible, Terraform, Puppet) reads the configuration files and connects to the target network devices. For Terraform, the user runs `terraform apply`. For Ansible, `ansible-playbook site.yml`. The tool authenticates to each device using credentials stored in a vault or environment variables. It then compares the desired state from the code against the current state of each device. If differences exist, it generates a plan of changes. The user or CI/CD pipeline reviews the plan and confirms execution. The tool applies the changes in the correct order (e.g., create VLAN before assigning it to an interface).
Verify and Validate Configuration
After applying, the tool reports success or failure. For Terraform, `terraform plan` again shows no changes if successful. For Ansible, the playbook output shows 'changed=0' if idempotent. The engineer may also run manual verification commands (e.g., `show vlan` on a switch) or automated tests (e.g., ping tests, connectivity checks). In a CI/CD pipeline, post-deployment tests run automatically. If a test fails, the pipeline can automatically roll back by applying the previous version of the code (e.g., `git revert` and re-run).
Continuous Monitoring and Drift Detection
IaC is not a one-time activity. Scheduled jobs (e.g., cron, Jenkins) run `terraform plan` or `ansible-playbook --check` periodically to detect configuration drift. If a manual change is made on a device, the next plan will show a diff. Alerts can be sent via email or Slack. Some tools like Terraform Cloud offer 'drift detection' as a managed service. When drift is detected, the engineer can either update the code to match (if the change was intentional) or reapply the code to revert the drift.
Scenario 1: Enterprise Data Center Spine-Leaf Deployment
A large financial institution is deploying a new leaf-spine architecture across three data centers. Each data center has 4 spine switches and 20 leaf switches. Manually configuring each device would take days and risk errors. The network team writes Ansible playbooks that define VLANs, VXLANs, BGP EVPN configurations, and interface descriptions. They use a Jinja2 template for the base configuration, with variables per device (hostname, IP addresses). The playbooks are stored in a private GitLab repository. On every commit to the main branch, a GitLab CI pipeline runs ansible-playbook --check to validate syntax and simulate changes. After approval, the pipeline runs ansible-playbook to push configs to all devices in parallel (using serial: 0 for rolling updates). The playbook is idempotent, so re-running it after a failed switch replacement brings the new switch to the correct state. Common issues include missing SSH keys (solved by using a vault for credentials) and network connectivity loss during config pushes (mitigated by serial: 1 and health checks between switches).
Scenario 2: Cloud Network Automation with Terraform
A SaaS company runs its infrastructure on AWS. They use Terraform to define VPCs, subnets, security groups, route tables, and VPN connections. The Terraform code is stored in a GitHub repository. Each developer works on a feature branch. When a pull request is created, a GitHub Actions workflow runs terraform plan and posts the output as a comment. After merge, the pipeline runs terraform apply automatically. The state file is stored in an S3 bucket with DynamoDB locking to prevent concurrent modifications. One day, a developer accidentally deletes the S3 bucket. The next terraform apply fails because it cannot find the state. The team restores the state from a backup (enabled by versioning on the S3 bucket). This scenario highlights the criticality of state file management and remote backends.
Scenario 3: Campus Network Zero-Touch Provisioning
A university is deploying 500 new access switches across multiple buildings. They use DHCP-based zero-touch provisioning (ZTP) combined with Ansible. When a new switch boots, it obtains an IP address via DHCP, downloads a bootstrap configuration from a TFTP server, which includes a script that runs Ansible pull. The switch then contacts the Ansible Tower server, authenticates using a certificate, and runs a playbook specific to its model and location. The playbook configures VLANs, port security, QoS, and SNMP. The entire process takes 5 minutes per switch, compared to 30 minutes manually. The team monitors the ZTP process via logs in Splunk. A common failure is that the bootstrap configuration is missing due to a misconfigured DHCP option 150. The fix is to verify DHCP scopes and TFTP server availability.
Exactly What N10-009 Tests on This Topic
CompTIA Network+ N10-009 Objective 1.7: 'Explain the importance of planning and implementing network automation and orchestration'. Specifically, you need to know:
IaC concepts: declarative vs. imperative, idempotency, desired state vs. current state.
Tools: Ansible, Terraform, Puppet, Chef – their basic roles (not deep syntax).
Benefits: consistency, speed, version control, reduced human error, audit trail, rollback.
Challenges: learning curve, tool compatibility, state file management, security (secrets in code).
Integration: CI/CD pipelines, version control (Git), testing (syntax validation, dry-run).
Common Wrong Answers and Why Candidates Choose Them
'IaC eliminates the need for network engineers' – Wrong. IaC automates repetitive tasks but still requires engineers to design, write, and maintain the code. Candidates choose this because they overestimate automation.
'Ansible is a declarative tool' – Wrong. Ansible is primarily imperative (procedural). Candidates confuse 'idempotent' with 'declarative'. Idempotent means repeatable; declarative means you specify the end state, not the steps.
'Terraform requires an agent on each device' – Wrong. Terraform is agentless; it uses APIs or SSH. Candidates think of Puppet/Chef which use agents.
'IaC guarantees zero configuration drift' – Wrong. IaC detects and remediates drift, but if the code is not applied regularly, drift can occur. Also, manual changes bypassing automation cause drift.
Specific Numbers, Values, and Terms That Appear Verbatim
Idempotency: The property that applying the same configuration multiple times yields the same result.
Declarative vs. imperative: Know the difference.
State file: Terraform's .tfstate file; must be stored securely.
Playbook: Ansible's configuration file (YAML).
Manifest: Puppet's configuration file.
Cookbook: Chef's configuration unit.
CI/CD: Continuous Integration/Continuous Deployment.
Git: Most common version control system.
Edge Cases and Exceptions the Exam Loves to Test
Idempotency not guaranteed: Some modules/scripts are not idempotent. For example, a script that appends a line to a file without checking duplicates.
State file loss: If the Terraform state file is lost, terraform apply may try to recreate existing resources or fail. The exam may ask how to recover (import resources or restore from backup).
Secret management: Hardcoding passwords in IaC files is a security risk. The exam tests that secrets should be stored in vaults or environment variables.
Rollback strategies: Git revert + re-apply is a common rollback method. Some tools support 'terraform destroy' for complete teardown.
How to Eliminate Wrong Answers Using the Underlying Mechanism
Read the question carefully. If it asks about 'desired state', the answer likely involves a declarative tool like Terraform. If it mentions 'steps to achieve state', it's imperative (Ansible). If the question is about 'repeatable configuration', think idempotency. For 'audit trail', think version control. For 'agentless', think Ansible or Terraform. For 'agent-based', think Puppet or Chef. Eliminate answers that contradict these core mechanisms.
Infrastructure as Code (IaC) manages network devices via machine-readable definition files, enabling automation, consistency, and version control.
Declarative IaC (e.g., Terraform) specifies the desired state; imperative IaC (e.g., Ansible) specifies steps to reach it.
Idempotency means applying the same configuration multiple times yields the same result—a key benefit of IaC.
Version control (Git) is essential for IaC to track changes, enable rollback, and support team collaboration.
CI/CD pipelines automate validation (syntax checks, dry-runs) and deployment of IaC changes.
State files (Terraform .tfstate) must be stored securely and backed up; loss can cause resource duplication or deletion.
Configuration drift occurs when manual changes deviate from the desired state; IaC detects drift via periodic plan/check runs.
Common IaC tools for networking: Ansible (agentless, imperative), Terraform (agentless, declarative), Puppet/Chef (agent-based).
Secrets (passwords, API keys) must never be hardcoded in IaC files; use vaults or environment variables.
Rollback strategies include git revert + re-apply or, for Terraform, using state file versioning.
These come up on the exam all the time. Here's how to tell them apart.
Declarative IaC (Terraform)
Specifies the desired end state only.
Tool determines the steps to achieve that state.
State file tracks real-world resources.
Idempotent by design (if provider supports it).
Best for provisioning cloud resources (VPCs, subnets, etc.).
Imperative IaC (Ansible)
Specifies the exact steps to execute.
Steps are executed in order; order matters.
No persistent state file (inventory is dynamic).
Idempotency depends on module implementation.
Best for configuring software and OS settings on existing devices.
Mistake
Infrastructure as Code means you never log into a device again.
Correct
IaC reduces the need for manual CLI access, but troubleshooting and emergency changes often require direct access. The goal is to minimize manual changes, not eliminate them entirely.
Mistake
All automation tools are idempotent.
Correct
Idempotency is a property of the tool's modules or scripts, not the tool itself. For example, a poorly written Ansible playbook that appends a line without checking if it exists is not idempotent.
Mistake
Terraform and Ansible are competitors and do the same thing.
Correct
They are complementary. Terraform is declarative and focuses on provisioning infrastructure (create, update, delete). Ansible is imperative and focuses on configuration management (installing software, applying configs). Many teams use both.
Mistake
IaC configuration files are only for initial deployment.
Correct
IaC is used throughout the lifecycle: initial deployment, updates, scaling, and teardown. Changes are made by modifying the code and reapplying, not by manual intervention.
Mistake
Version control is optional for IaC.
Correct
Version control is essential. Without it, you lose audit history, rollback capability, and collaboration features. The exam expects you to know that Git is the standard.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
Infrastructure as Code is a broader concept that includes provisioning and managing infrastructure through code. Configuration management is a subset focused on maintaining software and settings on existing devices. Tools like Ansible and Puppet are configuration management tools that can be used for IaC. Terraform is a provisioning tool specifically for IaC. In the N10-009 exam, know that IaC encompasses both provisioning and configuration management.
Idempotency ensures that running the same automation multiple times does not cause unintended changes. For example, if a playbook creates a VLAN, running it again should not create a duplicate or error. This is critical for safe automation, especially when handling large-scale deployments or recovering from failures. Without idempotency, accidental duplicate configurations or inconsistent states can occur.
Terraform uses a state file (terraform.tfstate) to map real-world resources to your configuration. This file is stored locally by default, but for team use, it should be stored in a remote backend like S3, Azure Storage, or Terraform Cloud. The state file is locked during operations to prevent concurrent modifications. Losing the state file can cause Terraform to lose track of resources; recovery requires importing resources or restoring from backup.
A CI/CD pipeline automates the steps from code commit to deployment. For network IaC, when a change is pushed to Git, the pipeline runs syntax checks, linting, and a dry-run (e.g., `terraform plan` or `ansible-playbook --check`). If tests pass, the pipeline can automatically apply the configuration to a test environment, and after manual approval, to production. This ensures consistent, tested, and auditable network changes.
Yes, tools like Ansible can connect to legacy devices via SSH and execute CLI commands. However, the automation is less robust because CLI output parsing is fragile. For devices with APIs (NETCONF, RESTCONF, gRPC), automation is more reliable. The exam may test that IaC can work with any device that supports SSH or SNMP, but modern APIs are preferred.
Configuration drift is when a device's actual configuration differs from the intended state defined in IaC. It occurs due to manual changes, failed deployments, or time-based changes (e.g., DHCP leases). IaC helps by periodically running `terraform plan` or `ansible-playbook --check` to detect drift. When drift is found, the code can be reapplied to revert to the desired state, or the code can be updated if the change was intentional.
Git serves as the version control system for IaC code. It tracks every change, who made it, and when. Branches allow separate development of features without affecting production. Pull requests enable code review before changes are merged. Git also enables rollback: if a change causes issues, you can revert to a previous commit and reapply. The exam expects you to know that Git is the standard tool for version control in IaC.
You've just covered Infrastructure as Code for Networks — now see how well it sticks with free N10-009 practice questions. Full explanations included, no account needed.
Done with this chapter?