17 Prompts for Security and DevSecOps: Audit, Scanning, Policies

17 Prompts for Security and DevSecOps: Audit, Scanning, Policies

Introduction

Security is no longer an afterthought—it's baked into every stage of the software delivery lifecycle. As a DevSecOps practitioner, you constantly juggle threat models, compliance checklists, SAST/DAST configurations, and access policies. But what if you could offload the boilerplate work to an AI assistant? The right prompt can turn a large language model (LLM) into a junior security engineer, generating Infrastructure as Code policies, secret scanning rules, or audit report templates in seconds.

This collection of 17 prompts is organized from Basic (everyday security chores) through Advanced (CI/CD integration and compliance) to Expert (custom rule creation and threat modeling). Each prompt includes a concrete task, the exact wording you can copy, and a realistic output example. By the end, you'll have a toolkit you can drop directly into your DevSecOps pipeline.


Basic Prompts (Everyday Security Tasks)

1. Generate a SAST Configuration for Python

Task: Create a Semgrep or Bandit configuration for a Python Django application to detect SQL injection, XSS, and hardcoded secrets.
Prompt:

You are a DevSecOps engineer. Generate a Bandit configuration file (bandit.yaml) for a Python Django project. The configuration should detect:  
- SQL injection (bandit.B608)  
- Cross-site scripting (bandit.B703)  
- Hardcoded password/secret (bandit.B105)  
- Use of eval() (bandit.B307)  
Include a custom plugin path and exclude the tests/ directory. Explain each rule with a one-line comment.  

Example Result:

# bandit.yaml  
skips: ['B101']  # skip assert statements for test files  
tests:  
  - B608      # SQL injection via string formatting  
  - B703      # XSS via mark_safe  
  - B105      # hardcoded password  
  - B307      # use of eval  
exclude_dirs:  
  - ./tests/  
  - ./venv/  
plugins:  
  - /path/to/custom/plugin  

2. Write an S3 Bucket Policy for Least Privilege

Task: Craft an AWS S3 bucket policy that allows read‑only access for a specific IAM role and denies public access.
Prompt:

Write an AWS S3 bucket policy that:  
1. Grants read (s3:GetObject) to the IAM role `arn:aws:iam::123456789012:role/app-reader`.  
2. Denies public access (Principal wildcard) to all actions.  
3. Enforces TLS (condition aws:SecureTransport = true).  
Use the official IAM policy language. Explain each statement.  

Example Result:

{  
  "Version": "2012-10-17",  
  "Statement": [  
    {  
      "Effect": "Allow",  
      "Principal": {  
        "AWS": "arn:aws:iam::123456789012:role/app-reader"  
      },  
      "Action": "s3:GetObject",  
      "Resource": "arn:aws:s3:::my-bucket/*",  
      "Condition": {  
        "Bool": {  
          "aws:SecureTransport": "true"  
        }  
      }  
    },  
    {  
      "Effect": "Deny",  
      "Principal": "*",  
      "Action": "s3:*",  
      "Resource": [  
        "arn:aws:s3:::my-bucket",  
        "arn:aws:s3:::my-bucket/*"  
      ]  
    }  
  ]  
}  

3. Create an Nginx Security Headers Config

Task: Generate an Nginx snippet that adds OWASP‑recommended security headers.
Prompt:

Generate an Nginx configuration snippet that adds the following security headers:  
- Content-Security-Policy (restrict to same-origin)  
- X-Frame-Options (DENY)  
- X-Content-Type-Options (nosniff)  
- Strict-Transport-Security (max-age=63072000; includeSubDomains)  
- Referrer-Policy (strict-origin-when-cross-origin)  
Explain why each header is necessary and provide a sample location block.  

Example Result:

add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'" always;  
add_header X-Frame-Options DENY always;  
add_header X-Content-Type-Options nosniff always;  
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;  
add_header Referrer-Policy strict-origin-when-cross-origin always;  

4. Build a Simple Secret Scanner (CLI Version)

Task: Write a Bash script using grep and truffleHog to scan a Git repository for secrets.
Prompt:

Write a Bash script that:  
1. Clones a Git repository into a temporary directory.  
2. Runs truffleHog (v3) on the entire history with entropy detection.  
3. Outputs results to a JSON file and sends an alert if any high‑confidence secrets are found.  
Assume truffleHog is installed. Include error handling.  

Example Result:

#!/bin/bash  
set -e  
REPO_URL=$1  
TMP_DIR=$(mktemp -d)  
git clone --depth=100 "$REPO_URL" "$TMP_DIR"  
trufflehog git --json "$TMP_DIR" > results.json  
if jq -e '.[] | select(.confidence=="high")' results.json > /dev/null; then  
  echo "ALERT: High-confidence secrets found!"  
  # Send to Slack or webhook  
fi  
rm -rf "$TMP_DIR"  

5. Write a Dockerfile with Security Best Practices

Task: Generate a Dockerfile for a Node.js app that avoids running as root, uses multi‑stage builds, and scans dependencies.
Prompt:

Create a production Dockerfile for a Node.js Express application. Include:  
- Node 20 Alpine base image  
- Multi‑stage build: install dependencies in builder, copy only runtime in final  
- Run as non‑root user (uid 1001)  
- Add Dockerfile linting comment (hadolint)  
- Add vulnerability scanning step using `npm audit --audit-level=high`  
Provide comments for each best practice.  

Example Result:

# hadolint global ignore=DL3006  
FROM node:20-alpine AS builder  
WORKDIR /app  
COPY package*.json ./  
RUN npm ci --only=production && npm audit --audit-level=high  

FROM node:20-alpine  
RUN addgroup -g 1001 app && adduser -u 1001 -G app -s /bin/sh -D app  
COPY --from=builder /app /app  
USER app  
EXPOSE 3000  
CMD ["node", "index.js"]  

6. Generate a Kubernetes Network Policy

Task: Write a Kubernetes NetworkPolicy that allows ingress only from a specific namespace and denies all egress except DNS.
Prompt:

Create a Kubernetes NetworkPolicy for a namespace called 'payment'. The policy should:  
- Allow ingress from namespace 'frontend' with pod selector 'app: web'.  
- Deny all other ingress.  
- Allow egress to port 53 (DNS) on UDP.  
- Deny all other egress.  
Use networking.k8s.io/v1.  

Example Result:

apiVersion: networking.k8s.io/v1  
kind: NetworkPolicy  
metadata:  
  name: payment-network-policy  
  namespace: payment  
spec:  
  podSelector: {}  
  policyTypes:  
  - Ingress  
  - Egress  
  ingress:  
  - from:  
    - namespaceSelector:  
        matchLabels:  
          kubernetes.io/metadata.name: frontend  
    - podSelector:  
        matchLabels:  
          app: web  
  egress:  
  - to:  
    ports:  
    - protocol: UDP  
      port: 53  

Advanced Prompts (CI/CD & Compliance)

7. Create a GitHub Actions Workflow for SAST + Secret Scan

Task: Write a CI workflow that runs Semgrep and Gitleaks on every pull request.
Prompt:

Create a GitHub Actions workflow that:  
1. Triggers on pull_request to main.  
2. Runs Semgrep using the p/default ruleset.  
3. Runs Gitleaks to detect secrets.  
4. Fails the build if any critical issues are found.  
5. Uploads SARIF reports to GitHub Code Scanning.  
Use official actions; include example comments.  

Example Result:

name: Security Scan  
on:  
  pull_request:  
    branches: [main]  
jobs:  
  security:  
    runs-on: ubuntu-latest  
    steps:  
      - uses: actions/checkout@v4  
      - name: Run Semgrep  
        uses: returntocorp/semgrep-action@v9  
        with:  
          config: p/default  
          generateSarif: true  
      - name: Run Gitleaks  
        uses: zricethezav/gitleaks-action@v2  
      - name: Upload SARIF  
        uses: github/codeql-action/upload-sarif@v3  
        with:  
          sarif_file: results.sarif  

8. Automate CIS Benchmark Auditing with Ansible

Task: Write an Ansible playbook that checks a Linux host against CIS Level 1 benchmarks.
Prompt:

Generate an Ansible playbook that runs common CIS Benchmark checks (e.g.,  
- Ensure /tmp is mounted with noexec (1.1.2)  
- Ensure permissions on /etc/shadow are 640 (6.1.3)  
- Ensure SSH Protocol is 2 (5.2.1)  
Output a report in JSON format. Use the ansible.builtin modules.  

Example Result:

---  
- name: CIS Level 1 Audit  
  hosts: all  
  become: yes  
  tasks:  
    - name: Check /tmp mount options  
      ansible.builtin.shell: mount | grep ' /tmp '  
      register: tmp_mount  
    - name: Assert noexec  
      ansible.builtin.assert:  
        that: "'noexec' in tmp_mount.stdout"  
        fail_msg: "CIS 1.1.2 failed"  
    - name: Check /etc/shadow permissions  
      ansible.builtin.stat:  
        path: /etc/shadow  
      register: shadow_stat  
    - name: Assert permissions  
      ansible.builtin.assert:  
        that: shadow_stat.stat.mode == '0640'  
        fail_msg: "CIS 6.1.3 failed"  

9. Write a Terraform Plan to Spot Public S3 Buckets

Task: Craft a Rego policy (OPA) that prevents Terraform from creating public S3 buckets.
Prompt:

Write a Rego policy for Open Policy Agent that denies any Terraform resource of type aws_s3_bucket if the public_access_block_configuration is not set to block all public access. The policy should be used with terraform plan. Include a test case.  

Example Result:

package terraform  

deny[msg] {  
  resource := input.resource_changes[_]  
  resource.type == "aws_s3_bucket"  
  not resource.change.after.public_access_block_configuration  
  msg = sprintf("Bucket %v must have public access block", [resource.change.after.bucket])  
}  

10. Generate an Incident Response Playbook

Task: Produce a step‑by‑step IR playbook for a suspected data breach.
Prompt:

You are a SOC lead. Write an incident response playbook for a data exfiltration discovery. Include:  
1. Triage checklist  
2. Containment steps (isolate host, revoke keys)  
3. Evidence collection commands (Linux, Windows)  
4. Communication template for stakeholders  
Base it on NIST SP 800‑61 Rev 2. Provide a sample timeline.  

Example Result:

## IR Playbook: Data Exfiltration  
### Triage  
- Verify alert from DLP or SIEM  
- Check if large outbound data transfer occurred > 5 GB  
### Containment  
- Disable user account in IdP  
- Block source IP in WAF  
- Isolate host via network ACL  
### Collection  
- Linux: `lsof -i`, `journalctl -u sshd`, `find / -ctime -1 -type f`  
### Communication  
- Email to CISO: "Subject: Incident #123 - Data Exfiltration - Action Required"  

11. Draft a Kubernetes Pod Security Admission Policy

Task: Create a Pod Security Admission configuration to enforce baseline/restricted profiles.
Prompt:

Write a Kubernetes PSA (Pod Security Admission) configuration for a namespace called 'production' that enforces the 'restricted' profile with an audit warning. Use the v1.25+ API. Explain how to apply it with a label.  

Example Result:

apiVersion: v1  
kind: Namespace  
metadata:  
  name: production  
  labels:  
    pod-security.kubernetes.io/enforce: restricted  
    pod-security.kubernetes.io/audit: restricted  
    pod-security.kubernetes.io/warn: restricted  

Expert Prompts (Threat Modeling & Custom Rules)

12. Build a Threat Model Using STRIDE

Task: Use an AI to generate a STRIDE threat model for a payment microservice.
Prompt:

You are a threat modeling lead. Using the STRIDE methodology, analyze a payment microservice architecture that includes:  
- User → API Gateway → Payment Service → Database  
- Integration with Stripe API  
- JWT authentication  
List potential threats per category (Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege). For each threat, propose a mitigation.  

Example Result:

STRIDE Category Threat Mitigation
Spoofing Attacker forges JWT token Verify signature, use short expiration
Tampering Manipulate payment amount in transit TLS + signature on payload

13. Write a Custom Semgrep Rule for Python (Banned Import)

Task: Create a Semgrep rule that catches imports of pickle or marshal in Python code.
Prompt:

Write a Semgrep rule (YAML) that flags any occurrence of `import pickle` or `import marshal`.  
- Pattern: direct import or `from X import Y`  
- Severity: ERROR  
- Message: "Avoid pickle/marshal – use JSON ormsgpack for untrusted data"  
Include a test snippet that fails the rule.  

Example Result:

rules:  
- id: banned-import-pickle  
  pattern-either:  
  - pattern: import pickle  
  - pattern: import marshal  
  - pattern: from pickle import ...  
  - pattern: from marshal import ...  
  message: "Avoid pickle/marshal – use JSON or msgpack for untrusted data"  
  severity: ERROR  
  languages: [python]  

14. Automate Compliance Report Generation (SOC 2)

Task: Generate a script that collects evidence for SOC 2 criteria.
Prompt:

Write a Python script that connects to AWS, GCP, and Azure APIs to gather evidence for SOC 2 control CC6.1 (Logical and Physical Access Controls). It should:  
- List IAM users and roles (AWS)  
- List Cloud IAM policy bindings (GCP)  
- List Azure role assignments  
- Export to a CSV with timestamps  
Use boto3, google-cloud-resource-manager, and azure-identity.  

Example Result:

import boto3  
import csv  
# ... other imports  
def gather_aws_iam():  
    iam = boto3.client('iam')  
    users = iam.list_users()['Users']  
    return [(u['UserName'], u['CreateDate']) for u in users]  
# ...  
with open('soc2_cc6_evidence.csv', 'w') as f:  
    writer = csv.writer(f)  
    writer.writerow(['Provider', 'Identity', 'Created'])  
    for name, date in gather_aws_iam():  
        writer.writerow(['AWS', name, date])  

15. Design a Zero Trust Network Architecture Description

Task: Use the AI to help draft a zero‑trust design document for a multi‑cloud environment.
Prompt:

Write an architecture description for a zero-trust network using Google BeyondCorp principles. Include:  
- Micro‑segmentation between workloads  
- Identity‑aware proxy (IAP) for access  
- No VPN; use TLS with mTLS  
- Continuous verification with logs from SIEM  
Structure as a section for a technical RFC.  

Example Result:

## Zero Trust Architecture  
### Principles  
- Every access request authenticated and authorized.  
- **Micro‑segmentation**: Kubernetes NetworkPolicies per service.  
- **IAP**: Cloud IAP for SSH/HTTPS, gRPC with SPIFFE.  
- **Logging**: All flow logs sent to SIEM; alerts on anomalous auth.  

16. Generate a Dependency Confusion Prevention Script

Task: Write a pipeline script that checks for potential dependency confusion vulnerabilities.
Prompt:

Create a Bash script for a CI pipeline that:  
1. Extracts package names from package.json (npm) or requirements.txt (pip).  
2. Queries public registries (npm, PyPI) to see if a private package name is publicly available.  
3. Flags any matches as high severity.  
Use `jq` and `curl`. Handle private scoped packages (@org/name).  

Example Result:

#!/bin/bash  
for pkg in $(jq -r '.dependencies | keys[]' package.json); do  
  if [[ $pkg == @* ]]; then  
    if npm view "$pkg" version > /dev/null 2>&1; then  
      echo "WARNING: Dependency confusion risk for $pkg"  
    fi  
  fi  
done  

17. Create a Kubernetes Admission Webhook for Image Signing Verification

Task: Write a mutating webhook that verifies container image signatures using Cosign before allowing a pod creation.
Prompt:

Generate a Kubernetes ValidatingAdmissionPolicy (or webhook configuration) that uses Cosign to verify that each pod's container image is signed with a trusted public key. Provide a sample Cosign verification command and explain how to integrate with OPA/Gatekeeper.  

Example Result:

apiVersion: admissionregistration.k8s.io/v1  
kind: ValidatingWebhookConfiguration  
metadata:  
  name: cosign-verifier  
webhooks:  
- name: cosign.example.com  
  rules:  
  - operations: ["CREATE"]  
    apiGroups: [""]  
    apiVersions: ["v1"]  
    resources: ["pods"]  
  clientConfig:  
    service:  
      name: cosign-verifier  
      namespace: gatekeeper-system  
      path: /verify  
    caBundle: <base64-ca>  
  admissionReviewVersions: ["v1"]  

Conclusion

Security automation doesn't have to be heavy‑lifted from scratch. By using these 17 prompts, you can instantly generate hardened configurations, audit scripts, policy as code, and even complex threat models. The examples are battle‑tested—they reference OWASP, CIS, NIST, and industry‑standard tools (Semgrep, Gitleaks, OPA, Cosign).

Your next step: pick one prompt that matches a current gap in your pipeline, run it with an LLM of your choice (GPT‑4, Claude, or a local model), and adapt the output to your environment. Then commit it to your repository. Security, after all, is code too.

Stay safe and keep shifting left.

← All posts

Comments