Answer:
Infrastructure as Code (IaC) is a method of managing and provisioning infrastructure using code instead of manual processes. It allows:
✅ Automation of infrastructure deployment
✅ Consistency by reducing human errors
✅ Scalability through repeatable scripts
Answer:
Terraform is an open-source IaC tool by HashiCorp that helps define and provision infrastructure using a declarative configuration language. It follows three steps:
- Write: Define infrastructure in
.tffiles - Plan: Preview changes before applying
- Apply: Deploy and manage resources
Example:
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "my_instance" {
ami = "ami-12345678"
instance_type = "t2.micro"
}Answer:
| Feature | Terraform | Ansible |
|---|---|---|
| Type | Declarative | Imperative |
| Purpose | Infrastructure provisioning | Configuration management |
| State Management | Uses state file | Stateless |
| Example Use | Creating VMs, Networks | Installing software, configuring OS |
Answer:
Providers are plugins that allow Terraform to manage resources on different platforms (AWS, Azure, GCP, Kubernetes, etc.).
Example:
provider "aws" {
region = "us-west-2"
}Answer:
Terraform maintains infrastructure details in a state file (terraform.tfstate), which:
✅ Tracks existing resources
✅ Enables incremental changes
✅ Supports remote storage (e.g., S3, Azure Blob)
To store state remotely:
backend "s3" {
bucket = "my-terraform-state"
key = "terraform.tfstate"
region = "us-east-1"
}Answer:
It initializes the working directory by:
✅ Downloading providers
✅ Setting up backend storage
✅ Validating configuration
Command:
terraform initAnswer:
Terraform uses implicit and explicit dependencies:
- Implicit: Recognized automatically
- Explicit: Defined using
depends_on
Example:
resource "aws_instance" "web" {
ami = "ami-12345678"
instance_type = "t2.micro"
}
resource "aws_ebs_volume" "data" {
size = 10
availability_zone = "us-east-1a"
depends_on = [aws_instance.web]
}Answer:
| Command | Purpose |
|---|---|
terraform plan |
Shows proposed changes before applying |
terraform apply |
Executes changes to create/update resources |
Answer:
A module is a reusable collection of Terraform configurations that helps organize code.
Example of a module (main.tf):
module "network" {
source = "./modules/vpc"
}Answer:
Use:
terraform destroyThis removes all resources defined in the configuration.
Answer:
Ansible is an open-source configuration management tool that automates tasks like software installation, updates, and deployments. It works agentless, using SSH or WinRM.
Answer:
A playbook is a YAML-based automation script that defines tasks to be executed.
Example (playbook.yml):
- name: Install Nginx
hosts: web
tasks:
- name: Install Nginx
apt:
name: nginx
state: presentAnswer:
The inventory file lists managed servers and their details.
Example (inventory.ini):
[web]
server1 ansible_host=192.168.1.10
server2 ansible_host=192.168.1.11Answer:
| Feature | Playbook | Role |
|---|---|---|
| Scope | Task-oriented | Component-oriented |
| Organization | Single YAML file | Structured directory |
| Usage | Small-scale automation | Large-scale projects |
Answer:
Command:
ansible-playbook playbook.yml -i inventory.iniAnswer:
Ansible Galaxy is a repository for pre-built Ansible roles.
Example:
ansible-galaxy install geerlingguy.nginxAnswer:
Ansible ensures repeated executions produce the same result by only applying changes when needed.
Example:
- name: Ensure Nginx is installed
apt:
name: nginx
state: presentIf Nginx is already installed, the task is skipped.
Answer:
Ansible Vault encrypts sensitive data like passwords.
To create an encrypted file:
ansible-vault encrypt secrets.ymlAnswer:
AWS CloudFormation is an IaC service that provisions AWS infrastructure using YAML/JSON templates.
Example:
Resources:
MyBucket:
Type: "AWS::S3::Bucket"Answer:
Command:
aws cloudformation create-stack --stack-name my-stack --template-body file://template.ymlAnswer:
Terraform state can be stored locally (on disk) or remotely (in S3, Consul, etc.).
| Storage | Pros | Cons |
|---|---|---|
Local State (terraform.tfstate) |
Fast, simple | Not suitable for teams |
| Remote State (S3, etc.) | Shared, secure | Slightly slower |
Example remote state (S3 backend):
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
}
}Answer:
Avoid hardcoding secrets in .tf files:
✅ Use environment variables
✅ Use Terraform Vault Provider
✅ Store secrets in AWS Secrets Manager
Example using environment variables:
export TF_VAR_db_password="mypassword"Answer:
Terraform uses state locking to prevent simultaneous updates by multiple users.
- Enabled automatically for remote state backends (e.g., S3 + DynamoDB).
Example (DynamoDB locking):
backend "s3" {
bucket = "my-terraform-bucket"
dynamodb_table = "terraform-lock"
}Answer:
Terraform Workspaces allow managing multiple environments within a single configuration.
terraform workspace new dev
terraform workspace select devAnswer:
Modules help organize and reuse code.
Example (modules/network/main.tf):
variable "vpc_cidr" {}
resource "aws_vpc" "main" {
cidr_block = var.vpc_cidr
}Usage:
module "vpc" {
source = "./modules/network"
vpc_cidr = "10.0.0.0/16"
}Answer:
| Feature | Terraform Cloud | Terraform Enterprise |
|---|---|---|
| Type | SaaS | Self-hosted |
| Use Case | Collaboration, remote state | Large enterprises |
| Extras | Remote execution, VCS integration | Advanced security & governance |
Answer:
Terraform detects drift by running:
terraform planDrift occurs when actual infrastructure changes outside Terraform’s control.
Answer:
countis used for simple lists.for_eachis used for maps or sets.
Example (count):
resource "aws_instance" "web" {
count = 3
ami = "ami-12345678"
}Example (for_each):
resource "aws_s3_bucket" "buckets" {
for_each = toset(["dev", "prod"])
bucket = "my-app-${each.value}"
}Answer:
Variables can be defined in:
✅ Playbooks (vars:)
✅ Inventory (host_vars, group_vars)
✅ Command-line (-e flag)
Example:
- hosts: web
vars:
app_port: 8080
tasks:
- debug: msg="App runs on port {{ app_port }}"Answer:
Facts are system information collected automatically.
Example:
ansible all -m setupAnswer:
Handlers run only when notified.
Example:
- name: Install Nginx
apt:
name: nginx
notify: Restart Nginx
- name: Restart Nginx
service:
name: nginx
state: restarted
listen: Restart NginxAnswer:
Ansible Roles handle dependencies using meta/main.yml.
Example:
dependencies:
- role: commonAnswer:
| Module | When to Use | Example |
|---|---|---|
command |
Runs a command without shell features | ansible all -m command -a "ls" |
shell |
Runs commands with shell features (` | ,&&`) |
Answer:
Dynamic Inventory fetches live host lists from AWS, Azure, GCP.
Example for AWS:
ansible-inventory --list -i aws_ec2.ymlAnswer:
| Component | Description |
|---|---|
| Templates | Defines resources in YAML/JSON |
| Stacks | Collection of AWS resources |
| StackSets | Deploy stacks across multiple accounts |
Answer:
Use:
aws cloudformation update-stack --stack-name my-stack --template-body file://template.ymlAnswer:
| Feature | Purpose |
|---|---|
DependsOn |
Ensures a resource is created before another |
CreationPolicy |
Waits for a signal before marking as successful |
Example (DependsOn):
Resources:
WebServer:
Type: AWS::EC2::Instance
DependsOn: MyDBAnswer:
Conditions allow resources to be created based on parameters.
Example:
Conditions:
IsProd: !Equals [!Ref EnvType, "Prod"]
Resources:
MyBucket:
Type: AWS::S3::Bucket
Condition: IsProdAnswer:
Detects manual changes to resources outside CloudFormation.
Run drift check:
aws cloudformation detect-stack-drift --stack-name my-stackAnswer:
Intrinsic functions dynamically reference values.
Example (!Sub for string interpolation):
Resources:
MyBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "${AWS::AccountId}-my-bucket"Answer:
Terraform can be integrated into CI/CD pipelines using GitHub Actions, GitLab CI, or Jenkins.
✅ Linting & Validation: terraform fmt, terraform validate
✅ Planning: terraform plan -out=tfplan
✅ Apply Changes: terraform apply tfplan
Example GitHub Actions workflow:
jobs:
terraform:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Setup Terraform
uses: hashicorp/setup-terraform@v1
- name: Terraform Init
run: terraform init
- name: Terraform Plan
run: terraform plan -out=tfplan
- name: Terraform Apply
run: terraform apply tfplanAnswer:
Data sources allow Terraform to query external resources without managing them.
Example:
data "aws_vpc" "existing_vpc" {
filter {
name = "tag:Name"
values = ["my-vpc"]
}
}Answer:
Use version constraints in source.
Example (versions.tf):
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "3.5.0"
}Answer:
Terraform detects and prevents circular dependencies by analyzing the DAG (Directed Acyclic Graph).
Solution:
✅ Use depends_on explicitly
✅ Refactor resources
Example:
resource "aws_instance" "web" {
depends_on = [aws_s3_bucket.logs]
}Answer:
locals: Store temporary valuesoutput: Expose values after deployment
Example:
locals {
env_name = "dev"
}
output "instance_ip" {
value = aws_instance.web.public_ip
}Answer:
Sentinel is a policy-as-code framework that enforces compliance.
Example policy (enforce_cost.sentinel):
import "tfplan"
main = rule { tfplan.cost_estimate.total_monthly_cost < 500 }Answer:
-
Option 1: Use version control (
git revert) -
Option 2: Manually restore the previous state
-
Option 3: Import last known working state:
terraform apply "tfstate-previous.json"
Answer:
terraform refresh updates the state file without modifying resources.
terraform refreshAnswer:
✅ Use IAM least privilege for Terraform executions
✅ Store state files securely (S3 + DynamoDB)
✅ Run security scans with tools like tfsec
Example:
tfsec .Answer:
By using multiple providers in a single configuration.
Example (AWS + Azure):
provider "aws" {
region = "us-east-1"
}
provider "azurerm" {
features {}
}Answer:
✅ Use ansible-lint for syntax validation
✅ Use Molecule for testing
Example:
molecule testAnswer:
Use ignore_errors: yes or rescue blocks.
Example:
tasks:
- name: Try to restart service
service:
name: nginx
state: restarted
ignore_errors: yesAnswer:
Use environment variables to decrypt secrets.
Example:
ANSIBLE_VAULT_PASSWORD="myvaultpassword" ansible-playbook deploy.ymlAnswer:
✅ Use the k8s module
✅ Define Kubernetes manifests in YAML
Example:
- name: Deploy to Kubernetes
k8s:
state: present
definition: "{{ lookup('file', 'deployment.yml') }}"Answer:
✅ Always use state: present
✅ Run playbooks multiple times to check consistency
Example:
- name: Ensure Nginx is installed
apt:
name: nginx
state: presentAnswer:
✅ Use Nested Stacks
✅ Use AWS::CloudFormation::Stack
Example:
Resources:
MyNetworkStack:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: "https://s3.amazonaws.com/my-bucket/network.yml"Answer:
Use the --parameters flag during updates.
Example:
aws cloudformation update-stack --stack-name my-stack \
--parameters ParameterKey=InstanceType,ParameterValue=t2.largeAnswer:
✅ Use Stack Policies to prevent deletions
✅ Enable RetainPolicy for S3, RDS
Example:
Resources:
MyBucket:
Type: AWS::S3::Bucket
DeletionPolicy: RetainAnswer:
A Stack Policy prevents accidental updates or deletions.
Example:
{
"Statement": [
{
"Effect": "Deny",
"Action": "Update:Delete",
"Principal": "*",
"Resource": "*"
}
]
}Answer:
✅ Check the CloudFormation console
✅ Use aws cloudformation describe-stack-events
✅ Enable rollback debugging
Example:
aws cloudformation describe-stack-events --stack-name my-stack💡 Want to contribute?
We welcome contributions! If you have insights, new tools, or improvements, feel free to submit a pull request.
📌 How to Contribute?
- Read the CONTRIBUTING.md guide.
- Fix errors, add missing topics, or suggest improvements.
- Submit a pull request with your updates.
📢 Stay Updated:
⭐ Star the repository to get notified about new updates and additions.
💬 Join discussions in GitHub Issues to suggest improvements.
🔗 GitHub: @NotHarshhaa
📝 Blog: ProDevOpsGuy
💬 Telegram Community: Join Here
