Intermediate Level
This section covers more advanced concepts in automation and scripting, including error handling, scheduling, and integration with various DevOps tools.
How do you pass arguments to a Bash script?
Positional arguments arrive as
$1,$2, ... with$0being the script name:bashbashAlso know:
$#is the argument count,"$@"is all arguments (quoted, preserves spaces), andshiftdrops$1and moves the rest down. For anything beyond simple flags, mentiongetoptsas the standard way to parse options like-e prod.How do you handle errors in Bash scripts?
A production-grade Bash script starts with strict mode:
bash-e— exit immediately if any command fails (non-zero exit code)-u— error on unset variables (catches typos like$ENVIROMENT)-o pipefail— a pipeline fails if any command in it fails, not just the last one
For cleanup and reporting, pair strict mode with a trap:
bashAlso show judgment:
set -edoesn't fire insideifconditions or after||, so commands whose failure you expect (likegrepfinding nothing) need explicit handling.What is an Ansible playbook?
A playbook is a YAML file that defines automation as an ordered list of plays, each mapping a group of hosts (from an inventory) to tasks:
yamlEach task calls a module (like
aptorcopy) — and modules are idempotent, so running the playbook twice leaves the same end state without side effects. Playbooks are how configuration management, patching, and multi-tier deployments are expressed in Ansible; the inventory, variables, and roles keep them reusable across environments.How do you handle exceptions in Python?
pythonBest practices interviewers expect:
- Catch specific exceptions (
FileNotFoundError,KeyError) — a bareexcept:hides real bugs like typos andKeyboardInterrupt - Use
finally(or awithcontext manager) for guaranteed cleanup - Let a script exit non-zero on unhandled failure so CI/CD pipelines detect the failure
- Catch specific exceptions (
How do you schedule a script with Cron?
Edit the crontab with
crontab -eand add a line with five time fields:bashFields are:
minute hour day-of-month month day-of-week— so this runs daily at 05:00. Useful examples:*/15 * * * *(every 15 minutes),0 4 * * 1(Mondays at 04:00).Two gotchas worth mentioning: cron runs with a minimal environment (always use absolute paths for binaries and scripts), and redirecting output (
>> file 2>&1) is the only way to capture failures, since nothing is watching cron's stdout.How do you execute Groovy logic in a Jenkins pipeline?
In a declarative pipeline, Groovy goes inside a
script { }block:groovyOutside pipelines, Groovy runs from Manage Jenkins → Script Console for admin automation. Best practice to mention: keep
script {}blocks small — declarative pipeline steps are safer, resumable, and readable; heavy Groovy belongs in a shared library.How do you create and manipulate lists in Python?
pythonLists are ordered and mutable — the everyday container in automation scripts (hostnames, file paths, service names). List comprehensions are worth mentioning: they're the idiomatic Python way to filter/transform a list in one line.
What is
sedin Bash?sedis a stream editor for parsing and transforming text line by line — most famously for substitution:bashThe
scommand means substitute,gmeans every occurrence on the line (without it, only the first). In DevOps it's the quick fix for config changes in pipelines — though for structured formats (YAML/JSON), tools likeyq/jqare safer than text substitution.How do you define a dictionary in Python?
pythonDictionaries are key-value maps with O(1) lookup by key — the natural fit for configuration, API payloads, and tagging metadata. Prefer
.get()over[]when a key may be missing, since[]raisesKeyError.How do you validate a YAML file?
Options depend on context — mentioning more than one scores well:
bashKey distinction: syntax checks (
yamllint, safe_load) only prove the YAML parses;kubectl --dry-runadditionally validates fields against the Kubernetes API schema. In CI, run validation as a pre-commit or pipeline step before anything gets deployed.How do you install Python modules?
bashAlways install inside a virtual environment (or container) — global installs cause version conflicts between projects and pollute the host. In pipelines, generate the lockfile with
pip freeze > requirements.txtso every run installs exactly the same versions.What is the Jenkins pipeline syntax for automation?
The modern declarative style:
groovyStructure to name:
pipeline → agent → stages → stage → steps, pluspostfor always/failed cleanup. The older scripted pipeline (a raw Groovy file withnode { }) is more flexible but less structured — declarative is the default recommendation today.How do you iterate over a dictionary in Python?
python.items()yields(key, value)tuples, which unpack directly into two loop variables. A practical DevOps use: looping over a dict of environment → config to generate deployments for each environment.How do you set environment variables in Bash?
bashThe
exportkeyword is the interview point: a variable set withoutexportexists only in the current shell and is not visible to scripts/commands it launches. That's why CI tools and Dockerfiles use exported variables (orENVinstructions) — so child processes like your build script can read them.What is an Ansible role?
A role is a reusable, self-contained unit of Ansible automation with a standard directory structure:
codeRoles let you package "install and configure nginx" once and reuse it across playbooks, projects, and teams (public ones are shared via Ansible Galaxy). In interviews, connect it to DRY: playbooks define what runs where, roles define how a component is configured.
What is a multiline string in YAML?
Block scalars:
yamlUse
|for scripts and certificates where line breaks matter,>for long human-readable text. A trailing minus (|-,>-) strips the final newline — relevant when generating files where you don't want an extra blank line. This comes up constantly in CI configs, Kubernetes ConfigMaps, and Ansible tasks.What is an associative array in Bash?
A key-value map, available in Bash 4+:
bashRegular Bash arrays are index-based (
arr[0]); associative arrays let you look up by name — ideal for mappings like environment → URL or service → host. Worth noting:declare -Arequires Bash 4+, so it doesn't run on default macOS Bash (3.2) — a real portability gotcha in mixed teams.How do you run a shell command from Python?
Use the
subprocessmodule —os.system()is legacy:pythonWhy
subprocesswins: it returns the exit code and output programmatically, raises exceptions on failure (check=True), and the list form avoids shell injection. Passshell=Trueonly when you genuinely need shell syntax (pipes, globs) and the input is trusted.What is
jqin Linux?jqis a command-line JSON processor — it parses, filters, and transforms JSON the waysed/awkhandle text:bashIt's essential in DevOps because cloud CLIs and APIs emit JSON: extracting instance IDs, parsing GitHub API responses, or pulling a value out of a Terraform output. Flag worth knowing:
-rprints raw strings (without surrounding quotes), and-esets the exit code based on the result — handy for scripting conditions.How do you exit a script with a status code?
bashEvery command finishes with a status code: 0 means success, 1–255 mean failure, and
$?holds the previous command's code. Conventions to mention:1is a general failure,2is often CLI misuse, and custom codes (e.g., 3, 4...) let the caller distinguish failure reasons. CI/CD pipelines and wrappers decide success purely by this code — a script that "fails loudly" but exits 0 will silently pass a pipeline.