📜 Bash and Python Scripts

Produce in a few minutes robust automation scripts (deployments, backups, monitoring) that would take 1-2 hours to write from scratch.

DevOps engineers write on average several scripts per week to automate recurring tasks: deployments, backups, log rotations, health checks. AI allows producing in 5-15 minutes what took 1-2 hours, with quality error handling and portability. The pitfall: generated scripts can be too permissive (risky rm -rf, missing error handling) or simply incorrect for edge cases. This guide presents the rigorous workflow that combines rapid generation and systematic verification.

Step-by-step Workflow
1
Describe the execution context

Before coding: target OS (bash on Linux? PowerShell on Windows? cross-platform?), Python version (3.11, 3.12), environment (CI/CD, cron, lambda, kubernetes job), available permissions. Without context, AI makes assumptions that can break things.

2
Specify critical invariants

Idempotence? Atomicity? Rollback? Structured logs? Notifications? These invariants must be explicit in the prompt. They distinguish a script that works from a production-ready script.

3
Generate with robust error handling

Explicitly ask: `set -euo pipefail` in bash, try/except with logging in Python, clear return codes, actionable error messages. AI naturally produces happy-path code — you must force robustness.

4
Test in dry-run mode

Before actual execution: run the script in dry-run or on a staging environment. Verify paths, permissions, dependencies, behavior on edge cases (missing file, full disk, network down).

5
Version and document

Commit to the infra repo with: usage comment at the top, invocation example, documented parameters. AI can also auto-generate Markdown documentation from the script.

Copyable Prompts
Robust backup script
You are a senior DevOps engineer. Generate a [BASH/PYTHON] script that:nn**Goal**: back up [WHAT: DB / volumes / files] to [DESTINATION: S3, NAS, etc.]nn**Constraints**:n- Environment: [LINUX/UBUNTU/ALPINE]n- Idempotent: multiple executions without corruptionn- Rotation: keep N backups, delete the oldestnesn- Compression: gzip/zstd based on compression ratio/CPUn- Logs: structured (JSON or clear format) with timestampsn- Notifications: Slack webhook or email on failuren- Return code: 0 if OK, different codes by error typen- `set -euo pipefail` or strictest equivalentnnProvide:n1. The complete, commented scriptn2. Required environment variables (with `.env.example`)n3. Typical invocation command (cron, systemd timer)n4. Tests to run before production
Blue/Green deployment script
Generate a Blue/Green deployment script for this application:nn**Stack**: [DESCRIPTION — e.g., Node.js app on ECS / Kubernetes / VM]n**Target**: [ENVIRONMENT]n**Source**: registry [DOCKER HUB / ECR / GHCR]nnThe script must:n1. Identify the current active versionen2. Deploy new version on the inactive environmentn3. Run smoke test on the new deploymentn4. If OK: switch trafflcn5. If KO: automatic rollbackn6. Log each step with timestampsn7. Notify Slack at each transitionnnAlso provide the runbook: what to do if smoke test fails, how to manually rollback if script crashes, who to notify.
Python CSV/JSON analysis script
Generate a Python script that:nn**Input**: [CSV/JSON] file with these columns: [LIST]n**Processing**: [DESCRIBE — e.g., aggregate by month, calculate percentiles, detect outliers]n**Output**: [FORMAT — CSV, JSON, Excel, chart]nnConstraints:n- Python 3.11+ with pandas/numpyn- Handle large files (chunking if >100MB)n- Input data validation (types, aberrant values)n- Logging via `logging` (not print)n- Argparse for parameters (input, output, options)n- Code structured in testable functionsn- Full docstringsnnAlso provide: `requirements.txt`, usage example, and 3 test cases to run.
Script conversion to another stack
Convert this script:nn[ORIGINAL SCRIPT]nnTo [TARGET LANGUAGE/STACK — e.g., Bash → Python, or Python → Go for performance].nnMaintain:n- Same functional behaviorn- Same error handling (or better if possible)n- Same log formatn- Same parameters and return codesnnProvide:n1. The converted scriptn2. Notable differences (what changes in behavior, why)n3. Improvements made (performance, readability, security)n4. Non-regression tests to run
Recommended tools
Claude Code
★ 4.9 (92) · 20 USD/mois

Assistant de développement IA agentique par Anthropic : comprend votre codebase, édite des fichiers, exécute des commandes et s'intègre à votre environnement de développement.

Why : Le meilleur pour le scripting avec accès au contexte de votre repo. Gère bien les invariants production (idempotence, gestion d'erreurs).

🤖
Cursor
★ 4.8 (145) · 20 USD/mois

Éditeur de code IA révolutionnaire basé sur VS Code avec agents autonomes

Why : L'IDE permet de générer et tester rapidement, avec accès aux fichiers du repo en contexte. Idéal pour itérer.

Claude Opus 4.5
★ 4.9 (92) · 20 USD/mois

Claude Opus 4.5 : modèle premium d’Anthropic pour code, agents et tâches complexes en entreprise.

Why : Pour les scripts complexes avec logique multi-étapes, reasoning supérieur. Hallucinations limitées sur les flags et options de commandes.

Estimated ROI
Time Saved
70-80% on standard scripts (10-15 min vs 1-2h)
Quality Gain
Systematic error handling and idempotence, auto-generated doc
Cost
20-30€/month for Claude Code or Cursor Pro
Frequently asked questions
Is the generated script production-ready?

Not as-is in 90% of cases. Common pitfalls: too-permissive permissions, incomplete error handling, hardcoded paths, secrets in plain text. Always audit before prod: `shellcheck` for bash, `bandit` or `pylint` for Python, and a human for business logic.

Can you generate Terraform or Ansible with AI?

Yes, and it's an excellent use case. But: always validate with `terraform plan` or `ansible-playbook –check`, scan with `tfsec` or `checkov`, and audit generated IAM permissions (AI is often overly permissive by default).

How to manage secrets in AI-generated scripts?

Golden rule: never put secrets in the prompt. The script must load them from the environment (env vars, AWS Secrets Manager, Vault, etc.). If AI suggests hardcoded: always replace before use.

Does AI handle edge cases well in scripting?

Less well than happy-path. Commonly forgotten cases: missing file, full disk, network timeout, permission denied, process killed mid-execution. Explicitly ask AI to cover these cases, and test each scenario pre-prod.

← Back to guide DevOps / SRE