terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "5.74.0"
}
}
}
provider "aws" {
# Configuration options
}
provider "aws" {
region = "us-west-2"
access_key = "my-access-key"
secret_key = "my-secret-key"
}
# Using MSI installer (recommended)
# Download from: https://awscli.amazonaws.com/AWSCLIV2.msi
# Using winget
winget install Amazon.AWSCLI
# Using chocolatey
choco install awscli
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "5.74.0"
}
}
}
provider "aws" {
}
|
provider "aws" { resource "aws_instance" "server"{ tags = { |
|
provider "aws" { resource "aws_instance" "server"{ tags = { |
|
provider "aws" { tags = { |
resource "azurerm_storage_container" "example" {
name = "vhds"
storage_account_id = azurerm_storage_account.example.id
container_access_type = "private"
}
resource "azurerm_storage_blob" "example" {
name = "my-awesome-content.zip"
storage_account_name = azurerm_storage_account.example.name
storage_container_name = azurerm_storage_container.example.name
type = "Block"
source = "some-local-file.zip"
}

self.<ATTRIBUTE>. For example ${self.private_ip} will interpolate that resource's private IP address.name(arg, arg2, ...). For example, to read a file: ${file("path.txt")}.Outputs:
star_vpc_id = "vpc-0e450a7a8fab169ef"
Default Values (temporarily hide terraform.tfvars)
mv terraform.tfvars terraform.tfvars.backup
terraform plan
# Uses: environment = "staging" (from variables.tf default)
mv terraform.tfvars.backup terraform.tfvars # restore
2. Using terraform.tfvars (automatically loaded)
terraform plan
# Uses: environment = "demo" (from terraform.tfvars)
3. Command Line Override (highest precedence)
terraform plan -var="environment=production"
# Overrides tfvars: environment = "production"
4. Environment Variables
export TF_VAR_environment="staging-from-env"
terraform plan
# Uses environment variable (but command line still wins)
5. Using Different tfvars Files
terraform plan -var-file="dev.tfvars" # environment = "development"
terraform plan -var-file="production.tfvars" # environment = "production"
## ๐ Simple File Structure
โโโ main.tf # S3 bucket resource โโโ variables.tf # Input variables (2 simple variables) โโโ locals.tf # Local variables (tags and computed name) โโโ output.tf # Output variables (bucket details) โโโ provider.tf # AWS provider โโโ terraform.tfvars # Default variable values โโโ README.md # This file
## ๐งช Practical Examples
### Example 1: Testing Different Input Values
```bash
# Test with defaults (temporarily hide terraform.tfvars)
mv terraform.tfvars terraform.tfvars.backup
terraform plan
# Shows: Environment = "staging", bucket will be "staging-my-terraform-bucket-xxxxx"
# Test with terraform.tfvars
mv terraform.tfvars.backup terraform.tfvars
terraform plan
# Shows: Environment = "demo", bucket will be "demo-terraform-demo-bucket-xxxxx"
# Test with command line override
terraform plan -var="environment=test" -var="bucket_name=my-test-bucket"
# Shows: Environment = "test", bucket will be "test-my-test-bucket-xxxxx"
Example 2: Viewing All Variable Types in Action
# Apply the configuration
terraform apply -auto-approve
# See all outputs (shows output variables)
terraform output
# bucket_arn = "arn:aws:s3:::demo-terraform-demo-bucket-abc123"
# bucket_name = "demo-terraform-demo-bucket-abc123"
# environment = "demo" # (input variable)
# tags = { # (local variable)
# "Environment" = "demo"
# "Owner" = "DevOps-Team"
# "Project" = "Terraform-Demo"
# }
# See how local variables computed the bucket name
echo "Input: environment = $(terraform output -raw environment)"
echo "Input: bucket_name = terraform-demo-bucket (from tfvars)"
echo "Local: full_bucket_name = $(terraform output -raw bucket_name)"
echo "Random suffix was added by local variable!"
Example 3: Variable Precedence in Action
# Start with terraform.tfvars (environment = "demo")
terraform plan | grep Environment
# Shows: "Environment" = "demo"
# Override with environment variable
export TF_VAR_environment="from-env-var"
terraform plan | grep Environment
# Shows: "Environment" = "from-env-var"
# Override with command line (highest precedence)
terraform plan -var="environment=from-command-line" | grep Environment
# Shows: "Environment" = "from-command-line"
# Clean up
unset TF_VAR_environment
๐ง Try These Commands
# Initialize
terraform init
# Plan with defaults
terraform plan
# Plan with command line override
terraform plan -var="environment=test"
# Plan with different tfvars file
terraform plan -var-file="dev.tfvars"
# Apply and see outputs
terraform apply
terraform output
# Clean up
terraform destroy
resource "azurerm_resource_group" "RG" {
name = "star-RG"
location = "UK South"
}
resource "azurerm_subnet" "example" {
name = "example-subnet"
resource_group_name = azurerm_resource_group.example.name
virtual_network_name = azurerm_virtual_network.example.name
address_prefixes = ["10.0.1.0/24"]
delegation {
name = "delegation"
service_delegation {
name = "Microsoft.ContainerInstance/containerGroups"
actions = ["Microsoft.Network/virtualNetworks/subnets/join/action", "Microsoft.Network/virtualNetworks/subnets/prepareNetworkPolicies/action"]
}
}
}
resource "azurerm_network_interface" "example" {
name = "example-nic"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
ip_configuration {
name = "internal"
subnet_id = azurerm_subnet.example.id
private_ip_address_allocation = "Dynamic"
}
}
resource "azurerm_resource_group" "example" {
name = "example-resources"
location = "West Europe"
}
resource "azurerm_public_ip" "example" {
name = "acceptanceTestPublicIp1"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
allocation_method = "Static"
tags = {
environment = "Production"
}
}
resource "azurerm_network_security_group" "example" {
name = "acceptanceTestSecurityGroup1"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
security_rule {
name = "test123"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "*"
source_address_prefix = "*"
destination_address_prefix = "*"
}
tags = {
environment = "Production"
}
}
resource "azurerm_subnet_network_security_group_association" "example" {
subnet_id = azurerm_subnet.example.id
network_security_group_id = azurerm_network_security_group.example.id
}




After adding txt record go back to azure and click verify and once it is verified custom domain is configured.


resource "azurerm_windows_virtual_machine" "example" {
name = "example-machine"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
size = "Standard_F2"
admin_username = "adminuser"
admin_password = "P@$$w0rd1234!"
network_interface_ids = [
azurerm_network_interface.example.id,
]
os_disk {
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
}
source_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2016-Datacenter"
version = "latest"
}
}
resource "azurerm_managed_disk" "example" {
name = "${local.vm_name}-disk1"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
storage_account_type = "Standard_LRS"
create_option = "Empty"
disk_size_gb = 10
}
resource "azurerm_virtual_machine_data_disk_attachment" "example" {
managed_disk_id = azurerm_managed_disk.example.id
virtual_machine_id = azurerm_virtual_machine.example.id
lun = "10"
caching = "ReadWrite"
}
resource "azurerm_linux_virtual_machine" "example" {
name = "example-machine"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
size = "Standard_F2"
admin_username = "adminuser"
network_interface_ids = [
azurerm_network_interface.example.id,
]
admin_ssh_key {
username = "adminuser"
public_key = file("~/.ssh/id_rsa.pub")
}
os_disk {
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
}
source_image_reference {
publisher = "Canonical"
offer = "0001-com-ubuntu-server-jammy"
sku = "22_04-lts"
version = "latest"
}
}
resource "tls_private_key" "linuxprivatekey" {
algorithm = "RSA"
rsa_bits = 4096
}
resource "azurerm_linux_virtual_machine" "VM3" {
name = "star-VM3"
resource_group_name = local.resource_group_name
location = local.location
size = "Standard_D2s_v3"
admin_username = "abdul"
admin_password = "India123456789"
disable_password_authentication = false
network_interface_ids = [
azurerm_network_interface.NIC1.id,
]
source_image_reference {
publisher = "Canonical"
offer = "0001-com-ubuntu-server-jammy"
sku = "22_04-lts"
version = "latest"
}
os_disk {
storage_account_type = "Standard_LRS"
caching = "ReadWrite"
}
}



#Install IIS server role.
Install-WindowsFeature -name Star-WebServer -IncludeManagementTools
#Remove default html file
Remove-Item c:\inetpub\wwwroot\iisstart.htm
#Add a new html file that display server name
Add-Content -Path "C:\inetpub\wwwroot\iisstart.htm" -Value $("Welcome from " + $env:computername)
Enter required fields.






paste the following text into a vbs file:
Dim goal
Dim before
Dim x
Dim y
Dim i
goal = 2181818
Do While True
before = Timer
For i = 0 to goal
x = 0.000001
y = sin(x)
y = y + 0.00001
Next
y = y + 0.01
Loop


data "azurerm_virtual_network" "Vnet1" {
name = "Vnet1"
resource_group_name = "star-RG"
}
output "virtual_network_id" {
value = data.azurerm_virtual_network.example.id
}
resource "azurerm_key_vault" "example" {
name = "examplekeyvault"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
enabled_for_disk_encryption = true
tenant_id = data.azurerm_client_config.current.tenant_id
soft_delete_retention_days = 7
purge_protection_enabled = false
sku_name = "standard"
access_policy {
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = data.azurerm_client_config.current.object_id
key_permissions = [
"Get",
]
secret_permissions = [
"Get",
]
storage_permissions = [
"Get",
]
}
}
resource "azurerm_key_vault_secret" "example" {
name = "secret-sauce"
value = "szechuan"
key_vault_id = azurerm_key_vault.example.id
}
resource "azurerm_resource_group" "example" {
name = "example-resources"
location = "West Europe"
}
resource "azurerm_virtual_network" "example" {
name = "examplevnet"
address_space = ["192.168.1.0/24"]
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
}
resource "azurerm_subnet" "example" {
name = "AzureBastionSubnet"
resource_group_name = azurerm_resource_group.example.name
virtual_network_name = azurerm_virtual_network.example.name
address_prefixes = ["192.168.1.224/27"]
}
resource "azurerm_public_ip" "example" {
name = "examplepip"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
allocation_method = "Static"
sku = "Standard"
}
resource "azurerm_bastion_host" "example" {
name = "examplebastion"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
ip_configuration {
name = "configuration"
subnet_id = azurerm_subnet.example.id
public_ip_address_id = azurerm_public_ip.example.id
}
}
resource "azurerm_app_service_source_control_slot" "example" {
slot_id = azurerm_linux_web_app_slot.example.id
repo_url = "https://github.com/Azure-Samples/python-docs-hello-world"
branch = "master"
}
resource "azurerm_web_app_active_slot" "swap" {
slot_id = azurerm_windows_web_app_slot.devslot.id
}

resource "azurerm_log_analytics_workspace" "example" {
name = "acctest-01"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
sku = "PerGB2018"
retention_in_days = 30
}
resource "azurerm_application_insights" "example" {
name = "tf-test-appinsights"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
application_type = "web"
}




terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "5.74.0"
}
}
}
provider "aws" {
}
|
provider "aws" { resource "aws_instance" "server"{ tags = { |
|
provider "aws" { resource "aws_instance" "server"{ tags = { |
|
provider "aws" { tags = { |
resource "azurerm_storage_container" "example" {
name = "vhds"
storage_account_id = azurerm_storage_account.example.id
container_access_type = "private"
}
resource "azurerm_storage_blob" "example" {
name = "my-awesome-content.zip"
storage_account_name = azurerm_storage_account.example.name
storage_container_name = azurerm_storage_container.example.name
type = "Block"
source = "some-local-file.zip"
}

self.<ATTRIBUTE>. For example ${self.private_ip} will interpolate that resource's private IP address.name(arg, arg2, ...). For example, to read a file: ${file("path.txt")}.Outputs:
star_vpc_id = "vpc-0e450a7a8fab169ef"
Default Values (temporarily hide terraform.tfvars)
mv terraform.tfvars terraform.tfvars.backup
terraform plan
# Uses: environment = "staging" (from variables.tf default)
mv terraform.tfvars.backup terraform.tfvars # restore
2. Using terraform.tfvars (automatically loaded)
terraform plan
# Uses: environment = "demo" (from terraform.tfvars)
3. Command Line Override (highest precedence)
terraform plan -var="environment=production"
# Overrides tfvars: environment = "production"
4. Environment Variables
export TF_VAR_environment="staging-from-env"
terraform plan
# Uses environment variable (but command line still wins)
5. Using Different tfvars Files
terraform plan -var-file="dev.tfvars" # environment = "development"
terraform plan -var-file="production.tfvars" # environment = "production"
## ๐ Simple File Structure
โโโ main.tf # S3 bucket resource โโโ variables.tf # Input variables (2 simple variables) โโโ locals.tf # Local variables (tags and computed name) โโโ output.tf # Output variables (bucket details) โโโ provider.tf # AWS provider โโโ terraform.tfvars # Default variable values โโโ README.md # This file
## ๐งช Practical Examples
### Example 1: Testing Different Input Values
```bash
# Test with defaults (temporarily hide terraform.tfvars)
mv terraform.tfvars terraform.tfvars.backup
terraform plan
# Shows: Environment = "staging", bucket will be "staging-my-terraform-bucket-xxxxx"
# Test with terraform.tfvars
mv terraform.tfvars.backup terraform.tfvars
terraform plan
# Shows: Environment = "demo", bucket will be "demo-terraform-demo-bucket-xxxxx"
# Test with command line override
terraform plan -var="environment=test" -var="bucket_name=my-test-bucket"
# Shows: Environment = "test", bucket will be "test-my-test-bucket-xxxxx"
Example 2: Viewing All Variable Types in Action
# Apply the configuration
terraform apply -auto-approve
# See all outputs (shows output variables)
terraform output
# bucket_arn = "arn:aws:s3:::demo-terraform-demo-bucket-abc123"
# bucket_name = "demo-terraform-demo-bucket-abc123"
# environment = "demo" # (input variable)
# tags = { # (local variable)
# "Environment" = "demo"
# "Owner" = "DevOps-Team"
# "Project" = "Terraform-Demo"
# }
# See how local variables computed the bucket name
echo "Input: environment = $(terraform output -raw environment)"
echo "Input: bucket_name = terraform-demo-bucket (from tfvars)"
echo "Local: full_bucket_name = $(terraform output -raw bucket_name)"
echo "Random suffix was added by local variable!"
Example 3: Variable Precedence in Action
# Start with terraform.tfvars (environment = "demo")
terraform plan | grep Environment
# Shows: "Environment" = "demo"
# Override with environment variable
export TF_VAR_environment="from-env-var"
terraform plan | grep Environment
# Shows: "Environment" = "from-env-var"
# Override with command line (highest precedence)
terraform plan -var="environment=from-command-line" | grep Environment
# Shows: "Environment" = "from-command-line"
# Clean up
unset TF_VAR_environment
๐ง Try These Commands
# Initialize
terraform init
# Plan with defaults
terraform plan
# Plan with command line override
terraform plan -var="environment=test"
# Plan with different tfvars file
terraform plan -var-file="dev.tfvars"
# Apply and see outputs
terraform apply
terraform output
# Clean up
terraform destroy
resource "aws_default_vpc" "default" {
tags = {
Name = "Default VPC"
}
}
resource "aws_vpc" "VPC1" {
cidr_block = "10.0.0.0/16"
}
resource "aws_vpc" "VPC1" {
cidr_block = "10.0.0.0/16"
instance_tenancy = "default"
tags = {
Name = "VPC1"
}
}
resource "aws_subnet" "subnet1" {
vpc_id = aws_vpc.VPC1.id
cidr_block = "10.0.1.0/24"
tags = {
Name = "Subnet1"
}
}
resource "aws_security_group" "star-SG" {
name = "star-SG"
description = "Allow TLS inbound traffic and all outbound traffic"
vpc_id = aws_vpc.VPC1.id
tags = {
Name = "Allow Traffic"
}
}
resource "aws_vpc_security_group_ingress_rule" "Allow_443_Inbound_ipv4" {
security_group_id = aws_security_group.star-SG.id
cidr_ipv4 = aws_vpc.VPC1.cidr_block
from_port = 443
ip_protocol = "tcp"
to_port = 443
}
resource "aws_vpc_security_group_ingress_rule" "allow_443_Inbound_ipv6" {
security_group_id = aws_security_group.star-SG.id
cidr_ipv6 = aws_vpc.VPC1.ipv6_cidr_block
from_port = 443
ip_protocol = "tcp"
to_port = 443
}
resource "aws_vpc_security_group_egress_rule" "allow_all_traffic_ipv4" {
security_group_id = aws_security_group.allow_tls.id
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "-1" # semantically equivalent to all ports
}
resource "aws_vpc_security_group_egress_rule" "allow_all_traffic_ipv6" {
security_group_id = aws_security_group.allow_tls.id
cidr_ipv6 = "::/0"
ip_protocol = "-1" # semantically equivalent to all ports
}
resource "aws_security_group" "example" {
name = "sg"
vpc_id = aws_vpc.example.id
ingress = []
egress = []
}
resource "aws_internet_gateway" "gw" {
vpc_id = aws_vpc.main.id
tags = {
Name = "main"
}
}
resource "aws_route_table" "example" {
vpc_id = aws_vpc.example.id
route {
cidr_block = "10.0.1.0/24"
gateway_id = aws_internet_gateway.example.id
}
route {
ipv6_cidr_block = "::/0"
egress_only_gateway_id = aws_egress_only_internet_gateway.example.id
}
tags = {
Name = "example"
}
}
resource "aws_nat_gateway" "example" {
allocation_id = aws_eip.example.id
subnet_id = aws_subnet.example.id
tags = {
Name = "NAT-Gateway"
}
resource "aws_route_table" "example" {
vpc_id = aws_vpc.example.id
route {
cidr_block = "10.0.1.0/24"
gateway_id = aws_internet_gateway.example.id
}
tags = {
Name = "example"
}
}
resource "aws_route_table_association" "a" {
subnet_id = aws_subnet.foo.id
route_table_id = aws_route_table.bar.id
}
provider "aws" {
region = "eu-west-2"
access_key = "xxxxxxxx"
secret_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
resource "aws_instance" "Webserver" {
ami = "ami-0dbec48abfe298cab"
instance_type = "t2.micro"
key_name = "keypair1"
tags = {
Name = "WebServer"
}
}
provider "aws" {
region = "eu-west-2"
access_key = "xxxxxx"
secret_key = "xxxxxxxxxxxxxxxxxxxxx"
}
resource "aws_key_pair" "keypair1" {
key_name = "keypair1"
public_key = file("/root/test/tf1.pub")
resource "aws_instance" "server"{
ami = "ami-0dbec48abfe298cab"
instance_type = "t2.micro"
key_name = "aws_key_pair.keypair1"
tags = {
Name = "WebServer"
}
}
resource "aws_eip" "eip" {
instance = aws_instance.star-web.id
}
resource "aws_network_interface" "multi-ip" {
subnet_id = aws_subnet.main.id
private_ips = ["10.0.0.10", "10.0.0.11"]
}
resource "aws_eip" "one" {
domain = "vpc"
network_interface = aws_network_interface.multi-ip.id
associate_with_private_ip = "10.0.0.10"
}
resource "aws_eip" "two" {
domain = "vpc"
network_interface = aws_network_interface.multi-ip.id
associate_with_private_ip = "10.0.0.11"
}
resource "aws_eip_association" "eip_assoc" {
resource "aws_nat_gateway" "example" {
allocation_id = aws_eip.example.id
subnet_id = aws_subnet.example.id
tags = {
Name = "NAT-Gateway"
}
resource "aws_route_table" "example" {
vpc_id = aws_vpc.example.id
route {
cidr_block = "10.0.1.0/24"
gateway_id = aws_internet_gateway.example.id
}
tags = {
Name = "example"
}
}
resource "aws_route_table_association" "a" {
subnet_id = aws_subnet.foo.id
route_table_id = aws_route_table.bar.id
}
resource "aws_ami" "example" {
name = "terraform-example"
virtualization_type = "hvm"
root_device_name = "/dev/xvda"
imds_support = "v2.0" # Enforce usage of IMDSv2. You can safely remove this line if your application explicitly doesn't support it.
ebs_block_device {
device_name = "/dev/xvda"
snapshot_id = "snap-xxxxxxxx"
volume_size = 8
}
}
resource "aws_ami_from_instance" "example" {
name = "terraform-example"
source_instance_id = "i-xxxxxxxx"
}
resource "aws_ami_copy" "example" {
name = "terraform-example"
source_ami_id = "ami-xxxxxxxx"
source_ami_region = "us-west-1"
tags = {
Name = "HelloWorld"
}
}
resource "aws_ami_launch_permission" "example" {
image_id = "ami-12345678"
account_id = "123456789012"
}
resource "aws_ami_launch_permission" "example" {
image_id = "ami-12345678"
group = "all"
}
data "aws_organizations_organization" "current" {}
resource "aws_ami_launch_permission" "example" {
image_id = "ami-12345678"
organization_arn = data.aws_organizations_organization.current.arn
}
[bucket_name]--[azid]--x-s3. Use the aws_s3_directory_bucket resource to manage S3 Express buckets.It should be define in terraform block
backend "s3" {
bucket = "star-s3-bucket"
key = "dev/terraform.tfstate"
region = "eu-west-2"
}
Multiple .tf files to create infrastrcture.
Project1: creation of VPC, Subnets, IGW, SG, RT, Instance, Key pair, EIP.
| variable "accesskey" { type = string default = "AKIAX2XVEK27GJNREDX4" } variable "secretkey" { type = string default = "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" } variable "region" { type = string default = "eu-west-2" } |
provider "aws" { access_key = var.accesskey secret_key = var.secretkey region = var.region } |
resource "aws_vpc" "star_vpc" { tags = { tags = { tags = { ingress { tags = { tags = { resource "aws_route_table" "star_rt" { route { route { |
resource "aws_key_pair" "tf1" { tags = { tags = { resource "aws_eip" "star_eip" { tags = { |
Loop: Create 3 subnets in different availability zones using terraform loop, count, element and length:
|
variable "vpccidr" {
type = string
default = "10.0.0.0/16"
}
variable "publicsubnet" {
type = string
default = "10.0.1.0/24"
}
variable "privatesubnet"{
type = list
default = ["10.0.2.0/24","10.0.3.0/2","10.0.4.0/24"]
}
|
resource "aws_vpc" "star_vpc" {
cidr_block = var.vpccidr
instance_tenancy = "default"
tags = {
Name = "star_vpc"
}
}
resource "aws_subnet" "publicsubnet" {
vpc_id = aws_vpc.star_vpc.id
tags = {
Name = "public_subnet"
}
}
resource "aws_subnet" "privatesubnet" {
vpc_id = aws_vpc.star_vpc.id
cidr_block = element(var.privatesubnet,count.index)
count = 3 #to define tag name to every subnet
tags = {
Name = "private_subnet-count.index+1"
}
}
|
Defining Availability Zones for multiple subnets: 3 subnets and 3 availability zone:
|
variable "vpccidr" {
type = string
default = "10.0.0.0/16"
}
variable "publicsubnet" {
type = string
default = "10.0.1.0/24"
}
variable "privatesubnet"{
type = list
default = ["10.0.2.0/24","10.0.3.0/2","10.0.4.0/24"]
}
variable "az" {
type = list
default = ["eu-west2a", "eu-west-2b","eu-west-2c"]
|
resource "aws_vpc" "star_vpc" {
cidr_block = var.vpccidr
instance_tenancy = "default"
tags = {
Name = "star_vpc"
}
}
resource "aws_subnet" "publicsubnet" {
vpc_id = aws_vpc.star_vpc.id
tags = {
Name = "public_subnet"
}
}
resource "aws_subnet" "privatesubnet" {
count = length(var.az)
vpc_id = aws_vpc.star_vpc.id
cidr_block = element(var.privatesubnet,count.index)
#to define tag name to every subnet
tags = {
Name = "private_subnet-${count.index+1}"
}
}
|
Data Sources: Based on region the availability zone should be picked using source data.
|
variable "vpccidr" {
type = string
default = "10.0.0.0/16"
}
variable "publicsubnet" {
type = string
default = "10.0.1.0/24"
}
variable "privatesubnet"{
type = string
default = ["10.0.2.0/24","10.0.3.0/2","10.0.4.0/24"]
}
#variable "az" {
# type = list
# default = ["eu-west-2a","eu-west-2b","eu-west-2c"]
#}
#Declare the data source
data "aws_availability_zones" "az" {
}
|
resource "aws_vpc" "star_vpc" {
cidr_block = var.vpccidr
instance_tenancy = "default"
tags = {
Name = "star_vpc"
}
}
resource "aws_subnet" "publicsubnet" {
vpc_id = aws_vpc.star_vpc.id
tags = {
Name = "public_subnet"
}
}
resource "aws_subnet" "privatesubnet" {
vpc_id = aws_vpc.star_vpc.id
cidr_block = element(var.privatesubnet,count.index)
availability_zone = element(data.aws_availability_zones.az.names,count.index)
count = length(data.aws_availability_zones.az.names)
tags = {
Name = "private_subnet-count.index+1"
}
}
|
Defining Load Balancer: click for AWS_LoadBalancer,
Elastic Load Balancer in AWS supports the following load balancers:
Application LB: Link for tutorial,
Lab Setup: variable, provider, VPC, IGW, Securitygroup, instances, install_httpd.sh, alb
ALB key words:
ELB: Elastic Load Balancer: link for turorial,
Lab setup: created the following files: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lb
Files: provider, variable, instances, vpc, igw, securitygroup, httpd_insall.sh, classicELB
Things to define in ELB (classic Load Balancer, VPC ELB)
Output Value: When infra is created and you want to see values assigned by provider, example: resource IDs, Public IP, Private IP etc..
https://www.terraform.io/docs/language/values/outputs.html
Syntax of output: During resource creation the required output value will be displayed.
|
#Syntax: #Add the below code in the source file. #If you have multiple servers or resources. output "publicIP" |
Once the resource is created and want to display the output value:
Get console: run command at the terraform folder prompt # terraform console
> aws_instance.webserver.*.public_ip
You can display any attribute (attribute is output value generated by resouce provider)
> aws_instance.webserver.id
Variable defined in a file: To set lots of variables, it is more convenient to specify their values in a variable definitions file (with a filename ending in either .tfvars or .tfvars.json) and then specify that file on the command line with -var-file:
variable.tfvars
Method1`: Create AMI with snapshot of an instance. (To create an snapshot> got to volume and create snapshot)
Volume => snapshot => AMI
Instance => AMI
|
provider "aws" { ebs_block_device { |
Copy AMI to different Region: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ami_copy
|
provider "aws" { tags = { |
Method2: Create AMI from Instance: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ami_from_instance
| provider "aws" { access_key = "AKIAX2XVEK27GJNREDX4" secret_key = "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" region = "eu-west-2" } resource "aws_ami_from_instance" "terraform_ami2" { name = "terraform_ami2" source_instance_id = "i-0b31e653a4e810c4a" } |
AMI Launch Permission: Give AMI access to other account ID: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ami_launch_permission
| provider "aws" { access_key = "AKIAX2XVEK27GJNREDX4" secret_key = "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" region = "eu-west-2" } resource "aws_ami_launch_permission" "terraform_eu-west-2" { image_id = "ami-0371f85fc88e9007c" account_id = "723581589149" } |
1. Create EBS Volume: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ebs_volume
|
provider "aws" { tags = { |
2. Increase size of volume to 20 GB.
|
provider "aws" { tags = { |
3. Create snapshot from volume: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ebs_snapshot
|
provider "aws" { resource "aws_ebs_volume" "terraform-server_volume" { tags = { tags = { |
4. Copy snapshot to different region: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ebs_snapshot_copy
|
provider "aws" {
tags = { |
|
provider "aws" { variable "instance_type" { variable input {} resource "aws_instance" "dev" { |
|
provider "aws" { variable "instance_type" { variable input {} resource "aws_instance" "dev" { tags = { resource "aws_instance" "test" { tags = { tags = { |
Local Value: used for tag names for all resources.
|
locals
provider "aws" { locals { tags = local.common_tag } tags = local.common_tag resource "aws_ebs_volume" "ebs_volume" { tags = local.common_tag |
with tags provider "aws" { resource "aws_vpc" "star_vpc" { tags = { tags = { tags = { |
For multiple departments or branches: if you need to change the name then change it in variable which will reflect in all resources.
|
provider "aws" { locals { resource "aws_vpc" "star_vpc" { tags = local.common_tag } tags = local.common_tag resource "aws_ebs_volume" "ebs_volume" { tags = local.common_tag
tags = local.hr_tag } tags = local.hr_tag resource "aws_ebs_volume" "ebs_volume1" { tags = local.hr_tag |
Terraform State Management: shared storage of sate file locally, shared storage of state file remotely, staging and production environment.
Shared storage of terraform.tfstate file Locally:

Shared storage of state file remotely:
code:
|
provider "aws" { tags = { tags = { |
Staging and Production Environment:
Manual Method 1 and Method 2:
Method 3 = Terraform workspace:
Project2: provision of instance and Apache configuration in AWS through terraform using file:
|
provider "aws" { resource "aws_key_pair" "tf1" {
tags = { |
IAM: user creation
Example1: Creating IAM user only and user ARN output..
Files: variable, provider, users, output
|
variable "accesskey" { variable "secretkey" { variable "region" { variable "username" { |
provider "aws" { access_key = var.accesskey secret_key = var.secretkey region = var.region } |
#1. syntax to create a user tags = { #2. syntax to create multiple users using count index resource "aws_iam_user" "newuser" { tags = {
resource "aws_iam_user" "newuser" { tags = { }
|
output "user_arn" { |
Example2: Creating IAM policy only with ec2 describe permissio:
Files: policy1
|
resource "aws_iam_policy" "policy1" { policy = <<EOF |
Example3: Lets attach the above policy1(ec2-describe) policy to both users created in example1.
Files: variable, provider, users, output, policy1, policy_attach
| resource "aws_iam_policy_attachment" "policy1-attachment" { name = "policy1-attachment" users = aws_iam_user.newuser.*.name policy_arn = aws_iam_policy.policy1.arn } |
Login with the above created users, users can describe or display instances.