Infrastructure as Code Concepts
Category: DevOps and System Tools
Type: Linux Commands
Generated on: 2025-07-10 03:22:28
For: System Administration, Development & Technical Interviews
Infrastructure as Code Concepts Cheatsheet (Linux Commands - DevOps & System Tools)
Section titled “Infrastructure as Code Concepts Cheatsheet (Linux Commands - DevOps & System Tools)”This cheatsheet covers essential Linux commands frequently used in Infrastructure as Code (IaC) and DevOps workflows. It aims to be a quick reference for sysadmins and developers alike.
1. Command Overview:
ssh: Secure Shell; remotely access and manage servers. Essential for IaC execution on remote machines.scp: Secure Copy; securely transfer files between systems. Used for deploying configurations and artifacts.rsync: Remote Sync; efficient file synchronization. Ideal for replicating configurations and backups.sed: Stream EDitor; perform text transformations. Used extensively for configuration templating and automation.awk: Pattern scanning and processing language; powerful text processing. Used for data extraction and reporting.grep: Global Regular Expression Print; search for patterns in files. Used for log analysis and configuration validation.find: Locate files based on criteria. Used for managing files across a system.xargs: Build and execute command lines from standard input. Used to chain commands and process large lists of files.curl: Transfer data with URLs; used for API interactions and downloading resources.jq: JSON processor; parse, filter, and transform JSON data. Essential for working with APIs.systemctl: Manage systemd services; control services on modern Linux systems.docker: Containerization platform; build, run, and manage containers.kubectl: Kubernetes command-line tool; manage Kubernetes clusters.ansible: Automation engine; orchestrate configuration management and application deployment.terraform: Infrastructure as Code tool; define and manage infrastructure across multiple cloud providers.
2. Basic Syntax:
ssh:ssh [user@]host [command]scp:scp [options] source destinationrsync:rsync [options] source destinationsed:sed [options] 'command' fileawk:awk '{action}' filegrep:grep [options] pattern filefind:find path [expression]xargs:command | xargs [options] commandcurl:curl [options] URLjq:jq [options] 'filter' filesystemctl:systemctl [command] servicedocker:docker [command] [options] imagekubectl:kubectl [command] [options] resourceansible:ansible [host-pattern] -m module -a 'arguments'terraform:terraform [command]
3. Practical Examples:
-
ssh:Terminal window # Connect to server 'webserver' as user 'deploy'ssh deploy@webserver# Execute a command on the remote server and exitssh deploy@webserver "uptime"Output:
14:32:01 up 10 days, 1:22, 1 user, load average: 0.01, 0.02, 0.00 -
scp:Terminal window # Copy a file to a remote serverscp local_file.txt deploy@webserver:/tmp/# Copy a directory recursivelyscp -r local_directory deploy@webserver:/tmp/ -
rsync:Terminal window # Sync a local directory to a remote server, recursively and with compressionrsync -avz local_directory deploy@webserver:/tmp/# Sync a remote directory to a local directoryrsync -avz deploy@webserver:/tmp/remote_directory ./local_directory -
sed:Terminal window # Replace all occurrences of 'old_string' with 'new_string' in a filesed 's/old_string/new_string/g' input.txt > output.txt# Replace in-place (be careful!)sed -i 's/old_string/new_string/g' input.txt# Replace based on a regular expressionsed 's/pattern/replacement/g' file.txt -
awk:Terminal window # Print the first column of each lineawk '{print $1}' file.txt# Print lines where the second column is greater than 10awk '$2 > 10 {print}' file.txt# Sum the values in the third columnawk '{sum += $3} END {print sum}' file.txt -
grep:Terminal window # Search for a pattern in a filegrep "error" logfile.txt# Search recursively in a directorygrep -r "error" /var/log/# Case-insensitive searchgrep -i "error" logfile.txt -
find:Terminal window # Find all files in the current directoryfind . -type f# Find all files modified in the last 24 hoursfind . -type f -mtime -1# Find all files with a specific namefind . -name "important.txt"# Find all files and execute a command on themfind . -type f -exec chmod 644 {} \; #WARNING: Be careful with this. -
xargs:Terminal window # Find all files and delete them (WARNING: VERY DANGEROUS!)find . -name "*.tmp" -print0 | xargs -0 rm -f# Find all files and compress themfind . -name "*.txt" -print0 | xargs -0 gzip -
curl:Terminal window # Download a filecurl -o output.txt https://example.com/file.txt# Send a POST request with datacurl -d "param1=value1¶m2=value2" https://example.com/api# Get data from an API with authenticationcurl -u user:password https://example.com/api -
jq:Terminal window # Pretty print JSON datacurl -s https://api.example.com/data | jq .# Extract a specific fieldcurl -s https://api.example.com/data | jq '.name'# Filter data based on a conditioncurl -s https://api.example.com/data | jq '.[] | select(.status == "active")' -
systemctl:Terminal window # Start a servicesudo systemctl start nginx# Stop a servicesudo systemctl stop nginx# Restart a servicesudo systemctl restart nginx# Check the status of a servicesystemctl status nginx# Enable a service to start on bootsudo systemctl enable nginx# Disable a service from starting on bootsudo systemctl disable nginx -
docker:Terminal window # Pull an imagedocker pull ubuntu:latest# Run a containerdocker run -d -p 80:80 nginx# List running containersdocker ps# Stop a containerdocker stop <container_id># Remove a containerdocker rm <container_id># Build an image from a Dockerfiledocker build -t my-app . -
kubectl:Terminal window # Get all podskubectl get pods# Get details about a specific podkubectl describe pod <pod_name># Apply a Kubernetes configuration filekubectl apply -f deployment.yaml# Delete a resourcekubectl delete deployment <deployment_name># Get logs from a podkubectl logs <pod_name> -
ansible:Terminal window # Ping all hosts defined in the inventory fileansible all -m ping# Execute a shell command on all hostsansible all -m shell -a "uptime"# Copy a file to all hostsansible all -m copy -a "src=local_file.txt dest=/tmp/"# Run a playbookansible-playbook my_playbook.yml -
terraform:Terminal window # Initialize Terraformterraform init# Plan the changesterraform plan# Apply the changesterraform apply# Destroy the infrastructureterraform destroy
4. Common Options:
-
ssh:-i: Specify identity (private key) file.-p: Specify port number.-v: Verbose mode for debugging.-N: Do not execute a remote command (port forwarding).-L: Local port forwarding.-R: Remote port forwarding.
-
scp:-r: Recursive copy (for directories).-p: Preserve modification times, access times, and modes.-C: Enable compression.-q: Quiet mode.
-
rsync:-a: Archive mode (recursive, preserves permissions, etc.).-v: Verbose mode.-z: Enable compression.-P: Show progress and keep partially transferred files if interrupted.--delete: Delete extraneous files on the destination.--exclude: Exclude files or directories.
-
sed:-i: Edit file in place. USE WITH CAUTION!-n: Suppress automatic printing of pattern space.-e: Execute multiple commands.-r: Use extended regular expressions.
-
awk:-F: Specify field separator.-v: Assign a variable.
-
grep:-i: Case-insensitive search.-r: Recursive search.-n: Show line numbers.-v: Invert match (show lines not matching).-c: Count the number of matching lines.
-
find:-type: Specify file type (e.g.,ffor file,dfor directory).-name: Specify file name.-mtime: Specify modification time (in days).-exec: Execute a command on found files.-delete: Delete found files. USE WITH EXTREME CAUTION!
-
xargs:-n: Maximum number of arguments per command line.-I: Replace occurrences of a placeholder in the command.-0: Expect input items to be terminated by a null character (for handling filenames with spaces).
-
curl:-o: Specify output file.-d: Send POST data.-H: Add a custom header.-u: Specify username and password.-X: Specify request method (e.g., POST, PUT, DELETE).-s: Silent mode.
-
jq:.: Represents the entire input.[]: Array/object value iterator.|: Pipe output from one filter to another..key: Access object properties.[index]: Access array elements.
-
systemctl:start: Start a service.stop: Stop a service.restart: Restart a service.status: Check the status of a service.enable: Enable a service to start on boot.disable: Disable a service from starting on boot.
-
docker:run: Run a container.ps: List containers.stop: Stop a container.rm: Remove a container.build: Build an image from a Dockerfile.pull: Pull an image from a registry.
-
kubectl:get: Get resources.describe: Get details about a resource.apply: Apply a configuration file.delete: Delete a resource.logs: Get logs from a pod.
-
ansible:-m: Specify the module to use.-a: Specify arguments for the module.-k: Ask for SSH password.-i: Specify inventory file.
-
terraform:init: Initialize Terraform.plan: Plan the changes.apply: Apply the changes.destroy: Destroy the infrastructure.
5. Advanced Usage:
-
ssh: Port forwarding for secure tunneling:Terminal window # Local port forwarding: Access a service on the remote server via localhostssh -L 8080:localhost:80 deploy@webserver# Remote port forwarding: Allow others to access a service on your local machine via the remote serverssh -R 8080:localhost:80 deploy@webserver -
sed: Complex substitutions with backreferences:Terminal window # Swap the first and second words on each linesed 's/\(\w\+\) \(\w\+\)/\2 \1/' file.txt -
awk: Using custom functions and arrays:# Calculate the average of numbers in a fileawk '{sum += $1; count++} END {print sum/count}' numbers.txt -
find+xargs: Parallel execution for faster processing:Terminal window # Find all files and compress them in parallel using multiple coresfind . -name "*.txt" -print0 | xargs -0 -P 4 gzip # -P 4 uses 4 parallel processes -
curl+jq: Chaining to extract specific data from APIs:Terminal window # Get the public IP address of the current machine using an external APIcurl -s https://api.ipify.org?format=json | jq -r .ip -
ansible: Usingwith_itemsto iterate over a list of items:- name: Create usersuser:name: "{{ item }}"state: presentloop:- user1- user2- user3 -
terraform: Using variables and modules for reusable infrastructure:variable "region" {type = stringdefault = "us-east-1"}module "ec2_instance" {source = "./modules/ec2"ami = "ami-0c55b4cdcec567a0a" # Example AMI IDregion = var.region}
6. Tips & Tricks:
- Shell Aliases: Define aliases for frequently used commands to save time and reduce typing errors. Example:
alias k=kubectl - Bash History: Use
Ctrl+Rto search your command history. - Tab Completion: Use
Tabto auto-complete commands, file names, and options. - Pipe to
less: Pipe long output tolessfor easier viewing (command | less). UseSpacebarto go down one page,qto quit. tee: Useteeto both display output on the screen and save it to a file (command | tee output.txt).history | grep <command>: Search your command history for a specific command.
7. Troubleshooting:
sshConnection Refused: Ensure the SSH service is running on the remote server and that the firewall is not blocking connections on port 22 (or the custom SSH port).scpPermission Denied: Verify you have the necessary permissions to write to the destination directory on the remote server.sedIncorrect Substitution: Double-check your regular expressions and escape characters. Use a testing tool likeregex101.comto validate your regex.findUnexpected Results: Carefully review your search criteria and ensure the path is correct.curlConnection Errors: Check your network connection and ensure the URL is correct.jqInvalid JSON: Verify the JSON data is valid using a validator likejsonlint.com.systemctlService Fails to Start: Check the service logs for errors usingjournalctl -u <service_name>.dockerContainer Fails to Start: Check the container logs for errors usingdocker logs <container_id>.kubectlResource Not Found: Ensure the resource exists in the specified namespace and that you have the correct permissions.ansibleHost Unreachable: Verify the host is reachable via SSH and that the inventory file is correctly configured. Check SSH key permissions.terraformState Corruption: Useterraform state pullandterraform state pushto back up and restore your Terraform state. Consider using remote state storage like S3 or Azure Blob Storage.
8. Related Commands:
- Package Management:
apt,yum,dnf,pacman(for installing and managing software packages). - Networking:
ifconfig,ip,netstat,ss,ping,traceroute(for network configuration and troubleshooting). - File Management:
ls,cd,mkdir,rm,cp,mv,chmod,chown(for basic file operations). - Process Management:
ps,top,htop,kill,pkill(for monitoring and managing processes). - User Management:
useradd,userdel,usermod,passwd(for managing user accounts). - Disk Management:
df,du,fdisk,mkfs(for managing disk space and partitions). - Cloud-Specific CLIs:
aws,gcloud,az(for interacting with cloud services).
This cheatsheet provides a solid foundation for using Linux commands in Infrastructure as Code workflows. Remember to always test your commands in a safe environment before applying them to production systems. Always double-check destructive commands like rm -rf and find -delete.