Let's face it: the most tedious part of DevOps isn't the 'ops'—it's the repetitive, copy-paste work that eats your day. Writing yet another Dockerfile, debugging a flaky pipeline, or spelunking through a 10,000-line log file. But what if you could offload that grunt work to an AI assistant? Not by writing code for you, but by giving you a head start, a second opinion, or a full solution you can review and refine. That's the promise of prompt engineering for DevOps.
This isn't about replacing your expertise. It's about augmenting it. Think of a well-crafted prompt as a pair of smart hands that never sleep: it generates a first draft, points out blind spots, and explains complex outputs. Below, I've curated 15 battle-tested prompts, organized from basic to expert, each with a real-world example and the reasoning behind it. Use them as templates, adapt them to your stack, and watch your toil melt away.
Getting Started: The Art of the DevOps Prompt
Before we dive into the prompts, let's establish a mental model. A great prompt for infrastructure tasks includes:
- Context: The technology stack, constraints, and environment.
- Task: A clear, specific request.
- Format: The desired output structure (e.g., YAML, table, step-by-step).
- Constraints: Any hard requirements (e.g., 'use official images only', 'must pass
docker scan').
Think of it as writing a ticket for a brilliant but inexperienced intern. The more context you provide, the better the result.
Basic Prompts: Daily Bread-and-Butter Tasks
These prompts handle routine chores, giving you a solid foundation to build upon.
1. Generating a Production-Ready Dockerfile
Task: Create a Dockerfile for a Node.js application with multi-stage build, non-root user, and health check.
Prompt:
Create a multi-stage Dockerfile for a Node.js 20 application. The app uses npm and has a 'build' script. Requirements: use official images, install only production dependencies in the final stage, run as a non-root user, include a HEALTHCHECK that curls the /health endpoint, and use the 'slim' variant for the final image. Provide a brief explanation of each stage.
Example Output (Snippet):
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM node:20-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/package*.json ./
RUN npm install --only=production && \
addgroup -g 1001 nodejs && \
adduser -S nodejs -u 1001
COPY --from=builder /app/dist ./dist
USER nodejs
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --retries=3 CMD wget -qO- http://localhost:3000/health || exit 1
CMD ["node", "dist/index.js"]
Why it works: The prompt specifies the base image, package manager, build process, security constraints (non-root), and health check. The AI fills in the blanks, producing a compliant Dockerfile. Always review the output—AI might miss edge cases, but it saves you from the blank page.
2. Creating a docker-compose.yml for Local Development
Task: Generate a docker-compose file for a microservices app (frontend, backend, database).
Prompt:
Write a docker-compose.yml for local development. Services: 'frontend' (React, port 3000), 'backend' (Node.js/Express, port 5000, depends on db), and 'db' (PostgreSQL 16). Use named volumes for db data, set environment variables for db credentials (POSTGRES_USER=dev, POSTGRES_PASSWORD=dev, POSTGRES_DB=app_db), and add a healthcheck for db. Include a comment on how to run it.
Example Output (Snippet):
version: '3.8'
services:
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: dev
POSTGRES_PASSWORD: dev
POSTGRES_DB: app_db
volumes:
- db_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U dev"]
interval: 10s
timeout: 5s
retries: 5
backend:
build: ./backend
ports:
- "5000:5000"
depends_on:
db:
condition: service_healthy
frontend:
build: ./frontend
ports:
- "3000:3000"
volumes:
db_data:
Why it works: The prompt defines the services, ports, dependencies, and even the volume. The AI handles the YAML structure, and you get a working local environment in seconds.
3. Writing a Bash Script to Clean Up Old Docker Artifacts
Task: Create a script to remove dangling images and stopped containers.
Prompt:
Write a bash script that prunes Docker resources safely. It should: 1) remove all stopped containers older than 24 hours, 2) remove dangling images, 3) remove unused volumes, and 4) log the freed space. Use `docker container prune`, `docker image prune`, and `docker volume prune` with appropriate flags. Add error handling and a dry-run option.
Example Output (Snippet):
#!/bin/bash
set -euo pipefail
DRY_RUN=${DRY_RUN:-false}
docker container prune -f --filter "until=24h" || true
docker image prune -f
docker volume prune -f
echo "Docker cleanup completed."
Why it works: The prompt specifies the exact commands and filters, ensuring the script is safe and effective. The AI adds error handling and a dry-run flag, which is a best practice.
4. Extracting and Summarizing Errors from Logs
Task: Parse a log file and identify the root cause of a failure.
Prompt:
Here is a snippet from our application logs. Identify the most likely root cause of the error, categorize it (e.g., network, database, code bug), and suggest a fix. Also explain any stack traces in plain English.
[Paste log here]
Example Output:
The error is a ECONNREFUSED on port 5432, indicating the application cannot connect to PostgreSQL. This is likely because the database service is not running or the connection string is misconfigured. Check the DATABASE_URL environment variable and ensure the db service is healthy. The stack trace shows the connection attempt in pg library.
Why it works: You provide the log, and the AI acts as a junior SRE, offering a diagnosis and actionable next steps. It's like having a rubber duck that actually knows something.
Advanced Prompts: Streamlining Complex Workflows
These prompts tackle more complex tasks, requiring a deeper understanding of the infrastructure.
5. Generating a Terraform Module for an AWS EC2 Instance
Task: Create a reusable Terraform module for an EC2 instance with security group, IAM role, and tags.
Prompt:
Create a Terraform module named 'ec2_instance' that provisions an AWS EC2 instance. Inputs: instance_type (default 't3.micro'), ami, subnet_id, security_group_ids (list), and tags (map). Outputs: instance_id, public_ip. Include a security group resource that allows SSH from a variable 'allowed_ip' (default '0.0.0.0/0' as a placeholder) and an IAM role with an S3 read-only policy. Use Terraform 1.5+. Provide usage example.
Example Output (Snippet):
# modules/ec2_instance/main.tf
variable "instance_type" {
default = "t3.micro"
}
# ... (other variables)
resource "aws_instance" "this" {
ami = var.ami
instance_type = var.instance_type
subnet_id = var.subnet_id
vpc_security_group_ids = var.security_group_ids
tags = var.tags
}
resource "aws_security_group" "ssh" {
name_prefix = "ssh-"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = [var.allowed_ip]
}
}
# ... (outputs, IAM)
Why it works: The prompt defines the module's interface (variables, outputs) and resources. The AI generates a structured module that you can drop into your infrastructure codebase.
6. Optimizing a GitHub Actions CI/CD Pipeline
Task: Improve a slow CI pipeline by adding caching and parallel jobs.
Prompt:
Here is my current GitHub Actions workflow for a Node.js app. It takes 15 minutes. Suggest optimizations: add caching for npm dependencies, split jobs into parallel lint/test/build, and use a faster runner if possible. Provide the updated YAML.
[Paste current workflow]
Example Output (Snippet):
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm run lint
test:
runs-on: ubuntu-latest
needs: lint
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test
build:
runs-on: ubuntu-latest
needs: test
steps:
- run: npm run build
Why it works: The AI identifies that caching and parallelization can drastically reduce build time. It outputs a complete workflow, which you can refine.
7. Writing a Kubernetes Manifest with Best Practices
Task: Generate a Deployment and Service for a web app with resource limits, probes, and a ConfigMap.
Prompt:
Create a Kubernetes manifest for a simple web app 'myapp' using nginx:alpine. Include: a Deployment with 3 replicas, resource requests/limits (cpu: 100m/500m, memory: 128Mi/256Mi), livenessProbe (HTTP GET /), readinessProbe (HTTP GET /), a Service of type ClusterIP exposing port 80, and a ConfigMap with a custom nginx.conf that enables gzip. Use apiVersion apps/v1. Provide the YAML and a short explanation.
Example Output (Snippet):
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
replicas: 3
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: nginx
image: nginx:alpine
ports:
- containerPort: 80
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
livenessProbe:
httpGet:
path: /
port: 80
readinessProbe:
httpGet:
path: /
port: 80
volumeMounts:
- name: config
mountPath: /etc/nginx/conf.d
volumes:
- name: config
configMap:
name: myapp-config
---
apiVersion: v1
kind: ConfigMap
metadata:
name: myapp-config
data:
default.conf: |
server {
listen 80;
gzip on;
location / {
root /usr/share/nginx/html;
}
}
Why it works: The prompt specifies the image, probes, resources, and ConfigMap. The AI produces a manifest that follows Kubernetes best practices, saving you from syntax errors.
8. Explaining a Complex kubectl Command or jq Query
Task: Understand what a complex command does before running it.
Prompt:
Explain the following command in detail, breaking down each part:
kubectl get pods -A -o json
| jq -r '.items[] | select(.status.phase == "Running") | .metadata.namespace + " " + .metadata.name'
Example Output:
This command lists all running pods across all namespaces. kubectl get pods -A -o json fetches pod info in JSON. The jq filter selects items where .status.phase is "Running", then prints the namespace and name. It's useful for auditing running workloads.
Why it works: Instead of blindly executing, you learn what the command does. This is especially valuable for complex jq filters.
Expert Prompts: Tackling Infrastructure at Scale
These prompts push the boundaries, leveraging AI for design, analysis, and incident response.
9. Designing a Multi-Cloud Disaster Recovery Strategy
Task: Create a high-level DR plan for a multi-cloud setup.
Prompt:
Design a disaster recovery strategy for a web application that is deployed on AWS (primary) and Azure (secondary). The app uses a PostgreSQL database. Describe the architecture, including failover mechanisms, data replication, and RPO/RTO targets. Consider using AWS Route 53 for DNS failover and Azure SQL Database as a geo-replica. Provide a step-by-step plan for failover and failback.
Example Output (Snippet):
The recommended approach is an active-passive setup with a warm standby. On AWS, run the production stack in us-east-1. Replicate the PostgreSQL database to Azure using Azure Database for PostgreSQL with geo-redundant backup. Use Route 53 with health checks to automatically failover DNS to Azure in case of an AWS outage. RPO: 5 minutes (via WAL shipping), RTO: 30 minutes. Failover steps: 1) Update DNS, 2) Promote Azure database, 3) Scale up resources...
Why it works: The prompt defines the scope, cloud providers, and key metrics. The AI provides a comprehensive strategy, which you can validate with your team.
10. Analyzing Performance Bottlenecks from top, vmstat, and iostat Output
Task: Diagnose a CPU spike on a Linux server.
Prompt:
Here is output from `top`, `vmstat`, and `iostat` taken during a CPU spike. Analyze the data and identify the likely bottleneck (CPU, memory, disk I/O). Suggest further diagnostic commands and possible fixes.
[Paste outputs]
Example Output:
The vmstat shows high wa (I/O wait) and iostat indicates heavy writes to /dev/sda1. This suggests disk I/O is the bottleneck. Check for excessive logging or swap usage. Consider moving to an SSD or tuning the application's write patterns. Use iotop to identify the process causing the I/O.
Why it works: You provide raw data, and the AI acts as a performance analyst, interpreting the numbers and guiding your next steps.
11. Writing a PromQL Query for a Complex SLO Alert
Task: Create a Prometheus alert for high error rate on a service, excluding a specific path.
Prompt:
Write a PromQL query that calculates the error rate (HTTP 5xx) for the service 'api', excluding requests to '/health'. Alert if the error rate exceeds 5% for 10 minutes. Provide the full alerting rule in YAML format.
Example Output (Snippet):
groups:
- name: api_errors
rules:
- alert: ApiHighErrorRate
expr: |
(
sum(rate(http_requests_total{service="api", status=~"5.."}[5m])) by (job)
/
sum(rate(http_requests_total{service="api"}[5m])) by (job)
) * 100 > 5
for: 10m
labels:
severity: page
annotations:
summary: "API error rate is high"
Why it works: The prompt specifies the service, status codes, and threshold. The AI generates a PromQL expression and alert rule, which you can tweak.
12. Generating an OpenAPI Specification from a Codebase
Task: Extract an API spec from existing code.
Prompt:
Here is a JavaScript file with Express routes. Generate an OpenAPI 3.0 specification for the endpoints defined. Include request/response schemas based on the code. Output in YAML.
[Paste code]
Example Output (Snippet):
openapi: 3.0.0
info:
title: My API
version: 1.0.0
paths:
/users:
get:
responses:
'200':
description: OK
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: integer
name:
type: string
Why it works: The AI parses the code and generates a spec, saving you from manual documentation. It's not perfect, but it's a great starting point.
13. Building a ChatOps Bot with Slack and AI
Task: Create a voice assistant for DevOps tasks.
Prompt:
Design a ChatOps bot for Slack that can: 1) check deployment status, 2) trigger a deployment, 3) fetch logs, and 4) scale a service. Describe the architecture, including the Slack API, a webhook server, and integration with Kubernetes. Provide a sample slash command handler in Python.
Example Output (Snippet):
Use Slack Slash Commands to trigger a webhook. The server (e.g., Flask) handles the command, authenticates with Kubernetes using kubeconfig, and returns the result to Slack. Sample code: @app.route('/deploy', methods=['POST']) ...
Why it works: This prompt generates a blueprint for a powerful automation tool. The AI provides the architecture and starter code, which you can expand.
14. Generating Configuration for ArgoCD ApplicationSet
Task: Create a Kubernetes ApplicationSet for multi-environment deployments.
Prompt:
Write an ArgoCD ApplicationSet manifest that deploys an app 'myapp' to dev, staging, and prod clusters. Use a list generator, different values per environment (e.g., replicas, image tag), and a common base. Provide the YAML.
Example Output (Snippet):
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
name: myapp
spec:
generators:
- list:
elements:
- cluster: dev
replicas: 1
imageTag: latest
- cluster: staging
replicas: 2
imageTag: staging
- cluster: prod
replicas: 3
imageTag: stable
template:
metadata:
name: '{{cluster}}-myapp'
spec:
project: default
source:
repoURL: https://github.com/example/myapp.git
targetRevision: HEAD
path: manifests
helm:
parameters:
- name: replicas
value: '{{replicas}}'
- name: imageTag
value: '{{imageTag}}'
destination:
server: 'https://kubernetes.default.svc'
namespace: myapp
Why it works: The prompt specifies the generator and values, and the AI produces a GitOps-ready ApplicationSet.
15. Simulating a Chaos Engineering Experiment
Task: Plan a chaos experiment to test resilience.
Prompt:
Design a chaos engineering experiment for a Kubernetes cluster. The hypothesis: the application should survive a single pod failure without downtime. Describe the experiment, including the steady-state hypothesis, blast radius, and rollback plan. Provide a step-by-step procedure using `kubectl` to kill a pod and measure the impact.
Example Output (Snippet):
Steady-state: the app returns HTTP 200. Blast radius: one deployment. Experiment: 1) identify a pod, 2) kubectl delete pod <pod>, 3) monitor the error rate, 4) verify the deployment recovers. Rollback: if error rate spikes, restart the deployment.
Why it works: The AI helps you structure a safe experiment, following principles from Chaos Engineering.
Putting It All Together: Your Prompt Library
You've seen 15 prompts that span the DevOps spectrum. But the real power comes from customizing them to your environment.
Start by building a personal library, saving your best prompts in a file or a tool like a Notion database. Include context about your stack, so you can reuse them with minor tweaks.
Remember, AI is a collaborator, not a magician. It works best when you provide clear, specific instructions. The more you practice, the better your results.
So, what's your next move? Pick one repetitive task you do every week, craft a prompt for it, and see how much time you save. Then, iterate. The future of DevOps is not manual scripting—it's intelligent automation, and you're just getting started.
Comments