DevOps Command CheatSheets
Your interactive quick-reference for Git, Linux, Docker, Kubernetes, Terraform and Ansible — with descriptions, examples, and one-click copy.
Welcome to the Ultimate DevOps Command CheatSheet 2026. Whether you are a Junior Engineer or a seasoned SRE, keeping track of every flag for kubectl, git, or terraform can be challenging. This interactive guide provides a centralized, quick-access reference for the most essential tools in the modern DevOps landscape.
Designed for speed and utility, you can search for any command, copy it with a single click, and view examples and pro-tips to avoid common pitfalls in production environments.
Git Cheatsheet
Version control system for tracking changes in source code during software development.
Basic Workflow 9 cmds
git clone <repo-url>Downloads the entire version history to your machine.
Copies a remote repository to local machine.
git clone https://github.com/user/repo.gitgit statusShows changed, staged, and untracked files.
Shows changed files, staged/untracked state.
git status -s (short format)git add <file> / git add .Use
. to stage all changes in the current directory.Prepare files for commit by staging them.
git add -p (interactive patch staging)git commit -m "message"Saves a snapshot of the staged changes to the history.
Save snapshot of staged changes.
git commit -am "fix: login bug"git push origin <branch>Uploads local commits to the remote repository.
Push local commits to remote.
git push --force-with-lease origin feature/logingit pull origin <branch>Equivalent to git fetch followed by git merge.
Update local branch from remote.
git pull --rebase origin maingit branchThe current branch is marked with *.
Lists all local branches.
git branch -a (all including remote)git checkout <branch>Moves HEAD to the specified branch.
Switch to another branch.
git switch main (modern alternative)git checkout -b <new-branch>Shorthand for git branch + git checkout.
Create and switch to a new branch.
git checkout -b feature/dark-modeBranch Management 4 cmds
git branch -aShows both local and remote-tracking branches.
Shows local and remote branches.
git branch -r (remote only)git branch -d <branch>Use -D to force delete even if unmerged.
Delete a local branch (safe). Use -D to force.
git branch -D old-featuregit branch -m <new-name>Renames the currently checked-out branch.
Rename the current branch.
git branch -m master maingit push -u origin <branch>Subsequent pushes can use just
git push.Push new branch and set upstream tracking.
git push -u origin feature/apiUndoing Changes 5 cmds
git reset <file>Removes file from staging area without touching working tree.
Remove file from staging area.
git reset HEAD~1 (undo last commit, keep changes)git checkout -- <file>Reverts the file to the last committed state.
Revert file to last commit state.
git restore <file> (modern syntax)git commit --amendEdit the last commit message or add staged files.
Edit last commit message or add files.
git commit --amend --no-editgit revert <commit>Creates a new commit that reverses the target commit.
Safely undo a commit (creates a new revert commit).
git revert HEADgit reset --hard <commit>Resets working tree and index to the specified commit. Uncommitted changes are LOST.
⚠️ DANGEROUS — permanently erases commits.
git reset --hard HEAD~1Rebasing 4 cmds
git rebase mainReplays your commits on top of main — gives a cleaner, linear history.
Applies commits on top of main. Use carefully on shared branches.
git rebase -i HEAD~3 (interactive)git rebase --abortReturns the branch to its original state before the rebase started.
Stop and undo an in-progress rebase.
git rebase --continueRun after manually resolving merge conflicts.
Continue rebase after fixing conflict.
git rebase --skipSkips the current conflicting commit and moves to the next.
Skip current commit during rebase.
Viewing History 4 cmds
git log --oneline --graph --decoratePretty one-line log with branch visualization.
View compact commit history with branch graph.
git log -10 --onelinegit log <file>Filters the commit history to changes affecting that file.
Shows commits that touched a specific file.
git blame <file>Shows who last changed each line and in which commit.
See who changed which line in a file.
git diffUse
git diff --staged to see staged changes.Show unstaged changes in working tree.
git diff main feature/newMerge & Conflict Resolution 4 cmds
git merge <branch>Combines the specified branch's history into the current branch.
Merge a branch into current branch.
git merge feature/my-featuregit merge --continueUsed after manually editing conflicted files and staging them.
Continue a merge after resolving conflicts.
git merge --abortRestores the branch to the pre-merge state.
Abort a bad merge and restore original state.
git reset --hard origin/mainUse when you've merged the wrong branch: revert, then force push, then merge the correct branch.
Revert to remote state after a wrong merge. Follow with git push --force.
git reset --hard HEAD~1 → git push --forceLinux Cheatsheet
Essential commands for interacting with Unix/Linux based systems.
File & Directory Operations 12 cmds
ls -la-l = long format, -a = include hidden files.
List files including hidden, with permissions and size.
ls -lh /var/log (human-readable sizes)cd /path/to/dirUse
cd .. to go up one level, cd ~ for home.Navigate to a directory.
cd ~/DocumentspwdShows the full path of your current location.
Show the current directory path.
mkdir -p project/src/main-p creates parent directories as needed.
Create directories recursively.
mkdir -m 755 publictouch file.txtCreates the file if it doesn't exist.
Create an empty file or update its timestamp.
cp -r directory/ backup/-p preserves timestamps and permissions.
Copy files or directories.
cp -p file.txt preserved.txtmv old.txt new.txtWorks for both renaming and moving to a different directory.
Move or rename files/directories.
mv *.txt archive/rm -rf directory/-r = recursive, -f = force. Permanent deletion!
⚠️ Permanently delete files/directories.
rm -i *.txt (interactive)find . -name "*.txt"Supports -type, -size, -mtime and many more filters.
Search for files matching a pattern.
find /home -type f -size +100Mcat file.txtAlso used to concatenate multiple files.
Print file contents to terminal.
cat file1.txt file2.txt > merged.txtdu -sh /home-s = summary, -h = human-readable.
Measure disk usage of a directory.
df -h-h = human-readable units.
Display free disk space for all mounted filesystems.
Text Processing 8 cmds
grep -Ri "pattern" .-R = recursive, -i = case insensitive.
Search for patterns recursively inside files.
grep -r 'error' /var/log/sed 's/old/new/g' file.txt-i flag edits the file in-place.
Stream editor for substituting text.
sed -i.bak 's/old/new/g' file.txtawk '{print $1}' file.txtExtremely powerful for field-based text processing.
Process and extract specific columns from text.
awk -F: '{print $1}' /etc/passwdtail -f /var/log/syslog-f continuously outputs new lines as they are added.
Monitor a log file in real-time.
head -n 20 file.txtDefault is 10 lines.
Display the first lines of a file.
sort -n numbers.txtBy default sort is lexicographic. -r for reverse.
Sort lines in a file.
sort -r -k2 data.txtwc -l file.txt-w = words, -c = characters, -l = lines.
Count words, lines and characters.
cut -d: -f1 /etc/passwd-d = delimiter, -f = field number.
Extract specific columns from text.
System Monitoring 8 cmds
topPress q to quit, k to kill a process.
Monitor system processes in real-time.
htop (better UI)ps auxa=all users, u=user-oriented format, x=processes without terminal.
Show all running processes with details.
ps aux | grep nginxfree -h-h for human-readable (MB/GB).
Check RAM and swap usage.
uname -aKernel, hostname, architecture, and OS version.
Display kernel and system information.
uptimeShows 1, 5, and 15 minute load averages.
Check how long system has been running.
dmesg | grep errordmesg shows kernel ring buffer messages.
View kernel messages, useful for diagnosing hardware issues.
lsof -i :8080lsof = list open files. -i filters by internet address.
Find which process is using a specific port.
journalctl -u nginx -f-u = unit (service), -f = follow.
View and follow logs for a systemd service.
journalctl --since "1 hour ago"Permissions & Users 7 cmds
chmod 755 script.sh7=owner rwx, 5=group rx, 5=others rx.
Change file/directory permissions.
chmod +x script.shsudo chown user:group file.txtUse -R for recursive ownership changes.
Change the owner of a file or directory.
sudo <command>Required for system-level operations.
Execute command with elevated root privileges.
sudo useradd -m -s /bin/bash newuser-m creates home directory, -s sets default shell.
Add a new user to the system.
sudo passwd usernameRun without args to change your own password.
Set or change a user password.
sudo usermod -aG sudo username-aG = append to group without removing from others.
Modify user account properties / group membership.
id usernameDisplays uid, gid, and supplementary groups.
Show user and group IDs.
Networking 8 cmds
ping -c 4 google.com-c = count (number of packets). Omit for continuous ping.
Check network reachability to a host.
ss -tulpnt=TCP, u=UDP, l=listening, p=process, n=numeric.
Show all open/listening network ports and associated processes.
ssh user@server.comUse -i for a specific key file, -p for custom port.
Securely connect to a remote server.
ssh -i key.pem user@server.comscp file.txt user@server:/tmp/-r for directories, -P for custom port.
Transfer files over SSH.
curl -X POST https://api.example.com/data-O download, -H headers, -d data body.
Transfer data using HTTP/HTTPS.
wget https://example.com/file.zip-O to specify output filename.
Download files from the internet.
nslookup google.comUse dig for more detailed output.
Query DNS records for a domain.
ip addr showModern replacement for ifconfig.
Display IP addresses for all network interfaces.
Process Management & Services 6 cmds
kill -9 <pid>SIGKILL (9) can't be caught or ignored.
Terminate a process by PID.
pkill nginxSends SIGTERM by default. Use -9 for force kill.
Kill processes matching a name pattern.
sudo systemctl restart nginxAlso: start, stop, status, enable, disable.
Manage systemd services.
sudo systemctl enable --now nginxcrontab -eFormat: MIN HOUR DOM MON DOW COMMAND
Schedule recurring tasks.
0 2 * * * /scripts/backup.shnohup command &Process continues after terminal closes.
Run a command in background, surviving terminal close.
screen -S mysessionDetach with Ctrl+A D, reattach with screen -r.
Manage persistent terminal sessions.
tmux new -s mysession is a modern alternative.Docker Cheatsheet
Platform for building, running, and managing containers.
Images 6 cmds
docker build -t <image_name> .-t sets the tag/name. . = build context.
Build a Docker image from a Dockerfile.
docker build --no-cache -t myapp:v2 .docker imagesShows image name, tag, ID, and size.
List all locally available Docker images.
docker rmi <image_name>Fails if containers from this image still exist.
Remove a local Docker image.
docker image prune -aFrees up disk space from images not used by any container.
Remove all unused images to free disk space.
docker pull <image_name>Downloads the latest tag by default.
Download an image from Docker Hub.
docker pull nginx:alpinedocker push <username>/<image_name>Must be logged in with docker login first.
Publish a local image to Docker Hub.
Containers 10 cmds
docker run --name <name> -d -p 8080:80 <image>-d = background, -p host:container port mapping.
Create and run a container from an image.
docker run -it ubuntu bash (interactive)docker ps --allWithout --all only shows running containers.
List all Docker containers.
docker start|stop <container_name>Also: docker restart, docker pause, docker unpause.
Start or stop an existing container.
docker rm <container_name>Use docker rm -f to remove running containers.
Delete a stopped container.
docker exec -it <container_name> sh-it = interactive tty. Use bash if sh not available.
Open an interactive shell inside a running container.
docker logs -f <container_name>-f = follow (similar to tail -f).
Stream logs from a running container.
docker inspect <container_name>Returns JSON with all configuration details.
Get detailed information about a container.
docker container statsShows CPU, memory, network, and disk I/O in real-time.
Monitor container resource usage live.
docker login -u <username>Required before pushing images.
Log into Docker Hub.
docker search <image_name>Returns official and community images.
Search Docker Hub for available images.
Compose & Networks 5 cmds
docker compose up -dReads docker-compose.yml. Builds images if needed.
Start multi-container application in detached mode.
docker compose downAdd --volumes to also delete volumes.
Stop and remove compose containers and networks.
docker network lsShows bridge, host, none, and custom networks.
List all Docker networks.
docker volume lsVolumes persist data beyond container lifecycle.
List all Docker volumes.
docker system prune -aFrees containers, images, networks, and build cache.
Clean up all unused Docker resources.
Kubernetes Cheatsheet
Container orchestration platform for automating deployment, scaling, and operations. (kubectl v1.35)
Autocomplete & Aliases 5 cmds
source <(kubectl completion bash)Requires bash-completion package installed.
Set up kubectl tab completion in bash.
echo "source <(kubectl completion bash)" >> ~/.bashrcsource <(kubectl completion zsh)Add to ~/.zshrc for persistence.
Set up kubectl tab completion in zsh.
alias k=kubectlAlso add:
complete -o default -F __start_kubectl kConfigure k as a short alias for kubectl.
alias kx='f() { [ "$1" ] && kubectl config use-context $1 || kubectl config current-context ; } ; f'kx = show current context, kx <name> = switch context.
Alias for switching kubectl context quickly.
kubectl -AWorks with get, describe, logs, etc.
Shorthand for --all-namespaces flag.
kubectl get pods -AContext & Configuration 10 cmds
kubectl config view--raw shows raw certificate data.
View all kubeconfig settings.
kubectl config view --rawkubectl config get-contextsA context defines cluster, user, and namespace.
Display list of all available kubectl contexts.
kubectl config current-contextTells you which cluster kubectl is talking to.
Display the currently active kubectl context.
kubectl config use-context my-cluster-nameUse after kubectl config get-contexts to see available ones.
Set the default kubectl context.
kubectl config set-context --current --namespace=my-nsAll subsequent commands will use this namespace.
Set the default namespace for the current context.
kubectl config set-credentials kubeuser --username=kubeuser --password=passSupports basic auth, token, and certificate.
Add a new user to kubeconfig.
kubectl config unset users.fooWorks for contexts, clusters, and users.
Delete a user entry from kubeconfig.
kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'jsonpath is powerful for targeting nested fields.
Get the password for a specific user from kubeconfig.
KUBECONFIG=~/.kube/config:~/.kube/kubconfig2 kubectl config viewColon-separated list. All files are merged at runtime.
Use and view multiple kubeconfig files simultaneously.
kubectl config set-cluster my-cluster --proxy-url=my-proxy-urlRoutes kubectl requests through the specified proxy.
Set a proxy URL for a cluster entry in kubeconfig.
Creating Objects 8 cmds
kubectl apply -f ./my-manifest.yamlCreates or updates resources defined in the YAML.
Create or update Kubernetes resources from a file.
kubectl apply -f ./my1.yaml -f ./my2.yamlkubectl apply -f ./dirProcesses all .yaml, .yml, and .json files.
Create/update resources from all files in a directory.
kubectl apply -f https://example.com/manifest.yamlIdeal for installing upstream tools directly.
Apply resources from a remote URL.
kubectl create deployment nginx --image=nginxQuick way to start a deployment without a YAML file.
Start a single instance of nginx as a deployment.
kubectl create job hello --image=busybox:1.28 -- echo "Hello World"Runs the specified command and exits.
Create a Kubernetes Job that prints Hello World.
kubectl create cronjob hello --image=busybox:1.28 --schedule="*/1 * * * *" -- echo "Hello"Runs on the specified cron schedule.
Create a scheduled (cron) job in Kubernetes.
kubectl explain podsUse kubectl explain pods.spec.containers for nested fields.
Get documentation for Kubernetes resource fields.
kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yamlDry-run generates the YAML without hitting the API server.
Generate a pod YAML spec without applying it.
Viewing & Finding Resources 12 cmds
kubectl get pods --all-namespacesShorthand: -A
List all pods across all namespaces.
kubectl get pods -o widekubectl get pod my-pod -o yamlUseful for understanding current state and debugging.
Get YAML spec of a running pod.
kubectl describe pod <pod-name>Shows events, conditions, containers, volumes.
Show verbose details and events for a pod.
kubectl describe nodes my-nodekubectl get pods --sort-by='.status.containerStatuses[0].restartCount'Helpful to identify crash-looping containers.
List pods sorted by restart count.
kubectl get pods --selector=app=cassandra -o jsonpath="{.items[*].metadata.labels.version}"jsonpath is a powerful templating language for extracting fields.
Filter pods by label and extract a specific field.
kubectl get node -o custom-columns='NODE_NAME:.metadata.name,STATUS:.status.conditions[?(@.type=="Ready")].status'Cleaner output than the full describe.
Check which nodes are ready using custom-columns output.
kubectl get node --selector='!node-role.kubernetes.io/control-plane'Excludes nodes with the control-plane label.
List only worker nodes by excluding control-plane label.
kubectl get pods --field-selector=status.phase=RunningField selectors filter by the resource state/spec values.
Get only running pods using field selector.
kubectl get events --sort-by=.metadata.creationTimestampUseful for understanding what happened in what order.
List events chronologically.
kubectl events --types=Warningkubectl diff -f ./my-manifest.yamlShows what changes would be made by kubectl apply.
Preview changes before applying a manifest.
kubectl get secret my-secret -o go-template='{{...}}'Uses go-template with base64decode function.
Output decoded secrets without using base64 externally.
kubectl get deployment nginx-deployment --subresource=statusReturns only the status portion of the resource.
Get the status subresource of a deployment.
Updating Resources 8 cmds
kubectl set image deployment/frontend www=image:v2Triggers a rolling update with zero downtime.
Update the image of a container in a deployment.
kubectl rollout status -w deployment/frontendReturns success/failure once rollout completes.
Monitor a deployment rollout until it completes.
kubectl rollout undo deployment/frontendUse --to-revision=N for a specific version.
Roll back a deployment to the previous version.
kubectl rollout undo deployment/frontend --to-revision=2kubectl rollout history deployment/frontendShows revision history including change cause.
Check deployment history and revisions.
kubectl rollout restart deployment/frontendForces pod recreation without changing the spec.
Restart all pods in a deployment via rolling update.
kubectl label pods my-pod new-label=awesomeUse --overwrite to change an existing label.
Add or update a label on a resource.
kubectl label pods my-pod new-label-kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWqAnnotations store arbitrary metadata.
Annotate a resource with metadata.
kubectl autoscale deployment foo --min=2 --max=10Automatically scales between min and max replicas.
Configure auto-scaling for a deployment.
Patching & Editing 6 cmds
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'Merge patch applies only the specified fields.
Partially update a resource using a patch.
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"...","image":"new image"}]}}'spec.containers[*].name is required as merge key.
Update a container's image using a strategic merge patch.
kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'RFC 6902 JSON Patch format.
Update a resource using JSON patch format.
kubectl patch deployment ... --type json -p='[{"op": "remove", "path": "...livenessProbe"}]'Useful for temporarily disabling health checks.
Disable a deployment's liveness probe using JSON patch.
kubectl patch deployment nginx-deployment --subresource='scale' --type='merge' -p '{"spec":{"replicas":2}}'Targets the /scale subresource instead of the full resource.
Update replica count via scale subresource patch.
kubectl edit svc/docker-registryUse KUBE_EDITOR=nano to set editor preference.
Open and edit an API resource in your editor.
KUBE_EDITOR="nano" kubectl edit svc/docker-registryScaling & Deleting 7 cmds
kubectl scale --replicas=3 rs/fooWorks with deployments, replicasets, statefulsets.
Scale a replicaset to the specified number of replicas.
kubectl scale --replicas=3 -f foo.yamlkubectl scale --current-replicas=2 --replicas=3 deployment/mysqlOnly scales if current replica count matches the expected value.
Scale only if current replicas match the condition.
kubectl delete -f ./pod.jsonDeletes the resource defined in the manifest file.
Delete a resource using a manifest file.
kubectl delete pod unwanted --nowSkips the graceful termination period.
Instantly delete a pod with no grace period.
kubectl -n my-ns delete pod,svc --allBe careful — this is irreversible.
Delete all pods and services in a specific namespace.
kubectl delete pods,services -l name=myLabelDeletes all matching resources across types.
Delete pods and services matching a label selector.
kubectl replace --force -f ./pod.jsonDeletes and recreates the resource — causes downtime.
⚠️ Force delete and re-create a resource (causes outage).
Interacting with Pods 10 cmds
kubectl logs -f my-pod-f = follow, -c = specific container, --previous = crashed container.
Stream logs from a pod.
kubectl logs -l name=myLabelkubectl logs my-pod --previousUseful when a container has crashed and restarted.
Get logs from a previously crashed container.
kubectl logs -f -l name=myLabel --all-containersUseful for microservices observation.
Follow logs from all pods matching a label.
kubectl exec --stdin --tty my-pod -- /bin/sh--stdin + --tty gives a real interactive shell.
Open an interactive shell inside a running pod.
kubectl exec my-pod -- ls /kubectl port-forward my-pod 5000:6000Useful for accessing services without exposing them.
Listen on port 5000 locally and forward to port 6000 on pod.
kubectl port-forward svc/my-service 5000kubectl debug my-pod -it --image=busybox:1.28Attaches a debugging sidecar to a running pod.
Attach a debug container to a running pod.
kubectl debug node/my-node -it --image=busybox:1.28kubectl top pod POD_NAME --containersRequires metrics-server to be installed.
Show CPU and memory metrics for a pod's containers.
kubectl cp /tmp/foo_dir my-pod:/tmp/bar_dirRequires 'tar' binary in the container image.
Copy files between local machine and pod.
kubectl cp my-namespace/my-pod:/tmp/foo /tmp/barkubectl attach my-pod -iDifferent from exec — connects to existing process.
Attach stdin to a running container process.
kubectl run -i --tty busybox --image=busybox:1.28 -- shUseful for quick network tests inside the cluster.
Spin up a temporary interactive debug pod.
Nodes & Cluster 8 cmds
kubectl cordon my-nodeNo new pods will be scheduled on this node.
Prevent new pods from being scheduled on a node.
kubectl drain my-nodeCombines cordon + graceful pod eviction for maintenance.
Drain a node before maintenance.
kubectl uncordon my-nodeRun after maintenance to restore normal operation.
Mark a node as schedulable again after maintenance.
kubectl top nodeRequires metrics-server installed in the cluster.
Show CPU and memory metrics for all nodes.
kubectl cluster-infoShows control plane and CoreDNS endpoints.
Display addresses of the master and cluster services.
kubectl cluster-info dumpkubectl taint nodes foo dedicated=special-user:NoSchedulePrevents pods without matching toleration from scheduling.
Add a taint to restrict pod scheduling on a node.
kubectl api-resourcesShows shortnames, API group, namespaced status, and kind.
List all Kubernetes resource types with API info.
kubectl api-resources --namespaced=truekubectl logs deploy/my-deployment -c my-containerAutomatically picks a pod from the deployment.
View logs from a deployment's pods.
Terraform Cheatsheet
Infrastructure as Code tool for building, changing, and versioning infrastructure safely and efficiently.
Init & Setup 4 cmds
terraform initFirst command to run. Downloads providers, modules, and sets up backend.
Initialize working directory — must run before any other command.
terraform init -input=falseterraform init -input=falseRequired for CI/CD pipelines to avoid waiting for input.
Initialize Terraform in non-interactive CI mode.
terraform init -backend-config=cfg/s3.dev.tf -reconfigure-reconfigure tells Terraform not to copy existing state to the new backend.
Initialize with a different backend configuration file.
terraform get -update=truePulls latest module content after editing module sources.
Download and update module sources.
Plan & Apply 5 cmds
terraform plan -out plan.outShows what actions Terraform will perform before making them.
Generate and save an execution plan to a file.
terraform apply plan.outApplies exact changes from the plan file.
Apply an infrastructure change from a plan file.
terraform apply --auto-approve⚠️ Skip interactive approval — use with caution!
Apply changes automatically without confirmation prompt.
terraform apply --auto-approve -var tags_repository_url=${GIT_URL}Useful for injecting CI/CD variables.
Apply and set specific variable values inline.
terraform apply -target=module.s3Works with plan too. Useful for targeted changes.
Apply changes to only one specific resource or module.
Destroy, Validate & Debug 6 cmds
terraform destroyUse -target to destroy only a specific resource.
⚠️ Destroy all Terraform-managed resources.
terraform destroy -target aws_s3_bucket.my_bucketterraform validateChecks all .tf files for syntax errors without accessing remote state.
Validate Terraform configuration for syntax errors.
echo "aws_iam_user.notif.arn" | terraform consoleTerraform console reads the current state.
Evaluate expressions and test interpolations interactively.
TF_LOG_PATH=mylogfile.txt TF_LOG=debug terraform applyLevels: TRACE, DEBUG, INFO, WARN, ERROR.
Set log level and save Terraform logs to a file.
terraform graph | dot -Tpng > graph.pngRequires graphviz (dot) to be installed.
Visualize infrastructure dependency graph as PNG.
terraform providersLists all providers used by modules in the project.
Print a tree of all providers used in the project.
State Management 7 cmds
terraform showHuman-readable display of all managed resources.
Display the current Terraform state.
terraform refreshCompares and updates state file from actual provider.
Update state to reflect actual infrastructure.
terraform state pull > terraform.tfstateUseful for inspection or migration.
Download remote state to a local file.
terraform state pushUsed when migrating from local to remote backend.
Upload local state to remote backend storage.
terraform state mv aws_iam_role.role1 module.mymodulUse after refactoring resources into modules.
Move a resource reference when refactoring into modules.
terraform import aws_iam_policy.elastic_post arn:aws:iam::123456789:policy/elastic_postAllows Terraform to manage resources not originally created by it.
Import an existing cloud resource into Terraform state.
terraform output -json | jq '.elastic_endpoint.value'Powerful combination for script automation.
Get specific output value in JSON format.
Workspaces 4 cmds
terraform workspace new devWorkspaces manage multiple environments with a single config.
Create and select a new Terraform workspace.
terraform workspace select devEach workspace has its own state file.
Switch to an existing workspace.
terraform workspace listActive workspace is marked with *.
List all available Terraform workspaces.
terraform workspace showPrints the active workspace name.
Display the name of the current active workspace.
Ansible Cheatsheet
IT automation tool for configuration management, application deployment, and task automation.
Installation 4 cmds
sudo apt update && sudo apt install ansibleInstalls the latest stable version from apt.
Install Ansible on Debian-based systems.
sudo yum install ansiblepip install ansibleAlways gets the latest version directly from PyPI.
Install Ansible using pip (cross-platform).
pipx install ansiblebrew install ansibleHomebrew is the recommended way on macOS.
Install Ansible on macOS using Homebrew.
export ANSIBLE_CONFIG=/path/to/ansible.cfgOverrides default ansible.cfg discovery.
Point Ansible to a custom configuration file.
Inventory & Ad-Hoc 6 cmds
ansible all -m ping -i inventoryVerifies SSH and Python availability on each managed node.
Ping all managed hosts to verify connectivity.
ansible all -m command -a "uptime"-m = module, -a = module arguments.
Run an ad-hoc command on all inventory hosts.
ansible all -m shell -a "echo $TERM"Shell module supports pipes, redirects, and env vars.
Run a shell command (supports shell features like $TERM).
ansible all -m copy -a "src=/etc/hosts dest=/tmp/hosts"Can also set permissions: owner, group, mode.
Copy a file to all managed hosts.
ansible all -m apt -a "name=nginx state=present"Use yum module for RHEL-based systems.
Install a package on all inventory hosts.
ansible all -m service -a "name=nginx state=restarted"States: started, stopped, restarted, reloaded.
Restart a service on all managed hosts.
Playbooks 12 cmds
ansible-playbook playbook.ymlExecutes tasks defined in the YAML file against matching hosts.
Execute an Ansible playbook.
ansible-playbook playbook.yml -i inventoryCan be a file, directory, or script.
Run playbook with a specific inventory file.
ansible-playbook playbook.yml --limit "web"Restricts the target hosts.
Limit playbook execution to a specific host group.
ansible-playbook playbook.yml --tags "install,configure"Useful for partial execution of a playbook.
Execute only tasks with specific tags.
ansible-playbook playbook.yml --skip-tags "configure"Runs everything except tasks with the specified tags.
Skip tasks with specific tags.
ansible-playbook playbook.yml --extra-vars "my_var=123"Overrides variables defined in the playbook.
Override or inject variables at runtime.
ansible-playbook playbook.yml --checkShows what would change without actually applying anything.
Preview what changes would be made without applying them.
ansible-playbook playbook.yml --diffShows before/after for files managed by modules.
Show file differences when running playbook.
ansible-playbook playbook.yml -vvv-v=verbose, -vv=more, -vvv=connection debug, -vvvv=extreme.
Run playbook with increasingly verbose debug output.
ansible-playbook playbook.yml --vault-password-file ~/.vault_pass.txtFor decrypting vault-encrypted variables.
Use a vault password file to decrypt secrets.
ansible-playbook playbook.yml --ask-become-passRequired when become: yes is used in the playbook.
Prompt for privilege escalation (sudo) password.
ansible-playbook playbook.yml --forks 50Default is 5. Increase for large inventories.
Set the number of parallel processes for execution.
Ansible Vault 6 cmds
ansible-vault encrypt file.ymlThe file is encrypted in-place with AES-256.
Encrypt a file using Ansible Vault.
ansible-vault decrypt file.ymlConverts back to plaintext — use with caution.
Decrypt a vault-encrypted file.
ansible-vault view file.ymlShows the plaintext without modifying the file.
View an encrypted vault file without decrypting it.
ansible-vault edit file.ymlOpens the file in your editor, re-encrypts on save.
Edit a vault-encrypted file in your editor.
ansible-vault rekey file.ymlRotate credentials by re-encrypting with a new password.
Re-encrypt a vault file with a new password.
ansible-vault encrypt_string "Hello World!" --name "my_var"Use the output directly inline in a playbook variable.
Encrypt a single string value for use in a playbook variable.
Galaxy & Collections 6 cmds
ansible-galaxy search nginxAnsible Galaxy is the community repository for roles.
Search Ansible Galaxy for available roles.
ansible-galaxy install elastic.elasticsearch,7.15.0Version pinning is recommended for reproducibility.
Install an Ansible role from Galaxy with version pinning.
ansible-galaxy init my_roleGenerates the standard role directory structure.
Create a new Ansible role with the standard directory structure.
ansible-galaxy collection install community.generalCollections bundle roles, playbooks, and plugins.
Install a collection from Ansible Galaxy.
ansible-galaxy collection install community.general:8.1.0ansible-galaxy collection install community.general-8.1.0.tar.gzUseful for air-gapped or offline environments.
Install a collection from a local archive file.
ansible all -m setupReturns system info: OS, CPU, memory, network, etc.
Collect facts (system info) from all managed hosts.
ansible all -m setup -a "filter=ansible_eth*"Debugging 5 cmds
ansible-playbook playbook.yml --syntax-checkValidates YAML structure and Ansible syntax.
Check playbook for syntax errors without executing.
ANSIBLE_DEBUG=1 ansible all -m pingOutputs extensive debug information.
Enable Ansible debug mode with an environment variable.
register: outputUse 'debug: var: output' to inspect the result.
Capture a task's output for inspection.
debug: var: output.stdoutansible all -m ping -c ssh-c local for local testing, -c winrm for Windows.
Test host connectivity with SSH connection type.
ansible-playbook playbook.yml --stepPrompts before executing each task — useful for debugging.
Execute playbook one task at a time with approval prompts.
Frequently Asked Questions
How do I use this DevOps cheatsheet effectively?
Use the search bar at the top to filter by tool, category, or specific keywords like "push", "logs", or "apply". Each command can be copied directly to your clipboard using the copy icon.
Are these commands compatible with the latest tool versions?
Yes, the commands are updated for 2026 standards, including Kubectl v1.35+, Terraform 1.7+, and modern Git workflows.
Can I contribute or suggest new commands?
Absolutely! This is a living document. Feel free to reach out via the contact section on the homepage to suggest improvements or new tools.