TExcelTAD
Home › Automation Scripting: Bash, Python & Go › Automation Scripting Exercises

Automation Scripting Exercises

Six exercises, two per language. Each starts from runnable code with a gap or a bug: run it first to see what it does now, change it until the output matches the expected output, then compare with the solution. The shell exercises are sessions you can repeat on any Linux machine with jq, yq and ShellCheck installed; the Python and Go ones run here.

Exercise 1: Fix a strict-mode script

Topics: Strict Mode and Its Traps, ShellCheck

count-errors.sh counts ERROR lines per log file. It has three bugs: a file name with a space breaks it, the script stops after a file with no errors, and a missing file is reported as an empty count with status 0 instead of failing. ShellCheck points at two of them.

bash · try it yourself
cat > count-errors.sh <<'SCRIPT'
#!/usr/bin/env bash
set -euo pipefail
count_file() {
  local n=$(grep -c ' ERROR ' $1)
  echo "$n"
}
total=0
for f in "$@"; do
  n=$(count_file "$f")
  echo "$f: $n"
  ((total += n))
done
echo "total: $total"
SCRIPT
printf '10:00 INFO up\n10:01 ERROR db\n10:02 ERROR db\n' > "app 1.log"
printf '10:00 INFO up\n' > app2.log
printf '10:05 ERROR disk\n' > app3.log
bash count-errors.sh "app 1.log" app2.log app3.log; echo "-> status $?"
bash count-errors.sh app3.log missing.log; echo "-> status $?"
shellcheck count-errors.sh && echo "shellcheck: clean"
grep: app: No such file or directory
grep: 1.log: No such file or directory
app 1.log:
-> status 1
app3.log: 1
grep: missing.log: No such file or directory
missing.log:
total: 1
-> status 0

In count-errors.sh line 4:
  local n=$(grep -c ' ERROR ' $1)
        ^-- SC2155 (warning): Declare and assign separately to avoid masking return values.
                              ^-- SC2086 (info): Double quote to prevent globbing and word splitting.

Did you mean:
  local n=$(grep -c ' ERROR ' "$1")

For more information:
  https://www.shellcheck.net/wiki/SC2155 -- Declare and assign separately to ...
  https://www.shellcheck.net/wiki/SC2086 -- Double quote to prevent globbing ...

Expected output:

text
app 1.log: 2
app2.log: 0
app3.log: 1
total: 3
-> status 0
app3.log: 1
grep: missing.log: No such file or directory
-> status 2
shellcheck: clean
Show solution
bash
count_file() {
  local n
  n=$(grep -c ' ERROR ' "$1") || { [ $? -eq 1 ] || return 2; }   # 1 = no match (fine), 2 = error
  echo "$n"
}
total=0
for f in "$@"; do
  n=$(count_file "$f")
  echo "$f: $n"
  total=$((total + n))
done
  • "$1" keeps app 1.log one argument.
  • Declaring local n first lets the substitution's status count. grep -c exits 1 when it finds nothing (fine here, the count is 0) and 2 when it cannot read the file, which now becomes the function's status. Because n=$(count_file "$f") is a plain assignment, set -e then stops the script with that status.
  • ((total += n)) returns status 1 whenever the result is 0, which set -e treats as a failure; total=$((total + n)) is an assignment and always succeeds.

Exercise 2: Pods per node with jq

Topics: jq: Transforming Data

Print one line per node, node: count (pod, pod, …), sorted by node name, with pods sorted by name. Pods that are not scheduled yet (no nodeName) go under unscheduled.

bash · try it yourself
cat > pods.json <<'JSON'
{"items": [
 {"metadata": {"name": "web-2"},  "spec": {"nodeName": "node-b"}},
 {"metadata": {"name": "api-1"},  "spec": {"nodeName": "node-a"}},
 {"metadata": {"name": "batch-9"}, "spec": {}},
 {"metadata": {"name": "web-1"},  "spec": {"nodeName": "node-a"}},
 {"metadata": {"name": "api-2"},  "spec": {"nodeName": "node-b"}},
 {"metadata": {"name": "cron-3"}, "spec": {}}
]}
JSON
# TODO: replace this filter
jq -r '.items[] | .metadata.name' pods.json
web-2
api-1
batch-9
web-1
api-2
cron-3

Expected output:

text
node-a: 2 (api-1, web-1)
node-b: 2 (api-2, web-2)
unscheduled: 2 (batch-9, cron-3)
Show solution
bash
jq -r '.items
  | map({node: (.spec.nodeName // "unscheduled"), name: .metadata.name})
  | group_by(.node)[]
  | "\(.[0].node): \(length) (\(map(.name) | sort | join(", ")))"' pods.json

group_by sorts by the key, so the nodes come out in order (unscheduled sorts after node-*). // supplies the default for pods without a node.

Exercise 3: A release bump with yq

Topics: yq: Querying and Editing YAML

manifests.yaml holds a Deployment and a CronJob that both run the shop-api image, plus a Service. Write a yq command that sets the tag of every registry.example.com/shop-api image to the value of $TAG, leaves other images (the envoy sidecar) alone, and keeps the comments.

bash · try it yourself
cat > manifests.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata: {name: shop-api}
spec:
  template:
    spec:
      containers:
        - name: api
          image: registry.example.com/shop-api:1.4.2  # bumped by CI
        - name: proxy
          image: envoyproxy/envoy:v1.36.2
---
apiVersion: batch/v1
kind: CronJob
metadata: {name: shop-api-cleanup}
spec:
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - name: cleanup
              image: registry.example.com/shop-api:1.4.2
---
apiVersion: v1
kind: Service
metadata: {name: shop-api}
YAML
export TAG=1.5.0
# TODO: write the yq -i command here
yq -N '.. | select(has("image")) | .image' manifests.yaml
grep -c 'bumped by CI' manifests.yaml
registry.example.com/shop-api:1.4.2
envoyproxy/envoy:v1.36.2
registry.example.com/shop-api:1.4.2
1

Expected output:

text
registry.example.com/shop-api:1.5.0
envoyproxy/envoy:v1.36.2
registry.example.com/shop-api:1.5.0
1
Show solution
bash
yq -i '(.. | select(has("image")) | select(.image | test("^registry.example.com/shop-api:")) | .image)
         |= sub(":[^:]+
quot;, ":" + strenv(TAG))' manifests.yaml

.. visits every node in each document, so the same expression finds containers in a Deployment, a CronJob or anything else, and the Service (which has no image) is untouched. strenv passes the tag as data.

Exercise 4: Parse an env file

Topics: Python Automation Scripts, Parsing JSON and YAML in Python

Write parse_env(text) for .env files: skip blank lines and # comments, accept an optional export prefix, strip one pair of matching quotes around a value, and reject bad lines with an error that names the line number. Keys must look like shell variable names.

python · try it yourself
import re

def parse_env(text):
    # TODO: return (values, errors)
    return {}, []

text = '''# shop-api settings
LOG_LEVEL=info
export REGION="eu-west-1"
GREETING='hello, world'
EMPTY=

DATABASE_URL=postgres://db:5432/shop?sslmode=require
9LIVES=true
JUST_A_WORD
'''
values, errors = parse_env(text)
for k, v in values.items():
    print(f"{k}={v!r}")
for e in errors:
    print("error:", e)
print(f"{len(values)} value(s), {len(errors)} error(s)")
0 value(s), 0 error(s)

Expected output:

text
LOG_LEVEL='info'
REGION='eu-west-1'
GREETING='hello, world'
EMPTY=''
DATABASE_URL='postgres://db:5432/shop?sslmode=require'
error: line 8: invalid key '9LIVES'
error: line 9: expected KEY=VALUE
5 value(s), 2 error(s)
Show solution
python
import re

KEY = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")

def parse_env(text):
    values, errors = {}, []
    for no, raw in enumerate(text.splitlines(), start=1):
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        line = line.removeprefix("export ").lstrip()
        key, sep, value = line.partition("=")
        if not sep:
            errors.append(f"line {no}: expected KEY=VALUE")
            continue
        key = key.strip()
        if not KEY.match(key):
            errors.append(f"line {no}: invalid key {key!r}")
            continue
        value = value.strip()
        if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
            value = value[1:-1]
        values[key] = value
    return values, errors

partition("=") splits at the first = only, so values may contain = (as URLs often do). Collecting every error instead of stopping at the first lets the user fix the file in one go.

Exercise 5: Fetch every page, surviving a hiccup

Topics: Retries, Backoff and Pagination

The fake API below returns pages of 2 users with a next cursor, and fails with 503 on the first request for page 2. Complete fetch_all so it returns every user, retrying a 503 up to 3 times (record the waits in waits instead of sleeping: 0.1 s, then 0.2 s, …) and raising RuntimeError for any other status.

python · try it yourself
USERS = ["ada", "grace", "linus", "margaret", "ken"]
calls = []

def fake_api(cursor):
    """Returns (status, body). body = {"items": [...], "next": cursor or None}."""
    calls.append(cursor)
    start = int(cursor or 0)
    if start == 2 and calls.count(cursor) == 1:
        return 503, None
    nxt = str(start + 2) if start + 2 < len(USERS) else None
    return 200, {"items": USERS[start:start + 2], "next": nxt}

def fetch_all(api, waits):
    # TODO: follow "next" until it is None, retrying 503s with doubling waits
    status, body = api(None)
    return body["items"]

waits = []
print(fetch_all(fake_api, waits))
print("requests:", calls)
print("waits:", waits)
['ada', 'grace']
requests: [None]
waits: []

Expected output:

text
['ada', 'grace', 'linus', 'margaret', 'ken']
requests: [None, '2', '2', '4']
waits: [0.1]
Show solution
python
def fetch_all(api, waits, retries=3):
    items, cursor = [], None
    while True:
        delay = 0.1
        for attempt in range(retries + 1):
            status, body = api(cursor)
            if status != 503 or attempt == retries:
                break
            waits.append(delay)
            delay *= 2
        if status != 200:
            raise RuntimeError(f"cursor {cursor}: HTTP {status}")
        items.extend(body["items"])
        cursor = body["next"]
        if cursor is None:
            return items

The retry loop sits inside the pagination loop, so a failure on page 2 retries page 2, not the whole listing.

Exercise 6: A phase summary in Go

Topics: encoding/json for Tools

Decode the pod list and print the number of pods per phase, sorted by phase name, followed by the names of pods that are not Running or Succeeded. Exit status (printed here) is 1 if there are any such pods.

go · try it yourself
package main

import (
	"encoding/json"
	"fmt"
)

const data = `{"items": [
 {"metadata": {"name": "api-1"}, "status": {"phase": "Running"}},
 {"metadata": {"name": "job-7"}, "status": {"phase": "Succeeded"}},
 {"metadata": {"name": "api-2"}, "status": {"phase": "Pending"}},
 {"metadata": {"name": "web-1"}, "status": {"phase": "Running"}},
 {"metadata": {"name": "etl-3"}, "status": {"phase": "Failed"}}]}`

// TODO: declare the structs you need

func main() {
	var list map[string]any // TODO: use your struct
	if err := json.Unmarshal([]byte(data), &list); err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("decoded keys:", len(list))
}
decoded keys: 1

Expected output:

text
Failed: 1
Pending: 1
Running: 2
Succeeded: 1
needs attention: api-2, etl-3
exit status 1
Show solution
go
package main

import (
	"encoding/json"
	"fmt"
	"sort"
	"strings"
)

type PodList struct {
	Items []struct {
		Metadata struct {
			Name string `json:"name"`
		} `json:"metadata"`
		Status struct {
			Phase string `json:"phase"`
		} `json:"status"`
	} `json:"items"`
}

func main() {
	var list PodList
	if err := json.Unmarshal([]byte(data), &list); err != nil {
		fmt.Println("error:", err)
		return
	}
	counts := map[string]int{}
	var bad []string
	for _, p := range list.Items {
		counts[p.Status.Phase]++
		if p.Status.Phase != "Running" && p.Status.Phase != "Succeeded" {
			bad = append(bad, p.Metadata.Name)
		}
	}
	phases := make([]string, 0, len(counts))
	for ph := range counts {
		phases = append(phases, ph)
	}
	sort.Strings(phases)
	for _, ph := range phases {
		fmt.Printf("%s: %d\n", ph, counts[ph])
	}
	code := 0
	if len(bad) > 0 {
		sort.Strings(bad)
		fmt.Println("needs attention:", strings.Join(bad, ", "))
		code = 1
	}
	fmt.Println("exit status", code)
}

The map of counts is sorted through a slice of its keys before printing, the usual Go idiom for deterministic output.

Test yourself

In Exercise 1, why does ((total += n)) stop the script when the first file has no errors?

  1. n is empty
  2. The arithmetic command returns status 1 when its result is 0, and set -e exits
  3. total is read-only
  4. Arithmetic is not allowed in loops

In Exercise 5, where should the retry loop sit relative to the pagination loop?

  1. Outside: retry the whole listing
  2. Inside: retry only the page that failed
  3. It does not matter
  4. Retries and pagination cannot be combined