1. Git & GitHub Advanced
Git Internals & Advanced Commands
Interactive Rebase
Git Stash Advanced
| Command | Description |
|---|---|
git stash save "message" |
Stash with descriptive message |
git stash list |
List all stashes |
git stash apply stash@{2} |
Apply specific stash |
git stash branch new-branch |
Create branch from stash |
git stash show -p stash@{0} |
Show stash content |
Git Hooks Example
2. GitHub Actions
Complete CI/CD Workflow
Matrix Strategy
3. Linux for DevOps
Essential System Commands
| Category | Command | Description |
|---|---|---|
| System Info | uname -a |
All system information |
df -h |
Disk usage human readable | |
free -h |
Memory usage | |
top / htop |
Process monitoring | |
| Network | ss -tulpn |
Show listening ports |
ip addr show |
Show IP addresses | |
curl -I URL |
Get HTTP headers | |
dig domain.com |
DNS lookup |
Service Management (systemd)
Creating a Custom Service
Changing File Permissions
The chmod command enables you to change the permissions on a file. You must be superuser or the owner of a file or directory to change its permissions.
You can use the chmod command to set permissions in either of two modes:
- Absolute Mode - Use numbers to represent file permissions (the method most commonly used to set permissions). When you change permissions by using the absolute mode, represent permissions for each triplet by an octal mode number.
- Symbolic Mode - Use combinations of letters and symbols to add or remove permissions.
Setting File Permissions in Absolute Mode
| Octal Value | File Permissions Set | Permissions Description |
|---|---|---|
| 0 | --- | No permissions |
| 1 | --x | Execute permission only |
| 2 | -w- | Write permission only |
| 3 | -wx | Write and execute permissions |
| 4 | r-- | Read permission only |
| 5 | r-x | Read and execute permissions |
| 6 | rw- | Read and write permissions |
| 7 | rwx | Read, write, and execute permissions |
Setting File Permissions in Symbolic Mode
| Symbol | Function | Description |
|---|---|---|
| u | Who | User (owner) |
| g | Who | Group |
| o | Who | Others |
| a | Who | All |
| = | Operation | Assign |
| + | Operation | Add |
| - | Operation | Remove |
| r | Permission | Read |
| w | Permission | Write |
| x | Permission | Execute |
| l | Permission | Mandatory locking, setgid bit is on, group execution bit is off |
| s | Permission | setuid or setgid bit is on |
| S | Permission | suid bit is on, user execution bit is off |
| t | Permission | Sticky bit is on, execution bit for others is on |
| T | Permission | Sticky bit is on, execution bit for others is off |
How to Change Permissions in Absolute Mode
If you are not the owner of the file or directory, become superuser.
Only the current owner or superuser can use the chmod command to change file permissions on a file or directory.
Change permissions in absolute mode by using the chmod command:
nnn specifies the octal values that change permissions on the file or directory. See the table above for the list of valid octal values.
filename is the file or directory.
Verify the permissions of the file have changed:
Example--Changing Permissions in Absolute Mode
How to Change Permissions in Symbolic Mode
If you are not the owner of the file or directory, become superuser.
Only the current owner or superuser can use the chmod command to change file permissions on a file or directory.
Change permissions in symbolic mode by using the chmod command:
who specifies whose permissions are changed, operator specifies the operation to perform, and permission specifies what permissions are changed. See the table above for the list of valid symbols.
filename is the file or directory.
Verify the permissions of the file have changed:
Examples--Changing Permissions in Symbolic Mode
4. Docker Deep Dive
Multi-Stage Dockerfile
Docker Commands Reference
5. Kubernetes Complete Guide
Deployment with All Features
Essential Kubectl Commands
| Category | Command |
|---|---|
| Cluster Info | kubectl cluster-info |
| Get Resources | kubectl get pods -o wide --all-namespaces |
| Describe | kubectl describe pod pod-name |
| Logs | kubectl logs -f pod-name --tail=50 |
| Execute | kubectl exec -it pod-name -- /bin/bash |
| Port Forward | kubectl port-forward pod-name 8080:80 |
| Scale | kubectl scale deployment app --replicas=5 |
| Rollout | kubectl rollout status deployment/app |
What is Ingress in Kubernetes?
Ingress is a Kubernetes API object used to manage external access to services inside the cluster.
Ingress is used to:
- expose HTTP/HTTPS applications
- route incoming traffic to different services
- define host-based or path-based routing
- handle SSL/TLS termination
Ingress acts like a set of rules that tells Kubernetes:
What is an Ingress Controller?
An Ingress Controller is the actual implementation that executes the rules defined in the Ingress object.
Ingress is only a configuration. It does nothing by itself. The Ingress Controller is responsible for processing those rules and routing the traffic.
Examples of Ingress Controllers:
- NGINX Ingress Controller
- AWS ALB Ingress Controller
- GKE Ingress
- Traefik Ingress Controller
- HAProxy Ingress
Simple Analogy
Ingress: Think of Ingress as a βtraffic rulebookβ written on paper.
Ingress Controller: Think of the Ingress Controller as the βtraffic policeβ who reads the rulebook and actually controls the traffic.
Visual Diagram Explanation
Internet
LoadBalancer
Ingress Controller
--------------------------------
/app1 β Service1
/app2 β Service2
/admin β Service3
The Ingress Controller reads these rules and handles routing.
Summary
| Component | Meaning | Responsibility |
|---|---|---|
| Ingress | A set of routing rules | Defines how traffic should flow |
| Ingress Controller | The engine that applies the rules | Routes traffic to correct services |
Basic Cluster Commands
| Command | Description |
|---|---|
kubectl version | Show client + server K8s version. |
kubectl cluster-info | See cluster master & DNS info. |
kubectl get all | List all resources (pods, svc, deployments, etc.) in default namespace. |
Working With Contexts
| Command | Description |
|---|---|
kubectl config get-contexts | List all contexts (clusters). |
kubectl config use-context dev | Switch to another cluster. |
kubectl config current-context | Show which cluster you are using. |
Namespaces
| Command | Description |
|---|---|
kubectl get namespaces | List namespaces. |
kubectl create namespace dev | Create namespace. |
kubectl delete namespace dev | Delete namespace. |
kubectl config set-context --current --namespace=dev | Set default namespace. |
Pods
| Command | Description |
|---|---|
kubectl get pods | List pods. |
kubectl get pods -o wide | Show pod IP, node, etc. |
kubectl describe pod pod-name | Detailed pod info & events. |
kubectl logs pod-name | View logs. |
kubectl logs -f pod-name | Follow live logs. |
kubectl exec -it pod-name -- bash | Enter pod terminal. |
kubectl delete pod pod-name | Delete a pod. |
Deployments
| Command | Description |
|---|---|
kubectl get deployments | List deployments. |
kubectl create deployment web --image=nginx | Create deployment. |
kubectl scale deployment web --replicas=5 | Scale number of pods. |
kubectl rollout status deployment/web | Check deployment rollout status. |
kubectl rollout undo deployment/web | Rollback to previous version. |
kubectl delete deployment web | Delete deployment. |
ReplicaSets
| Command | Description |
|---|---|
kubectl get rs | List ReplicaSets. |
kubectl describe rs rs-name | ReplicaSet details. |
Services
| Command | Description |
|---|---|
kubectl get svc | List services. |
kubectl expose deployment web --type=NodePort --port=80 | Expose deployment as a service. |
kubectl describe svc web | Service details. |
kubectl get svc -o wide | See service cluster IP & ports. |
ConfigMaps
| Command | Description |
|---|---|
kubectl create configmap app-config --from-literal=env=prod | Create ConfigMap. |
kubectl create configmap myconfig --from-file=config.properties | Create from file. |
kubectl get configmaps | List ConfigMaps. |
kubectl describe configmap app-config | View config details. |
Secrets
| Command | Description |
|---|---|
kubectl create secret generic db-secret --from-literal=password=1234 | Create secret. |
kubectl create secret generic tls-secret --from-file=server.crt --from-file=server.key | Create TLS secret. |
kubectl get secrets | List secrets. |
kubectl describe secret db-secret | Describe secret. |
YAML Apply, Update & Delete
| Command | Description |
|---|---|
kubectl apply -f deployment.yaml | Apply or update resource. |
kubectl delete -f deployment.yaml | Delete resource. |
kubectl edit deployment web | Edit resource live in editor. |
Nodes & Cluster Info
| Command | Description |
|---|---|
kubectl get nodes | List nodes. |
kubectl get nodes -o wide | Node details (OS, internal IP). |
kubectl describe node node1 | Node details (taints, capacity). |
kubectl drain node1 --ignore-daemonsets | Drain node safely. |
kubectl cordon node1 | Mark node unschedulable. |
kubectl uncordon node1 | Mark node schedulable. |
Resource Usage
| Command | Description |
|---|---|
kubectl top pods | CPU & memory usage of pods. |
kubectl top nodes | CPU & memory usage of nodes. (Metrics server required) |
Taints & Tolerations
Add taint:
Remove taint:
Used for:
- Dedicate nodes
- Restrict workloads
- Isolation
Labels & Selectors
| Command | Description |
|---|---|
kubectl label pod web app=frontend | Add label. |
kubectl get pods -l app=frontend | Filter with label. |
kubectl label pod web app- | Remove label. |
Port Forwarding
Access pod locally. Common for debugging APIs.
Ingress
| Command | Description |
|---|---|
kubectl get ingress | List ingress rules. |
kubectl describe ingress my-ingress | Ingress details. |
StatefulSets
| Command | Description |
|---|---|
kubectl get statefulsets | List StatefulSets. |
kubectl describe statefulset mysql | Stateful app details. |
Used for:
- Databases
- Kafka
- ElasticSearch
DaemonSets
| Command | Description |
|---|---|
kubectl get daemonsets | List DaemonSets. |
Used for:
- Logging agents
- Monitoring agents
Jobs & CronJobs
| Command | Description |
|---|---|
kubectl create job myjob --image=busybox | Create Job. |
kubectl create cronjob backup --image=busybox --schedule="*/5 * * * *" | Create CronJob. |
kubectl get jobs | List jobs. |
kubectl get cronjobs | List CronJobs. |
Pod Debugging
| Command | Description |
|---|---|
kubectl describe pod web | Check events. |
kubectl logs pod --previous | Check logs of crashed container. |
kubectl exec -it web -- sh | Debug inside pod. |
kubectl get pod web -o yaml | View complete pod spec. |
Troubleshooting Cluster
| Command | Description |
|---|---|
kubectl get events | Cluster-wide events. |
kubectl get endpoints | Check service endpoints. |
kubectl get componentstatus | Master component status (older K8s). |
kubectl get networkpolicies | Check network restrictions. |
Network Policies
| Command | Description |
|---|---|
kubectl get netpol | List policies. |
kubectl describe netpol | Network policy details. |
Used for:
- Restrict pod-to-pod communication
- Zero-trust networking
Storage
| Command | Description |
|---|---|
kubectl get pv | List persistent volumes. |
kubectl get pvc | List persistent volume claims. |
kubectl describe pv pv-name | PV details. |
kubectl describe pvc pvc-name | PVC details. |
Service Accounts & RBAC
| Command | Description |
|---|---|
kubectl get serviceaccounts | List service accounts. |
kubectl create serviceaccount dev-sa | Create SA. |
kubectl get clusterrole | List cluster roles. |
kubectl get clusterrolebinding | List bindings. |
Used for:
- Access control
- Least privilege
- Pod-to-AWS auth (IRSA)
Deleting Everything
| Command | Description |
|---|---|
kubectl delete all --all | Delete pods, svc, deployments in namespace. |
kubectl delete namespace dev | Delete entire namespace. |
Useful Shortcuts
| Command | Description |
|---|---|
kubectl get po | Short for pods. |
kubectl get deploy | Short for deployments. |
kubectl get svc | Short for service. |
kubectl get ing | Short for ingress. |
kubectl get cm | Short for configmap. |
kubectl get no | Short for nodes. |
Apply with Dry Run (very important)
Check if YAML is valid without applying.
28. Debugging Node Issues
Detailed node conditions.
29. Extract Pod YAML
Useful for reproducing or modifying pods.
30. Kubernetes API Access
31. Advanced Pod Debugging
32. Ephemeral Debug Container (K8s 1.23+)
Used for:
- CrashLoopBackOff
- ImagePullBackOff
- Node-level debugging
33. ImagePull & Crash Issues
Common issues:
- ImagePullBackOff
- ErrImagePull
- CrashLoopBackOff
34. Rollouts & History
35. Advanced Scaling
36. YAML Dry Run & Diff
Useful for CI/CD pipelines.
37. Patching (Very Important for DevOps)
Used for:
- Hotfixes
- On-the-fly changes
- CI/CD automation
38. Node Health & Troubleshooting
39. Events & Cluster-level Issues
40. Service Debugging
41. Ingress Debugging
42. Network Policy Debugging
43. Persistent Storage Commands
44. Logs & Audit
45. Node-to-Pod Debugging
46. Copy Files To & From Pod
47. ConfigMaps & Secrets Debugging
48. K8s Useful JSONPath Queries
49. Resource Quotas & Limits
50. LimitRanges
Used for:
- default CPU/memory
- maximum/minimum allowed resources
51. Service Account with Pod
52. RBAC Debugging
53. Port & Connectivity Debugging (Must Know)
54. Horizontal Pod Autoscaling
Cluster Autoscaler Debugging
Advanced Resource Filtering (field selectors)
| Command | Description |
|---|---|
kubectl get pods --field-selector spec.nodeName=node1 | Get pods scheduled on a specific node |
kubectl get pods --field-selector=status.phase=Failed | Get pods that failed |
kubectl get pods --field-selector=status.phase!=Running | Get pods that are not running |
kubectl get pods --sort-by=.metadata.creationTimestamp | Get pods created in last 5 minutes |
Advance JSON & YAML Output Formatting
| Command | Description |
|---|---|
kubectl get pods -o jsonpath='{.items[*].metadata.name}' | Get only pod names |
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}' | Get node internal IPs |
kubectl get pods -o jsonpath='{.items[*].spec.containers[*].image}' | Get pod image names |
Temporary BusyBox Pod (for debugging)
Check Pod Events Script
Get Pod Environment Variables
Debugging Service DNS
| Command | Description |
|---|---|
kubectl run dns-test --rm -it --image=busybox -- nslookup svc-name | Test DNS resolution |
kubectl run dns-test --rm -it --image=busybox -- nslookup kubernetes.default | Test cluster DNS |
Debug Service Connectivity
| Command | Description |
|---|---|
kubectl run test --rm -it --image=busybox -- nc -zv svc-name 80 | Test port connectivity |
kubectl run test --rm -it --image=curlimages/curl -- curl http://svc-name | Test via curl |
Debug Node Ports
Pod Security / User Permissions
Copy Kubernetes Manifest From Live Resource
| Command | Description |
|---|---|
kubectl get deploy web -o yaml > web.yaml | Extract current running deployment YAML |
kubectl get cm app-config -o yaml > configmap.yaml | Extract current configmap YAML |
Validating YAML
| Command | Description |
|---|---|
kubectl apply -f app.yaml --dry-run=client | Client-side validation |
kubectl apply -f app.yaml --dry-run=server | Server-side validation |
kubeval app.yaml | Lint YAML (if installed) |
Kubernetes API Access (Raw)
| Command | Description |
|---|---|
kubectl get --raw /metrics | View cluster components metrics |
kubectl get --raw /api | Access API paths |
Node Disk / Memory Pressure Debugging
Look for:
- DiskPressure
- MemoryPressure
- PIDPressure
Node Logs (Master & Worker Debugging)
- journalctl -u kubelet -f
- journalctl -u containerd -f
Restarting Pods Properly
| Command | Description |
|---|---|
kubectl delete pod pod-name | Delete pod safely (deployment recreates it) |
kubectl delete pod pod-name --force --grace-period=0 | Force delete stuck pod |
Restart Deployment (Without Editing)
Checking Cluster Authentication
| Command | Description |
|---|---|
kubectl auth can-i create pods | Test if user can perform action |
kubectl auth can-i delete pods --as bob | Test as specific user |
Get Logs From ALL Pods of a Deployment
Debugging Network Policies
| Command | Description |
|---|---|
kubectl get netpol | List policies |
kubectl run test --rm -it --image=busybox -- sh | Connectivity test across namespaces |
Inside:
ConfigMap Reload Troubleshooting
- Pod restarts
- Sidecar reloaders (e.g., Reloader, ConfigMap reloader)
- Using projected volumes
Secret Decoding & Validation
| Command | Description |
|---|---|
echo 'cGFzc3dvcmQ=' | base64 --decode | Decode a secret |
echo -n 'mypassword' | base64 | Encode new value |
Checking Pod Storage Paths
| Command | Description |
|---|---|
kubectl get pod pod -o jsonpath='{.spec.volumes}' | Check mounted volumes |
kubectl get pod pod -o jsonpath='{.spec.containers[*].volumeMounts}' | Check volume mount path |
Live Pod Debug Session
This creates a temporary container INSIDE pod for debugging.
Upgrade Kubernetes Without Downtime (Cluster Admin)
Check nodes before upgrade:
Upgrade node one-by-one:
Then update node OS/Kubelet.
Advanced kube-proxy Debugging
- iptables -L -t nat
- journalctl -u kube-proxy -f
6. Ingress & Cert Manager
Complete Ingress Configuration
Cert Manager Setup
7. Observability Stack
Prometheus Configuration
Useful PromQL Queries
Grafana Dashboard Setup
Quick Reference
Daily Use Commands
9. Terraform
Terraform Interview Questions
By DevOps Shack
Table of Contents
- Introduction to Terraform
- What is Terraform and what are its main features?
- Can you explain the difference between Terraform and other configuration management tools like Ansible, Puppet, or Chef?
- State Management
- What is state in Terraform, and why is it important?
- How do you manage multiple environments (e.g., development, staging, production) in Terraform?
- Providers and Modules
- What is a Terraform provider, and how do you use it?
- Explain the difference between Terraform modules and resources.
- Importing Resources
- How can you import existing infrastructure into Terraform?
- Variables and Outputs
- What are Terraform variables, and how do you use them?
- How do you handle secrets or sensitive data in Terraform?
- Initialization and Planning
- What is the purpose of the terraform init command?
- How does Terraform handle concurrent operations in a team environment?
- Advanced Features
- How does Terraform handle resource dependencies?
- What is drift detection in Terraform, and how do you handle drift?
- Lifecycle Management
- How does Terraform manage resource lifecycles?
- What is the purpose of the terraform taint command?
- Dynamic Blocks and Conditional Logic
- What are Terraform dynamic blocks, and how are they used?
- How does Terraform support conditional resource creation?
- Remote State Management
- How do you manage remote state in Terraform?
- How does Terraform state file locking work in remote backends?
- Formatting and Debugging
- What is terraform fmt, and why is it important?
- How do you debug errors in Terraform?
- Zero-Downtime Deployments
- How does Terraform handle zero-downtime deployments?
- Provisioners
- Explain the difference between local-exec and remote-exec provisioners.
- Shared Modules
- How do you manage shared modules in Terraform?
- Terraform Cloud
- What is Terraform Cloud, and how does it differ from Terraform CLI?
- Resource Management
- What are Terraform backends, and why are they important?
- What is the purpose of the terraform output command?
- Version Constraints
- How does Terraform manage provider and configuration version constraints?
- Secrets Management
- How can you securely manage secrets in Terraform?
- Interactive Console
- What is the purpose of the terraform console command?
- Limitations and Best Practices
- What are the limitations of Terraform?
- How can you ensure best practices while working with Terraform?
Introduction to Terraform
Terraform, developed by HashiCorp, is one of the most popular Infrastructure as Code (IaC) tools, enabling developers and operations teams to define, provision, and manage infrastructure efficiently. With its declarative configuration language (HCL) and multi-cloud compatibility, Terraform has become a go-to tool for automating infrastructure management. This document compiles 50 Terraform interview questions and answers, covering fundamental concepts, advanced features, and practical use cases. It serves as a comprehensive guide for professionals preparing for Terraform interviews or looking to strengthen their understanding of the tool.
What is Terraform and what are its main features?
Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp. It allows you to define, provision, and manage infrastructure across various cloud providers and services using a declarative configuration language known as HashiCorp Configuration Language (HCL).
Main Features:
- Infrastructure as Code (IaC): Manage infrastructure using code, enabling version control, reuse, and sharing.
- Provider Agnostic: Supports multiple providers like AWS, Azure, GCP, and others, allowing for a consistent workflow.
- Execution Plans: Generates and shows execution plans before applying changes, helping you understand what Terraform will do.
- Resource Graph: Builds a graph of all resources and their dependencies, optimizing resource creation and modification.
- Change Automation: Automates complex changesets to your infrastructure with minimal human interaction.
Can you explain the difference between Terraform and other configuration management tools like Ansible, Puppet, or Chef?
Purpose:
- Terraform: Primarily an infrastructure provisioning tool. It focuses on creating, updating, and versioning infrastructure safely and efficiently.
- Ansible/Puppet/Chef: Primarily configuration management tools. They are used to install and manage software on existing servers.
Approach:
- Terraform: Declarative. You describe the desired state, and Terraform figures out how to achieve it.
- Ansible/Puppet/Chef: Can be both declarative and procedural, depending on how you write your configurations or playbooks.
Infrastructure Lifecycle:
- Terraform: Manages the entire lifecycle of infrastructure, including creation, scaling, and destruction.
- Ansible/Puppet/Chef: Manages the software and settings on already provisioned infrastructure.
What is state in Terraform, and why is it important?
Terraform State: A persistent data store that maps Terraform configurations to real-world resources. It's typically stored in a file named terraform.tfstate.
Importance:
- Mapping: Keeps track of resource IDs and metadata, enabling Terraform to manage resources effectively.
- Planning and Execution: Allows Terraform to generate accurate execution plans by knowing the current state of resources.
- Collaboration: When stored remotely (e.g., in AWS S3 or Terraform Cloud), it enables team collaboration by sharing the state.
Managing Multiple Environments in Terraform
To manage multiple environments (e.g., development, staging, production) in Terraform, you can use the following methods:
Workspaces
- Use Terraform workspaces to maintain separate state files within the same configuration for different environments.
- Example:
Directory Structure
- Organize configurations into separate directories for each environment, each with its own state.
- Example:
Variable Files
- Use different .tfvars files for each environment to parameterize configurations.
- Example:
Backend Configuration
Configure backends to manage state storage for different environments.
Terraform Provider
A Terraform provider is a plugin that interacts with APIs of cloud platforms and services (e.g., AWS, Azure, Google Cloud). Providers define resources and data sources for a service.
Usage
- Declaration:
- Version Pinning:
- You can configure multiple providers to manage resources across different platforms.
Difference Between Terraform Modules and Resources
Resources
Resources are the basic building blocks in Terraform, representing infrastructure objects like virtual networks, compute instances, or databases.
Modules
Modules are containers for multiple resources that are used together, promoting code reuse and organization. They can be shared and versioned.
Importing Existing Infrastructure into Terraform
Step 1: Write Resource Configuration
Define the resource in your .tf files without any parameters that Terraform can't infer.
Step 2: Run Import Command
Use terraform import to map the existing resource to the Terraform resource.
Step 3: Refresh and Update Configuration
Run terraform plan to see differences and update the configuration to match the actual settings.
Terraform Variables
Input Variables
Input variables are parameters for Terraform modules, making configurations flexible and reusable.
Usage
Setting Variables
- Environment Variables: export TF_VAR_instance_type="t2.small"
- Command-Line Flags: terraform apply -var="instance_type=t2.small"
- Variable Files: Create .tfvars files and pass them with -var-file flag.
Output Variables
Output variables are used to expose values to the user or other configurations.
Handling Secrets or Sensitive Data in Terraform
Sensitive Variables
Mark variables as sensitive to prevent them from being displayed in logs.
Avoid Hardcoding
Do not store secrets in code or version control. Use environment variables or prompt for input.
Use Vault or Secret Management Services
Integrate with tools like HashiCorp Vault to fetch secrets at runtime.
Secure State Storage
Use encrypted remote backends to store state files securely.
Example of Fetching a Secret
Purpose of the terraform init Command
The terraform init command initializes a Terraform working directory by downloading and installing the necessary providers and modules.
Functions
- Plugin Installation: Downloads provider plugins required for the configuration.
- Backend Initialization: Sets up the backend for state storage.
- Module Installation: Downloads modules from sources like GitHub or the Terraform Registry.
When to Run
- First time setting up a configuration.
- After adding or changing providers or modules.
- After cloning a repository containing Terraform configurations.
Handling Resource Dependencies in Terraform
Implicit Dependencies
Terraform automatically determines resource dependencies by analyzing references in configurations.
Explicit Dependencies
Use depends_on when a dependency isnβt detected automatically.
Managing Remote State in Terraform
Remote state is used to share the state file among team members and secure it.
Example Using AWS S3
Terraform Backend Configuration
Features of Terraform Backend
- Storage: Stores the state in a remote backend like S3, Azure Blob, or Terraform Cloud.
- Locking: Prevents concurrent changes using mechanisms like DynamoDB tables.
Terraform Data Sources
Data Sources allow you to fetch existing information or resources from a provider.
Example of a Data Source
Using Data Source in a Resource
Terraform Commands: Plan vs Apply
- terraform plan: Shows the changes Terraform will make to your infrastructure without actually applying them. Use for review and approval.
- terraform apply: Executes the changes proposed in the plan, creating, modifying, or destroying resources as necessary.
Count vs For_each in Terraform
- count: Creates multiple resources by a specified number.
Accessed using count.index.
- for_each: Creates resources based on a map or a set.
Accessed using each.key and each.value.
Debugging Errors in Terraform
- Enable Debug Logs: Set the TF_LOG environment variable.
- Log Output File: Redirect logs to a file for detailed review.
Validate Configurations: Use terraform validate to check for syntax errors.
Plan Execution: Run terraform plan to identify issues in execution plans.
Local-exec vs Remote-exec Provisioners
- local-exec: Executes commands on the machine running Terraform.
- remote-exec: Executes commands on a remote resource (e.g., an EC2 instance).
Null Resource in Terraform
A null_resource is a resource that doesnβt directly manage infrastructure but allows running provisioners and triggers.
Use Cases for Null Resource
- Execute local commands or scripts based on conditions.
- Handle non-infrastructure workflows.
Terraform fmt
terraform fmt: Formats Terraform configuration files to ensure consistent style.
Run it in the directory containing .tf files: terraform fmt
Importance of terraform fmt
Improves readability and standardizes configuration files.
Terraform Taint Command
terraform taint: Marks a resource as needing to be destroyed and recreated during the next terraform apply.
Use Case: When a resource is in an inconsistent state or needs to be updated due to external changes.
Difference Between terraform destroy and terraform apply -destroy
- terraform destroy: Deletes all the resources defined in the current state file.
- terraform apply -destroy: Combines terraform plan and terraform destroy into one command, showing a plan before destruction.
Rollback Changes in Terraform
- State Restoration: Restore a previous state backup if state file corruption occurs.
- Revert Code Changes: Revert to a previous commit in version control and reapply.
- Manual Correction: Edit configurations and use terraform plan to apply corrective changes.
Terraform Modules
Terraform Modules are a way to encapsulate resources for reuse.
Steps to Create a Module
Structure:
βββ main.tf βββ variables.tf βββ outputs.tf