Docsity

WGU D522 V2 Python for IT Automation WEN1 Task 1 & Task 2 Comprehensive Study Guide, Exams of Nursing

Toggle sidebar
bg1
Page 1 • WGU D522 V2 • WEN1 Task 1 & Task 2 • Study Guide — Not a Completed Submission
UPDATED 2026/2027 EDITION • WEN1 PERFORMANCE ASSESSMENTS • TASK 1 + TASK 2
WGU D522 V2 Python for IT Automation
WEN1 Task 1 & Task 2 Comprehensive Study Guide
From Python fundamentals to working automation — DNS, MailHog, Helpdesk API, GitLab,
network inventory, reachability, reporting & evidence. Learn the concepts, practice the patterns,
then build your own original submission.
HOW TO USE THIS GUIDE — READ FIRST
This is an independent study guide, not a completed submission and not a copy of any task
prompt. Work through Part A for Python, Part B for Task 1 lab skills, Part C for Task 2 skills, then
use the checklists in Part D to self-grade your own code before submitting. Always follow your
current Course Search / assessment instructions in your ■entity-WGU¦canonical_name=Western
Governors University■ student portal for the exact files, endpoints, credentials, and rubric in your
cohort — lab IPs, ports, and API details change by version.
Contents
• Part A — Python Core for IT Automation (Ch. 1–6) • Part B — WEN1 Task 1 Lab Skills: DNS,
MailHog, Helpdesk API & GitLab • Part C — WEN1 Task 2 Skills: Inventory, Reachability, DNS
Audit, Reporting • Part D — Submission, Evidence & Rubric Checklists • Part E — 40 Practice
Questions + Answers • Appendix — Cheat Sheets, Error Decoder & 7-Day Plan
Part A — Python Core for IT Automation
1. Why Python for IT? Paradigms & Mindset
• Interpreted, readable, batteries-included: fast to write, easy to audit — ideal for glue scripts,
audits, and reports.
• Imperative / procedural: sequence of steps — most automation scripts. Object-oriented:
objects bundle data + behavior (e.g., a Device class). Functional: pure functions, immutable
data, map/filter — useful for transforms.
• Automation mindset: 1) Identify repeatable task → 2) Get data in (file/API/CLI) → 3)
Transform/validate → 4) Act or report → 5) Log + handle errors. Never automate what you cannot
do manually once.
2. Setup, Virtual Environments & Running Code
• Use Python 3.11+, check with python3 --version. Use a venv per project: python3 -m venv
.venv → activate → pip install requests.
• pip freeze > requirements.txt documents dependencies. Never commit secrets — use .env /
environment variables.
• Run: python3 script.py • Interactive: python3 REPL • Debug: print() → then breakpoint() / VS
Code debugger.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download WGU D522 V2 Python for IT Automation WEN1 Task 1 & Task 2 Comprehensive Study Guide and more Exams Nursing in PDF only on Docsity!

UPDATED 2026/2027 EDITION • WEN1 PERFORMANCE ASSESSMENTS • TASK 1 + TASK 2

WGU D522 V2 Python for IT Automation

WEN1 Task 1 & Task 2 Comprehensive Study Guide

From Python fundamentals to working automation — DNS, MailHog, Helpdesk API, GitLab, network inventory, reachability, reporting & evidence. Learn the concepts, practice the patterns, then build your own original submission.

HOW TO USE THIS GUIDE — READ FIRST

This is an independent study guide , not a completed submission and not a copy of any task prompt. Work through Part A for Python, Part B for Task 1 lab skills, Part C for Task 2 skills, then use the checklists in Part D to self-grade your own code before submitting. Always follow your current Course Search / assessment instructions in your nentity-WGU¦canonical_name=Western Governors Universityn student portal for the exact files, endpoints, credentials, and rubric in your cohort — lab IPs, ports, and API details change by version.

Contents

  • Part A — Python Core for IT Automation (Ch. 1–6) • Part B — WEN1 Task 1 Lab Skills: DNS, MailHog, Helpdesk API & GitLab • Part C — WEN1 Task 2 Skills: Inventory, Reachability, DNS Audit, Reporting • Part D — Submission, Evidence & Rubric Checklists • Part E — 40 Practice Questions + Answers • Appendix — Cheat Sheets, Error Decoder & 7-Day Plan

Part A — Python Core for IT Automation

1. Why Python for IT? Paradigms & Mindset

  • Interpreted, readable, batteries-included: fast to write, easy to audit — ideal for glue scripts, audits, and reports.
  • Imperative / procedural: sequence of steps — most automation scripts. Object-oriented: objects bundle data + behavior (e.g., a Device class). Functional: pure functions, immutable data, map/filter — useful for transforms.
  • Automation mindset: 1) Identify repeatable task → 2) Get data in (file/API/CLI) → 3) Transform/validate → 4) Act or report → 5) Log + handle errors. Never automate what you cannot do manually once.

2. Setup, Virtual Environments & Running Code

  • Use Python 3.11+ , check with python3 --version. Use a venv per project: python3 -m venv .venv → activate → pip install requests.
  • pip freeze > requirements.txt documents dependencies. Never commit secrets — use .env / environment variables.
  • Run: python3 script.py • Interactive: python3 REPL • Debug: print() → then breakpoint() / VS Code debugger.

setup.sh — venv + deps python3 -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install requests python-dotenv pip freeze > requirements.txt

3. Variables, Types & Operators

Concept What to Know / IT Example

Variables snake_case , descriptive: hostname, ip_address, ticket_count. Assignment = binds name to object. No declaration needed.

Types str, int, float, bool, None. Use type() and isinstance(). Cast carefully: int('80') works, int('80a') raises ValueError.

Operators Arithmetic **+ - * / // % **** • Comparison == != < > • Logic and or not • Membership in

  • Identity is (use for None).

F-strings f"{hostname} is {status}" — preferred formatting. Format numbers: f"{pct:.1f}%" , pad: f"{n:03d}".

4. Strings, Lists, Dictionaries, Sets & Tuples — The IT Workhorses

  • String: immutable. strip(), lower(), split(), join(), startswith(), replace(). Parse logs / CSV with split, clean with strip.
  • List: ordered, mutable. append(), extend(), [x for x in ...]. Use for inventories, results.
  • Dict: key → value, fast lookup. device['ip'] , .get('dns', 'N/A') avoids KeyError, .items() for loops. This is your JSON / API shape.
  • Set: unique values, fast membership, set(a) - set(b) finds differences — perfect for DNS audit / inventory diff.
  • Tuple: immutable, e.g., (host, port) as dict key. collections.py — inventory patterns devices = [{"host": "sw01", "ip": "10.0.0.5"}, {"host": "sw02", "ip": "10.0.0.6"}] by_host = {d["host"]: d for d in devices} # dict comprehension expected = {"sw01", "sw02", "rtr01"} found = {d["host"] for d in devices} missing = expected - found # {'rtr01'} -> set difference = audit gold print(f"Missing: {sorted(missing)}")

5. Conditionals, Loops & Comprehensions

  • if / elif / else — always handle the else / unknown case in automation. Indentation = blocks ( spaces).
  • for over lists/dicts; while with a clear exit; break / continue for early exit / skip.
  • Comprehensions: [d for d in devices if d['status']=='down'] — concise, but keep readable. If it needs 2 lines, use a loop.
  • Truthiness: empty string/list/dict, 0, None = False. Use if tickets: not if len(tickets) > 0:.

errors.py — fail gracefully, log clearly import logging, requests logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") log = logging.getLogger(name)

try: r = requests.get(url, timeout=10) r.raise_for_status() except requests.RequestException as e: log.error(f"API failed for {url}: {e}") return [] # or re-raise if task must stop

9. HTTP & APIs with requests — The Core Automation Skill

Topic Pattern to Memorize

GET requests.get(url, headers=..., params=..., timeout=10) → r.status_code , r.json()

POST requests.post(url, json={...}, headers=...) — use json= not data= for JSON APIs

Auth Header: {'Authorization': f'Bearer {token}'} or auth=(user, pass). Token from env, never in code.

Status 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Server Error

Pagination Loop page / next until empty. Collect all pages before reporting.

Timeouts Always set timeout=. No timeout = script can hang forever.

10. OOP Basics & Regex — When You Need Them

  • Class: class Device: def init(self, host, ip): ... — use when data + behavior travel together. Otherwise functions are fine.
  • Regex (re): re.search(r'\d+.\d+.\d+.\d+', text) for IPs, r'^[a-z0-9.-]+$' for hostnames. Use re.fullmatch for validation, not search.
  • datetime: datetime.now(timezone.utc).isoformat() for timestamps in reports. Never use naive local time for logs.

Part B — WEN1 Task 1 Lab Skills

Task 1 is a hands-on lab performance assessment. You are given a small lab environment (often with DNS, a mail catcher like nentity-MailHog¦canonical_name=MailHogn, a helpdesk / ticketing API, and a nentity-GitLab¦canonical_name=GitLabn repo) and asked to write Python that does real work against live services and produces evidence — not just a theory answer. The pattern below repeats in every Task 1 variant: connect → query → validate → act → report → commit.

B1. Lab Orientation — Map Before You Code

  • List every service: base URL, port, credentials location, expected data shape. Write it in a README or lab-notes file first.
  • Confirm each service manually: curl / browser / ping before writing Python. If manual fails, Python will fail — fix access first.
  • Record what success looks like for each sub-task: e.g., 'DNS resolves X → Y', 'Ticket created with ID', 'Email captured in nentity-MailHog¦canonical_name=MailHogn', 'Commit pushed to nentity-GitLab¦canonical_name=GitLabn'.
  • Keep a run log : commands run, outputs, timestamps, screenshots. This becomes your evidence.

B2. DNS — Query, Compare & Audit

  • Concepts: A (IPv4), AAAA (IPv6), CNAME (alias), MX (mail), TXT (SPF/DKIM), PTR (reverse). TTL = cache time.
  • Python: socket.gethostbyname(host) for simple A lookup. For full records, use dnspython: dns.resolver.resolve(name, 'MX') if allowed in your lab.
  • Audit pattern: expected (from inventory / task) vs. actual (from DNS) → match / mismatch / missing / extra. Use set difference (Part A §4).
  • Common pitfalls: trailing dot ( example.com. ), case-insensitivity, cached stale records, querying wrong resolver. Normalize: lower().rstrip('.'). dns_audit.py — expected vs actual import socket def resolve(host): try: return socket.gethostbyname(host) except socket.gaierror: return None

expected = {"web01": "10.0.0.10", "db01": "10.0.0.20"} for host, want in expected.items(): got = resolve(host) status = "OK" if got == want else f"MISMATCH got={got} want={want}" print(f"{host}: {status}")

B3. n entity-MailHog¦canonical_name=MailHog n — Capture & Verify Email

Without Sending Real Mail

  • What it is: local SMTP catcher + web UI / API. Your script sends mail to nentity-MailHog¦canonical_name=MailHogn's SMTP port; you verify via its HTTP API / UI — no real inboxes harmed.
  • Flow: Python smtplib → nentity-MailHog¦canonical_name=MailHogn SMTP → GET /api/v2/messages → assert subject / to / body present.
  • Verify, don't assume: check message count increased, subject matches, recipient matches, body contains the ticket ID / hostname.
  • Pitfalls: wrong SMTP port, nentity-MailHog¦canonical_name=MailHogn not running, searching before mail arrives (add small poll / retry).
  • Branch: work on a feature branch if instructed, merge / MR as required. Never push secrets — check .gitignore for .env, pycache, credentials.
  • What evaluators look for: a clean repo, runnable code, README with how to run, and evidence files (logs / reports / screenshots) committed — not just code on your laptop.
  • Verify: after push, open nentity-GitLab¦canonical_name=GitLabn web UI, confirm files + latest commit + pipeline (if any) are green. gitlab.sh — clean commit flow git status git add script.py README.md output/report.csv git commit -m "Add DNS audit + Helpdesk ticket automation" git push origin main # or your branch name

Then verify in GitLab web UI: files, commit, pipeline

TASK 1 EXAM TIP — THE EVIDENCE TRAP Students lose marks not because code fails, but because they cannot prove it ran. For every action, save one artifact: terminal output, API response, nentity-MailHog¦canonical_name=MailHogn screenshot, nentity-GitLab¦canonical_name=GitLabn commit link, or CSV/JSON report. If it isn't saved, it didn't happen for grading.

Part C — WEN1 Task 2 Skills

Task 2 builds on Task 1: less hand-holding, more end-to-end automation. Typical shape: network inventory + reachability + DNS audit + reporting + evidence. You are given (or must build) an inventory, you check what is real, you reconcile differences, and you produce a trustworthy report.

C1. Network Inventory — Single Source of Truth

  • Inventory = list of devices: hostname, IP, role, site, owner, expected DNS, expected status. Source: CSV / JSON / API.
  • Normalize on load: strip, lower hostnames, validate IPs ( ipaddress.ip_address() ), drop duplicates, report bad rows — don't silently skip them.
  • Keep inventory separate from code: data in CSV/JSON, logic in .py. Hard-coding devices in code = brittle + hard to grade. inventory.py — load + validate import csv, ipaddress from pathlib import Path

def load_inventory(path): rows, errors = [], [] with open(path, newline='', encoding='utf-8') as f: for i, r in enumerate(csv.DictReader(f), start=2): host = (r.get('hostname') or '').strip().lower() ip = (r.get('ip') or '').strip() try: ipaddress.ip_address(ip) except ValueError: errors.append(f"Row {i}: bad IP {ip!r} for {host}"); continue if not host: errors.append(f"Row {i}: missing hostname"); continue rows.append({'hostname': host, 'ip': ip, 'role': r.get('role','').strip()}) return rows, errors

C2. Reachability — Ping / TCP / HTTP Checks

  • Ping (ICMP): ping -c 1 -W 2 host via subprocess, or subprocess.run(['ping', ...], capture_output=True). Parse returncode, not just output text.
  • TCP check: socket.create_connection((host, port), timeout=3) — proves a service port is listening, not just host up.
  • HTTP check: requests.get(f'http://{host}/health', timeout=5) — proves app is responding.
  • Classify: UP / DOWN / DEGRADED / UNKNOWN + latency + error message. Never report just 'failed' — say why.
  • Concurrency (bonus): concurrent.futures.ThreadPoolExecutor to check 50 hosts fast. Keep it simple if not required. reachability.py — TCP + ping import socket, subprocess, platform

def tcp_ok(host, port=80, timeout=3): try: with socket.create_connection((host, port), timeout=timeout): return True except OSError: return False

def ping_ok(host): flag = "-n" if platform.system() == "Windows" else "-c" r = subprocess.run(["ping", flag, "1", "-W", "2", host], capture_output=True, text=True, timeout=10) return r.returncode == 0

C3. DNS Audit — The Reconciliation Report

  • Join three sources: inventory IP vs. DNS A record vs. reachability. One row per host, with a verdict.
  • Verdicts: OK (all agree) • DNS_MISMATCH • DNS_MISSING • UNREACHABLE • NOT_IN_INVENTORY (found in DNS but not inventory).
  • Sort + count: summary counts at top, detail rows below. Evaluators scan summary first.

C4. Reporting — CSV + Human-Readable Summary

  • Always produce both : machine-readable CSV/JSON + human-readable summary (Markdown / .txt / PDF).
  • CSV columns: hostname, expected_ip, dns_ip, reachable, verdict, checked_at, notes.
  • Summary must include: total, OK, mismatches, missing, unreachable, timestamp, how to reproduce.
  • Use csv.DictWriter , sort rows by hostname, and include a header. No report = no proof.

D2. Common Failure Modes & Fixes

Symptom Likely Cause → Fix

401 Unauthorized Bad / expired token → re-check env var, regenerate token, print headers (not token) for debug

404 Not Found Wrong base URL / path → copy exact endpoint from task, check trailing slash

Connection refused Service not running / wrong port → check service, curl manually first

KeyError / TypeError API shape changed → print r.json() keys, use .get() with defaults

Script hangs No timeout → add timeout= to every requests / socket call

Works on my machine Hard-coded path / venv → use Path, requirements.txt, README

D3. Evidence Pack Template

  • 01_code/ — .py files + requirements.txt + README.md
  • 02_output/ — report.csv, report.json, run.log, terminal transcript
  • 03_screenshots/ — nentity-MailHog¦canonical_name=MailHogn message, nentity-GitLab¦canonical_name=GitLabn commit, API response, DNS output
  • 04_notes/ — lab notes: URLs, ports, credentials location (not values), decisions, issues fixed

Part E — 40 Practice Questions + Answers

Q1. Which Python type is best for fast lookup of a device by hostname?

A) List B) Dict C) Tuple D) Set Answer: B — Dict: hostname → device dict gives O(1) lookup; list would need a scan.

Q2. What does socket.gethostbyname('web01') return?

A) MX records B) IPv4 address or raises gaierror C) Ticket ID D) HTML

Answer: B — It resolves an A record to IPv4; on failure it raises socket.gaierror.

Q3. Why use .get('dns','N/A') instead of ['dns']?

A) Faster B) Avoids KeyError if key missing C) Uses less memory D) Required by JSON

Answer: B — .get() returns a default instead of crashing on a missing key.

Q4. Which HTTP status means 'Created'?

A) 200 B) 201 C) 404 D) 500

Answer: B — 201 Created is the correct success code for POST creating a resource.

Q5. What is the purpose of MailHog in Task 1?

A) Send real email B) Capture test email locally without real delivery C) Block spam D) Host DNS Answer: B — nentity-MailHog¦canonical_name=MailHogn catches SMTP locally so you can verify mail safely.

Q6. Best way to store an API token?

A) Hard-code in .py B) Commit to Git C) Environment variable / .env (gitignored) D) In a screenshot Answer: C — Env vars keep secrets out of code and history.

Q7. What does requests.get(..., timeout=10) prevent?

A) 404s B) Hanging forever on a dead server C) JSON errors D) Auth failures Answer: B — Timeout bounds how long you wait for a response.

Q8. Set difference expected - found is useful for?

A) Sorting B) Finding missing hosts in a DNS / inventory audit C) Sending email D) Parsing CSV

Answer: B — Set difference instantly shows missing / extra items.

Q9. Why use 'with open(...) as f:'?

A) Faster B) Auto-closes file, even on error C) Encrypts file D) Required for CSV

Answer: B — Context manager guarantees cleanup.

Q10. What should a report summary include?

A) Only code B) Totals, OK/issues counts, timestamp, how to reproduce C) Secrets D) Only screenshots Answer: B — Summary must let a grader verify scope and outcome at a glance.

Q11. f"{pct:.1f}%" formats a float to?

A) 1 decimal place B) 1 integer C) Hex D) Scientific

Answer: A — .1f = one digit after decimal.

Q12. Which is a pure function?

A) One that prints + writes file B) One that returns a value from inputs, no I/O / globals C) One that uses random D) One that mutates globals Answer: B — Pure = same input → same output, no side effects; easy to test.

Q13. What does r.raise_for_status() do?

A) Prints JSON B) Raises HTTPError for 4xx/5xx C) Retries D) Closes connection Answer: B — It turns error statuses into exceptions you can handle.

Q14. Best verdict for inventory IP != DNS IP?

A) OK B) DNS_MISMATCH C) NOT_IN_INVENTORY D) UNKNOWN

Answer: B — Mismatch means the two sources disagree.

Q15. How to check a TCP port is listening?

A) Ping only B) socket.create_connection((host,port), timeout=...) C) Read CSV D) Check Git

Answer: B — TCP connect proves the port accepts connections.

Q16. Why use pathlib.Path?

A) Faster loops B) Cross-platform paths, readable, / operator C) Required for requests D) Encrypts Answer: B — Path handles Windows / Linux differences and is cleaner than string paths.

Q17. What does csv.DictReader return?

A) README B) requirements.txt (pip freeze) C) .gitignore D) report.csv

Answer: B — requirements.txt documents exact deps for reproducibility.

Q29. What is TTL in DNS?

A) Time to live — how long a record may be cached B) Ticket length C) TCP timeout D) Git log

Answer: A — TTL controls caching; stale cache can explain old values.

Q30. Why avoid bare except:?

A) Slower B) Hides bugs, catches KeyboardInterrupt / SystemExit, makes debugging hard C) Uses memory D) Not allowed in Git

Answer: B — Catch specific exceptions.

Q31. What does ThreadPoolExecutor help with?

A) Sorting B) Checking many hosts concurrently C) Sending email D) Parsing JSON

Answer: B — Parallel I/O for reachability checks.

Q32. What is the best first fix for 401?

A) Change code logic B) Check token / env var, regenerate if expired C) Delete DB D) Reboot router Answer: B — 401 = auth problem, not logic.

Q33. Why use json.dump(..., indent=2)?

A) Faster B) Human-readable, diff-friendly output C) Encrypts D) Compresses

Answer: B — Indented JSON is readable in evidence.

Q34. What does 'r.json()' do?

A) Sends request B) Parses response body as JSON → dict/list C) Closes D) Prints headers

Answer: B — Parses JSON body.

Q35. Which is a good commit message?

A) 'stuff' B) 'Add DNS audit + Helpdesk ticket automation' C) 'asdf' D) 'final_final2'

Answer: B — Clear, verb + scope.

Q36. What should you do before running a script twice?

A) Nothing B) Ensure idempotency — don't create duplicates C) Delete Git D) Change password Answer: B — Re-runs should be safe.

Q37. What does subprocess.run(['ping',...]) return?

A) Bool B) CompletedProcess with returncode, stdout, stderr C) IP D) JSON Answer: B — Check returncode == 0 for success.

Q38. Why use datetime.now(timezone.utc)?

A) Faster B) Unambiguous, timezone-aware timestamps for logs/reports C) Required for CSV D) Shorter

Answer: B — UTC avoids local-time confusion.

Q39. What is the main Task 2 deliverable?

A) Only code B) Code + validated report + evidence proving inventory/reachability/DNS audit C) Only screenshots D) Only README Answer: B — Task 2 is end-to-end: code + report + proof.

Q40. What does 'git status' show?

A) Passwords B) Changed / untracked files, branch C) API keys D) DNS Answer: B — Status shows what would be committed.

Appendix — Cheat Sheets

A1. Python Quick Reference

cheatsheet.py

Strings: s.strip().lower().split(',') | f"{x}" | ','.join(list)

Lists: [x for x in xs if cond] | xs.append(v) | sorted(xs)

Dicts: d.get(k, default) | d.items() | {k: v for k,v in ...}

Sets: a - b # missing | a & b # common | a | b # union

Files: Path('x.csv').read_text(encoding='utf-8')

HTTP: requests.get(url, headers=H, timeout=10) # .status_code .json()

Errors: try: ... except requests.RequestException as e: log.error(e)

A2. Error Decoder

Error / Code Meaning → Action

NameError Used undefined name → check spelling / import

TypeError Wrong type for operation → print type(x), convert

ValueError Right type, bad value → validate input, e.g. int('abc')

KeyError Missing dict key → use .get(), check API shape

FileNotFoundError Path wrong → print Path.cwd(), use relative Path

401 / 403 Auth / permission → token, role, env var

404 Wrong URL / ID → copy endpoint, check ID exists

500 Server error → check server logs, retry, report

A3. 7-Day Study Plan

  • Day 1: Part A §§1–4 + write 10 small scripts (strings, lists, dicts, sets).
  • Day 2: Part A §§5–8 + file I/O, CSV/JSON, error handling, logging.
  • Day 3: Part A §9 + HTTP: GET/POST a public test API (e.g., httpbin) with auth + pagination.
  • Day 4: Part B: DNS + nentity-MailHog¦canonical_name=MailHogn patterns + build a mini DNS audit.
  • Day 5: Part B: Helpdesk API + nentity-GitLab¦canonical_name=GitLabn flow + evidence pack.
  • Day 6: Part C: Full Task 2 mini-project — inventory → reachability → DNS audit → CSV report.