Skip to main content
AUTOMATING IT OPERATIONS / LESSON 01

Automation Projects & Git Workflows.

Move from an isolated Python script to a reviewable operations tool. Learn to validate evidence, use Git branches, plan without changing systems, and produce reliable handoffs.

Intermediate75–110 minutes plus a local Git exercise5 original Python challengesLocal Git exerciseNo live infrastructure
00

What you'll learn

Python Fundamentals taught you to reason about code, and Applied Python introduced local tools, APIs, and reliable execution. This path starts here in Lesson 01, not on a separate landing page. The shared navigation above the lesson contains the course phases, Learn → Practice milestones and browser-local progress. The introductory examples are small on purpose: understand the safety boundaries before connecting to live systems.

Try Python as you read: The collapsible Python Scratchpad tab is available at the right edge (bottom-left on mobile). Open it anytime to test or change a code example without leaving the lesson. It does not affect Practice progress.

  • Explain the collect → validate → plan → authorize → execute → verify → record lifecycle.
  • Create a local Git repository, a working branch and meaningful staged commits.
  • Validate identifiers and address families before deciding what to do with an inventory.
  • Separate read-only plans from explicitly authorized operational changes.
  • Describe dry runs, approval scope, post-change verification and rollback readiness.
  • Generate structured, timestamped evidence without exposing credentials.
Where the code runs: The companion Practice workbench executes Python in an isolated browser environment using fictional data. Git commands in this lesson run only in your own terminal if you choose the optional local exercise. No real endpoints, remote devices, or credentials are needed.

Prerequisite: Be comfortable with functions, loops, lists, dictionaries and reading local files. If you need a refresher, start with Applied Python.

FROM SCRIPT TO OPERATIONAL TOOL
01

Think in a complete operational workflow

A useful automation doesn't stop at getting a response from a server. It separates discovery from validation, planning, authorization, execution, verification, and reporting. Those boundaries prevent a failed check or a malformed inventory from becoming an incorrect change. An unreachable device is not proof that its DNS is wrong, and a command exiting successfully is not proof that the service recovered.

Collect facts first

Gather the inventory, requested action, observed response and timestamp without modifying the target. Preserve uncertainty when information cannot be obtained.

Decide separately

Compare evidence with a trusted policy or baseline. Build a report or proposed plan without executing a change; reject ambiguous targets.

Verify and record

After any authorized operation, check the actual state again. Report unsuccessful, unknown and partial outcomes explicitly rather than declaring success from the absence of errors.

PYTHON / READ AND PREDICTExample
def classify_probe(response):
    if response is None:
        return 'unknown'
    if response.get('reachable') is False:
        return 'unreachable'
    if response.get('reachable') is True:
        return 'reachable'
    return 'unknown'

print(classify_probe({'reachable': False}))
Why should a timeout produce an unknown or unreachable observation rather than an automatic configuration change? Reveal the explanation after predicting.

A timeout does not tell you which layer failed. It could be routing, a firewall, a powered-down device or the probe itself. Collect corroborating evidence and use change authorization before remediation.

Remember: An automation is a decision pipeline, not just a sequence of commands.
YOUR SCRIPT NEEDS A HISTORY
02

Use Git to preserve safe, reviewable changes

In IT operations, the ability to show what changed is nearly as important as the script itself. Git records versions of text files. A commit is a deliberate snapshot; a branch isolates work while you refine or test it. GitLab and GitHub host repositories, but the core commands work in a local terminal. A repository is not a backup of production secrets or collected confidential data. Before following the terminal examples, confirm Git is installed using git --version. If your first commit reports an unknown author, set a personal Git user.name and user.email on your own machine; the example does not require a hosted GitHub or GitLab account.

Working tree → stage → commit

Edit a local file, inspect git status, stage only intended files with git add, review the staged diff, and commit a meaningful change. Uncommitted edits are not in branch history. On a new computer, Git may request your author name and email before the first commit; configure your own identity locally rather than copying credentials from a lesson.

Branches protect unfinished work

Create a feature branch for one change, make focused commits, then open a review before merging it. Branch names and commit messages should explain the operational purpose.

Review before pushing

Use .gitignore for generated files and local secrets, and check git diff --cached for accidental credentials, tokens, logs or customer data before the commit. Ignore rules do not remove secrets already committed.

TERMINAL / RUN LOCALLYOptional commands
git --version
git init operations-lab
git -C operations-lab switch -c feature/health-check
# Create operations-lab/health_check.py with a harmless print statement.
git -C operations-lab status
git -C operations-lab add health_check.py
git -C operations-lab diff --cached
git -C operations-lab commit -m "Start read-only health check"
git -C operations-lab log --oneline --decorate
You edited a file but git status shows it as modified. Will a new commit automatically include it? Reveal the explanation after predicting.

Not unless you stage that edit. Review and stage the specific file first. Then commit the staged snapshot. Avoid blindly staging everything in a repository that might contain generated output or credentials.

Remember: Use a branch and small, reviewed commits; Git is your audit trail for source changes, not proof that infrastructure changed.
BAD DATA MAKES BAD CHANGES
03

Define the input contract before contacting devices

Operational tools often start with a CSV export, API JSON, or device inventory. Specify mandatory fields, data types, identifiers and allowed states. A duplicate host or missing address is an input problem, not an invitation to guess. Keep the raw observations separate from normalized data and record which records were rejected.

Identifiers must be trustworthy

Normalize surrounding spaces and casing consistently, but do not quietly merge two conflicting records. Reject empty hostnames and ambiguous duplicates.

Validate addresses, not just strings

The standard-library ipaddress module parses IPv4 and IPv6 addresses. Choose the allowed address families explicitly for each tool. Never treat a syntactically valid address as proof a device is reachable.

Configuration belongs outside logic

Use documented CLI arguments or approved environment configuration for sites, timeouts and endpoints. A missing value is different from an explicit False or zero, and secrets should never be committed.

PYTHON / READ AND PREDICTExample
from ipaddress import ip_address

samples = ['192.0.2.41', 'not-an-ip', '2001:db8::5']
for raw in samples:
    try:
        address = ip_address(raw)
        print(raw, 'IPv' + str(address.version))
    except ValueError:
        print(raw, 'invalid')
If a hostname appears twice with different IP addresses, should the script just use the last record? Reveal the explanation after predicting.

No. The duplicate may be an export error, an outdated address or a genuine conflict. Halt actions for that target and report the ambiguity instead of silently choosing a winner.

Remember: Validate the entire decision input before generating an actionable plan.
READ-ONLY BEFORE WRITE
04

Make dry runs and approvals first-class behavior

A production script should be safe to inspect and run without automatically changing infrastructure. A dry run creates a proposed action list and shows the exact targets, expected effect and evidence. A separate approved apply operation can later perform changes, but only after re-checking targets and authorization. This course uses fictional data and a browser-isolated Python workbench; it does not access real devices.

Start in report-only mode

A default run should print the plan, not restart services or rewrite configurations. Make write operations opt-in and limited to an explicitly approved scope.

Require an exact target match

A change request for APP-01 does not authorize an action on APP-02. Match identity, action, environment and approval state before executing.

Idempotency and rollback

Repeating a verified operation should not produce duplicate tickets or repeated disruptive changes. Know what state to restore before modifying anything.

PYTHON / READ AND PREDICTExample
request = {'target': 'APP-01', 'action': 'inspect'}

# Construct a plan without executing its actions.
plan = {
    'target': request['target'],
    'action': request['action'],
    'mode': 'dry-run',
}
print(plan)
A dry run passed yesterday. Is that sufficient authorization to apply the change today? Reveal the explanation after predicting.

No. The environment and approval scope could have changed. Revalidate the target and current state, confirm the approved change window, and require explicit authorization at execution time.

Remember: Planning, authorization, and execution should be different steps with visible boundaries.
NO EVIDENCE, NO SUCCESS CLAIM
05

Produce logs and a useful handoff

Operations automation is only as trustworthy as its evidence. Capture the device identifier, what was checked, the result and an unambiguous timestamp. Distinguish success, failure, and unknown outcomes. Use structured records so another program can inspect them, and a concise human summary so a technician can quickly decide what needs attention.

Use aware timestamps

Prefer datetime.now(timezone.utc).isoformat() for audit events. Label UTC clearly; avoid ambiguous local timestamps when events may cross time zones.

Don't expose credentials in logs

Record non-sensitive request IDs, status codes and the operation performed. Never print authorization headers, API tokens or passwords into a ticket or evidence file.

Verify what you claim

A script that queued an action has not proved the action completed. Record separate attempted, verified and failed states; preserve unresolved exceptions for a follow-up.

PYTHON / READ AND PREDICTExample
from datetime import datetime, timezone

event = {
    'host': 'APP-01',
    'check': 'https-health',
    'result': 'unknown',
    'timestamp_utc': datetime.now(timezone.utc).isoformat(),
}
print(event['host'], event['result'])
An API reports 202 Accepted after you submit a maintenance job. Is the device verified healthy? Reveal the explanation after predicting.

No. HTTP 202 means the request was accepted for processing; the operation may not have completed. Poll the job status through an approved API or perform a separate health check before claiming restoration.

Remember: Log verified outcomes and unresolved uncertainty, not just the command you tried.
ON YOUR COMPUTER / OPTIONAL PROJECT
06

Build a local read-only operations starter

The browser exercises check Python logic. For real Git practice, use a separate fictional local folder and your terminal. Finish each action yourself rather than copying a complete solution.

  1. Create a new folder called operations-lab with a Git repository and feature/health-check branch.
  2. Add a small health_check.py that reads three fictional host records (no real connections) and prints a safe summary.
  3. Create a README describing required inventory fields, default dry-run behavior and what an unknown result means.
  4. Review git status and git diff --cached, then commit only the README and Python source with a descriptive message.
  5. Change one fictional record, inspect the diff, create a second commit and compare the two versions with git log.
Safety boundary: Keep real customer inventories, access tokens, generated logs and credentials out of the repository. No device access or live tickets are required in this exercise.
07

Prove the concepts with real Python

Five independent exercises challenge record validation, probe interpretation, read-only change plans, exact approval matching, and trustworthy evidence summaries. Checks run against extra fictional cases so memorizing the example output is not enough.

After reading, use the shared Continue Your Learning Path panel below to mark Lesson 01 complete and begin the five-challenge Practice milestone. Complete Practice before continuing to Lesson 02.

08

Official references

Use the source documentation to explore tools, not as a substitute for understanding the examples.

CONTINUE YOUR LEARNING PATH · AUTOMATING IT OPERATIONS

Complete the Practice milestone

You've reached the end of this written lesson. Your next step is practice: Operational Safety · Python Coding Clinic. Complete that milestone before moving to the following lesson. You can revisit the explanation whenever you need it. Next: milestone 2 of 12.

Your completion marks are saved in this browser only.