20 DevOps Scripts for Infrastructure Automation

20 infrastructure automation scripts: Terraform state bootstrap, drift checks, Packer, Ansible patching, AWS security audits, EKS and Helm, with code.

Dec 29, 2025 - 18:00
Nov 9, 2026 - 18:21
 0  100
20 DevOps Scripts for Infrastructure Automation

Infrastructure automation scripts handle the jobs around your IaC tools: bootstrapping Terraform state, checking for drift, building images, auditing security groups, tags, keys and public buckets, preparing clusters and running safe changes. The 20 scripts below use Bash, the AWS CLI, Terraform, Packer, Ansible, kubectl and Helm, each with what it does and how to run it safely.

These scripts sit next to infrastructure as code, not instead of it. For general scripting habits (a safe Bash template, backups, health-checked deploys) see our top 10 DevOps automation scripts, and for boto3 and Python examples see Python scripts for DevOps automation. This post stays on provisioning, compliance checks and cluster operations. The tools behind them is covered in our IaC tools pillar.

Key takeaways

  • Use scripts for glue around Terraform and Ansible: bootstrapping, checks, reports and guarded operations. Put lasting infrastructure in code.
  • Every script starts with set -euo pipefail, takes inputs as arguments or environment variables, and never contains credentials.
  • Audit scripts should report first. Anything that deletes or changes resources needs a dry-run mode and an explicit flag.
  • Run scheduled checks (drift, open ports, old keys) from CI with short-lived credentials, and send the output somewhere people read.
  • Test each script against a sandbox account or cluster before it touches production.

The 20 scripts at a glance

#ScriptToolingChanges things?
1Terraform state backend bootstrapAWS CLIYes (one time)
2Terraform pre-commit checksTerraform, tflintNo
3Scheduled drift detectionTerraformNo
4Multi-environment Terraform wrapperTerraformYes
5Golden image buildPackerYes (new image)
6cloud-init user datacloud-initYes (new VM)
7Dynamic Ansible inventory checkAnsibleNo
8Rolling OS patchingAnsibleYes
9SSH hardening playbookAnsibleYes
10Open security group auditAWS CLINo
11Untagged resource reportAWS CLINo
12IAM access key age reportAWS CLINo
13S3 public access checkAWS CLINo
14Old EBS snapshot reportAWS CLINo
15RDS snapshot before changeAWS CLIYes
16Auto Scaling instance refreshAWS CLIYes
17Route 53 record updateAWS CLIYes
18EKS kubeconfig and context checkAWS CLI, kubectlNo
19Namespace bootstrap with quotaskubectlYes
20Helm release with automatic rollbackHelmYes

Before you run any of these

  • Install current versions of the AWS CLI v2, Terraform, Ansible, kubectl and Helm, plus jq.
  • Authenticate with short-lived credentials: AWS IAM Identity Center (aws sso login) on a laptop, OIDC federation in CI. Do not put access keys in scripts.
  • Set AWS_PROFILE and AWS_REGION explicitly so a script never runs against the wrong account by accident.
  • Keep the scripts in a repository, run shellcheck on them in CI, and review changes like any other code.

Terraform and state

1. Terraform state backend bootstrap

Remote state needs a bucket before Terraform can use it, which is a chicken-and-egg problem. This script creates a versioned, encrypted, private S3 bucket once. Terraform 1.10 and later can lock state with an S3 lock file (use_lockfile = true), so a DynamoDB table is no longer required for new setups.

#!/usr/bin/env bash
set -euo pipefail
BUCKET="${1:?usage: $0 bucket-name}"
REGION="${AWS_REGION:?set AWS_REGION}"

aws s3api create-bucket --bucket "$BUCKET" --region "$REGION" \
  --create-bucket-configuration LocationConstraint="$REGION"
aws s3api put-bucket-versioning --bucket "$BUCKET" \
  --versioning-configuration Status=Enabled
aws s3api put-bucket-encryption --bucket "$BUCKET" \
  --server-side-encryption-configuration \
  '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"aws:kms"}}]}'
aws s3api put-public-access-block --bucket "$BUCKET" \
  --public-access-block-configuration \
  BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
echo "State bucket $BUCKET ready in $REGION"

Note: in us-east-1 you must omit --create-bucket-configuration. The matching backend block:

terraform {
  backend "s3" {
    bucket       = "acme-tfstate-prod"
    key          = "network/terraform.tfstate"
    region       = "ap-south-1"
    use_lockfile = true
  }
}

2. Terraform pre-commit checks

Formatting and validation errors are cheap to catch before a pull request. Run this locally or as the first CI job.

#!/usr/bin/env bash
set -euo pipefail
terraform fmt -check -recursive
for dir in $(find . -name '*.tf' -not -path '*/.terraform/*' -exec dirname {} \; | sort -u); do
  echo "Validating $dir"
  terraform -chdir="$dir" init -backend=false -input=false >/dev/null
  terraform -chdir="$dir" validate
done
tflint --recursive

init -backend=false downloads providers without touching remote state, so the check needs no cloud credentials.

3. Scheduled drift detection

Someone changes a security group in the console and Terraform does not know until the next apply. A nightly plan with -detailed-exitcode catches it: exit code 0 means no changes, 2 means changes are pending, 1 means an error.

#!/usr/bin/env bash
set -uo pipefail
STACKS=("network" "eks" "data")
drifted=()
for s in "${STACKS[@]}"; do
  terraform -chdir="stacks/$s" init -input=false >/dev/null || exit 1
  terraform -chdir="stacks/$s" plan -input=false -lock=false -detailed-exitcode -no-color > "plan-$s.txt"
  rc=$?
  if [ "$rc" -eq 2 ]; then drifted+=("$s"); elif [ "$rc" -eq 1 ]; then echo "Plan failed for $s"; exit 1; fi
done
if [ "${#drifted[@]}" -gt 0 ]; then
  echo "Drift found in: ${drifted[*]}"
  exit 2
fi
echo "No drift"

Run it from a scheduled CI job with a read-only role and post the result to your team channel. Our automation scripts guide uses the same exit code as a merge gate; here it is a nightly check across stacks.

4. Multi-environment Terraform wrapper

Typing the wrong var file in production is a classic mistake. A wrapper ties the environment name to its backend config and variables and asks for confirmation on apply to prod.

#!/usr/bin/env bash
set -euo pipefail
ENV="${1:?usage: $0 dev|staging|prod plan|apply}"
ACTION="${2:?usage: $0 dev|staging|prod plan|apply}"
case "$ENV" in dev|staging|prod) ;; *) echo "Unknown env $ENV"; exit 1;; esac

terraform init -input=false -reconfigure -backend-config="env/$ENV.backend.hcl"
terraform plan -input=false -var-file="env/$ENV.tfvars" -out="$ENV.tfplan"

if [ "$ACTION" = "apply" ]; then
  if [ "$ENV" = "prod" ]; then
    read -r -p "Type 'prod' to apply: " answer
    [ "$answer" = "prod" ] || { echo "Aborted"; exit 1; }
  fi
  terraform apply -input=false "$ENV.tfplan"
fi

Applying the saved plan file guarantees that what was reviewed is what runs.

Images and first boot

5. Golden image build with Packer

Baking common packages and hardening into an image makes servers start faster and identically. A minimal Packer template:

packer {
  required_plugins {
    amazon = {
      source  = "github.com/hashicorp/amazon"
      version = ">= 1.3.0"
    }
  }
}

source "amazon-ebs" "base" {
  region        = "ap-south-1"
  instance_type = "t3.small"
  ssh_username  = "ec2-user"
  ami_name      = "base-al2023-{{timestamp}}"
  source_ami_filter {
    filters = {
      name                = "al2023-ami-2023.*-x86_64"
      virtualization-type = "hvm"
    }
    owners      = ["amazon"]
    most_recent = true
  }
}

build {
  sources = ["source.amazon-ebs.base"]
  provisioner "shell" {
    inline = ["sudo dnf -y update", "sudo dnf -y install amazon-cloudwatch-agent"]
  }
}
packer init . && packer validate . && packer build .

6. cloud-init user data

For settings that differ per instance, cloud-init runs at first boot. Keep it short and idempotent; heavy configuration belongs in the image or in Ansible.

#cloud-config
package_update: true
packages:
  - chrony
users:
  - name: deploy
    groups: wheel
    shell: /bin/bash
    ssh_authorized_keys:
      - ssh-ed25519 AAAAC3Nza...example deploy@ci
runcmd:
  - systemctl enable --now chronyd

Configuration management

7. Dynamic Ansible inventory check

Static inventory files go stale. The amazon.aws.aws_ec2 inventory plugin builds groups from tags at run time. Save this as inventory.aws_ec2.yml:

plugin: amazon.aws.aws_ec2
regions:
  - ap-south-1
filters:
  instance-state-name: running
keyed_groups:
  - key: tags.Role
    prefix: role
compose:
  ansible_host: private_ip_address
ansible-inventory -i inventory.aws_ec2.yml --graph
ansible -i inventory.aws_ec2.yml role_web -m ping

Run the graph command before any playbook to confirm which hosts it will touch.

8. Rolling OS patching

Patching every web server at once takes the site down. serial patches a batch at a time, and max_fail_percentage stops the run if a batch breaks.

- name: Rolling patch for web servers
  hosts: role_web
  become: true
  serial: "25%"
  max_fail_percentage: 0
  tasks:
    - name: Apply updates
      ansible.builtin.dnf:
        name: "*"
        state: latest
    - name: Check whether a reboot is needed
      ansible.builtin.command: needs-restarting -r
      register: reboot_check
      changed_when: false
      failed_when: reboot_check.rc not in [0, 1]
    - name: Reboot if required
      ansible.builtin.reboot:
      when: reboot_check.rc == 1
    - name: Wait for the app health endpoint
      ansible.builtin.uri:
        url: "http://{{ ansible_host }}:8080/health"
      register: health
      retries: 10
      delay: 6
      until: health.status == 200

needs-restarting comes from dnf-utils on RHEL-family systems. More playbooks like this are in Ansible playbooks used in production.

9. SSH hardening playbook

Disable password and root login and validate the config before restarting the service, so a typo cannot lock you out.

- name: Harden SSH
  hosts: all
  become: true
  tasks:
    - name: Set secure sshd options
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "^#?{{ item.key }}\\s"
        line: "{{ item.key }} {{ item.value }}"
        validate: /usr/sbin/sshd -t -f %s
      loop:
        - { key: PasswordAuthentication, value: "no" }
        - { key: PermitRootLogin, value: "no" }
        - { key: MaxAuthTries, value: "3" }
      notify: Restart sshd
  handlers:
    - name: Restart sshd
      ansible.builtin.service:
        name: sshd
        state: restarted

Test on one host with a second session open before running it fleet-wide. On distributions that use /etc/ssh/sshd_config.d/ drop-in files, check that no drop-in overrides these values.

Cloud security and cost audits

10. Open security group audit

Security groups that allow SSH (22) or RDP (3389) from 0.0.0.0/0 are a frequent audit finding. This read-only report lists them.

#!/usr/bin/env bash
set -euo pipefail
for port in 22 3389; do
  aws ec2 describe-security-groups \
    --filters Name=ip-permission.cidr,Values=0.0.0.0/0 Name=ip-permission.from-port,Values=$port \
    --query 'SecurityGroups[].[GroupId,GroupName,VpcId]' --output text |
  while read -r id name vpc; do
    echo "OPEN port $port: $id ($name) in $vpc"
  done
done

The filters match groups that have a rule with that CIDR and a rule starting at that port, so confirm findings in the console before changing them. The fix is to remove the rule and use Systems Manager Session Manager or a VPN instead of open SSH.

11. Untagged resource report

Tags drive cost allocation and ownership. The Resource Groups Tagging API lists resources across services; this script shows those missing an Owner tag.

#!/usr/bin/env bash
set -euo pipefail
aws resourcegroupstaggingapi get-resources --output json |
  jq -r '.ResourceTagMappingList[]
    | select([.Tags[]?.Key] | index("Owner") | not)
    | .ResourceARN'

The API only returns resources that are or were tagged, or that support tagging through it, so treat the list as a starting point. Enforce tags going forward with Terraform default_tags and AWS Organizations tag policies.

12. IAM access key age report

Long-lived access keys are a common cause of credential leaks. The IAM credential report lists every user with key age and last use.

#!/usr/bin/env bash
set -euo pipefail
MAX_DAYS="${MAX_DAYS:-90}"
until aws iam generate-credential-report --query State --output text | grep -q COMPLETE; do sleep 2; done
aws iam get-credential-report --query Content --output text | base64 -d |
  awk -F, -v max="$MAX_DAYS" 'NR>1 && $9=="true" {
    cmd="date -d " $10 " +%s"; cmd | getline t; close(cmd)
    age=int((systime()-t)/86400)
    if (age>max) print $1, "key1 age", age, "days"
  }'

Columns 9 and 10 are access_key_1_active and access_key_1_last_rotated. The script uses GNU date and gawk's systime(), so run it on Linux. Better still, replace user keys with roles and Identity Center.

13. S3 public access check

Account-level Block Public Access should be on unless you have a documented reason. This script checks the account setting and each bucket.

#!/usr/bin/env bash
set -euo pipefail
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
aws s3control get-public-access-block --account-id "$ACCOUNT" || echo "No account-level block set"
for b in $(aws s3api list-buckets --query 'Buckets[].Name' --output text); do
  if ! aws s3api get-public-access-block --bucket "$b" >/dev/null 2>&1; then
    echo "No bucket-level public access block: $b"
  fi
done

14. Old EBS snapshot report

Snapshots pile up and cost money. List your own snapshots older than a cutoff, then decide on retention, ideally with Amazon Data Lifecycle Manager or AWS Backup rather than a delete script.

#!/usr/bin/env bash
set -euo pipefail
CUTOFF=$(date -u -d "${DAYS:-180} days ago" +%Y-%m-%d)
aws ec2 describe-snapshots --owner-ids self \
  --query "Snapshots[?StartTime<'${CUTOFF}'].[SnapshotId,VolumeSize,StartTime,Description]" \
  --output table

Safe changes to running infrastructure

15. RDS snapshot before change

Take a manual snapshot before a risky migration or engine upgrade and wait until it is available.

#!/usr/bin/env bash
set -euo pipefail
DB="${1:?usage: $0 db-instance-id}"
SNAP="${DB}-pre-change-$(date -u +%Y%m%d%H%M)"
aws rds create-db-snapshot --db-instance-identifier "$DB" --db-snapshot-identifier "$SNAP"
aws rds wait db-snapshot-available --db-snapshot-identifier "$SNAP"
echo "Snapshot $SNAP is available"

16. Auto Scaling instance refresh

After a new launch template version (for example a new golden image), an instance refresh replaces instances gradually while keeping healthy capacity.

#!/usr/bin/env bash
set -euo pipefail
ASG="${1:?usage: $0 asg-name}"
ID=$(aws autoscaling start-instance-refresh --auto-scaling-group-name "$ASG" \
  --preferences '{"MinHealthyPercentage":90,"InstanceWarmup":120,"AutoRollback":true}' \
  --query InstanceRefreshId --output text)
echo "Started refresh $ID"
while true; do
  status=$(aws autoscaling describe-instance-refreshes --auto-scaling-group-name "$ASG" \
    --instance-refresh-ids "$ID" --query 'InstanceRefreshes[0].Status' --output text)
  echo "Status: $status"
  case "$status" in Successful) exit 0;; Failed|Cancelled|RollbackSuccessful|RollbackFailed) exit 1;; esac
  sleep 30
done

Automatic rollback requires the group to use a launch template; check the AWS documentation for the conditions that apply to your setup.

17. Route 53 record update

Useful for cutovers that are not yet managed in Terraform. UPSERT creates or updates the record, and the wait command blocks until the change is in sync.

#!/usr/bin/env bash
set -euo pipefail
ZONE="${1:?zone-id}"; NAME="${2:?record name}"; IP="${3:?new ip}"
CHANGE=$(cat <<EOF
{"Changes":[{"Action":"UPSERT","ResourceRecordSet":{
  "Name":"$NAME","Type":"A","TTL":60,"ResourceRecords":[{"Value":"$IP"}]}}]}
EOF
)
ID=$(aws route53 change-resource-record-sets --hosted-zone-id "$ZONE" \
  --change-batch "$CHANGE" --query ChangeInfo.Id --output text)
aws route53 wait resource-record-sets-changed --id "$ID"
echo "$NAME now points to $IP"

Lower the TTL a day before a planned cutover so clients pick up the new address quickly.

Kubernetes cluster operations

18. EKS kubeconfig and context check

Running kubectl against the wrong cluster is one of the easiest serious mistakes. This script refreshes the kubeconfig entry and refuses to continue unless the current context matches what you expect.

#!/usr/bin/env bash
set -euo pipefail
CLUSTER="${1:?usage: $0 cluster-name}"
aws eks update-kubeconfig --name "$CLUSTER" --alias "$CLUSTER"
current=$(kubectl config current-context)
[ "$current" = "$CLUSTER" ] || { echo "Context is $current, expected $CLUSTER"; exit 1; }
kubectl get nodes -o wide

19. Namespace bootstrap with quotas

New teams get a namespace with a ResourceQuota and LimitRange so one workload cannot consume the whole cluster. Applying with kubectl apply keeps it repeatable.

#!/usr/bin/env bash
set -euo pipefail
NS="${1:?usage: $0 namespace}"
kubectl apply -f - <<EOF
apiVersion: v1
kind: Namespace
metadata:
  name: $NS
  labels:
    pod-security.kubernetes.io/enforce: restricted
---
apiVersion: v1
kind: ResourceQuota
metadata:
  name: default-quota
  namespace: $NS
spec:
  hard:
    requests.cpu: "4"
    requests.memory: 8Gi
    limits.cpu: "8"
    limits.memory: 16Gi
    pods: "50"
---
apiVersion: v1
kind: LimitRange
metadata:
  name: default-limits
  namespace: $NS
spec:
  limits:
    - type: Container
      default:
        cpu: 500m
        memory: 512Mi
      defaultRequest:
        cpu: 100m
        memory: 128Mi
EOF

The pod-security.kubernetes.io/enforce label turns on Pod Security Admission at the restricted level. Once this works, move it into your GitOps repository.

20. Helm release with automatic rollback

helm upgrade --install handles first install and upgrades with one command. With --atomic (renamed --rollback-on-failure in Helm 4), a failed upgrade is rolled back automatically.

#!/usr/bin/env bash
set -euo pipefail
RELEASE="${1:?release}"; CHART="${2:?chart}"; NS="${3:?namespace}"; VALUES="${4:?values file}"
helm lint "$CHART" -f "$VALUES"
helm upgrade --install "$RELEASE" "$CHART" \
  --namespace "$NS" --create-namespace \
  -f "$VALUES" --atomic --wait --timeout 5m
helm history "$RELEASE" -n "$NS" --max 5

Check which flag your Helm version supports with helm upgrade --help. For chart structure see Helm best practices.

When a script should become code

SignalMove it to
It creates resources that must exist long termA Terraform module
It configures many servers the same wayAn Ansible role
It applies Kubernetes objects repeatedlyA GitOps repository (Argo CD or Flux)
It checks compliance rulesAWS Config rules or policy as code
It grows past a page of Bash with JSON parsingPython with boto3

For running scripts and pipelines together, see DevOps pipeline automation tools.

Practise with guidance

Terraform and Ansible are where most of these scripts end up. Our Terraform training and Ansible training cover state, modules, inventories and roles in labs, in the Kharadi, Pune classroom or live online.

Frequently asked questions

What scripts should a DevOps engineer write for infrastructure automation?

Start with scripts that bootstrap Terraform state, run fmt and validate checks, detect drift, and report security issues such as open SSH ports, old access keys and public buckets. Then add guarded operational scripts for snapshots, instance refreshes and Helm releases.

Should I use Bash or Terraform for infrastructure automation?

Use Terraform (or another IaC tool) for resources that must exist long term, because it tracks state and shows plans. Use Bash for glue: bootstrapping, checks, reports and one-off operational tasks around the IaC.

How do I detect Terraform drift automatically?

Run terraform plan -detailed-exitcode on a schedule from CI with a read-only role. Exit code 2 means the real infrastructure differs from code, so alert the team and decide whether to update code or revert the change.

Do I still need DynamoDB for Terraform state locking?

Not for new setups on Terraform 1.10 or later. The S3 backend supports native locking with use_lockfile = true. DynamoDB-based locking still works but is deprecated in the S3 backend documentation.

How do I keep credentials out of infrastructure scripts?

Use AWS IAM Identity Center on laptops and OIDC federation in CI so scripts get short-lived role credentials from the environment. Never hard-code access keys, and scan repositories for secrets.

Should audit scripts delete resources automatically?

No. Start with report-only scripts, review findings, and fix them through code. If you add deletion later, require an explicit flag, a dry-run default and a retention policy owned by a person.

How do I test infrastructure scripts safely?

Run shellcheck in CI, test against a sandbox account or a local kind cluster, and add dry-run modes. For Ansible use --check --diff; for Terraform review the plan before apply.

References

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.