Usage examples
![[Pasted image 20260412170422.png]]
tofu init
tofu apply
# aws_instance = resource_type
# my_instance = resource_name
resource "aws_instance" "my_instance" {
ami = var.AMIS[var.AWS_REGION]
instance_type = "t2.micro"
}
resource "aws_instance" "imported_instance" {
ami = "ami-0ea87431b78a82070"
instance_type = "t3.micro"
}
# tofu apply same as:
# tofu import aws_instance.imported_instance i-0c7f0f4eb9bdea3b7
import {
to = aws_instance.imported_instance
id = "i-0c7f0f4eb9bdea3b7"
}
terraform {
backend "s3" {
bucket = "<bucket_name>"
key = "terraform.tfstate"
region = "us-east-1"
dynamodb_table = "<table_name>"
encrypt = false
profile = "default"
}
}
variable "AWS_REGION" {
default = "us-east-1"
}
variable "AMIS" {
type = map(any)
default = {
us-east-1 = "ami-05b10e08d247fb927"
}
}
provider "aws" {
profile = "default"
region = var.AWS_REGION
}
resource "aws_key_pair" "my_ssh_key" {
key_name = "my_ssh_key"
public_key = file("./my_ssh_key.pub")
}
resource "aws_instance" "loadbalancer" {
ami = lookup(var.AMIS, var.AWS_REGION)
instance_type = "t2.micro"
vpc_security_group_ids = [aws_security_group.allow_ssh_http.id]
key_name = aws_key_pair.my_ssh_key.key_name
tags = {
Name = "my_instance"
}
}
resource "aws_instance" "webserver-1" {
ami = lookup(var.AMIS, var.AWS_REGION)
instance_type = "t2.micro"
vpc_security_group_ids = [aws_security_group.allow_ssh_http.id]
key_name = aws_key_pair.my_ssh_key.key_name
tags = {
Name = "my_instance"
}
}
resource "aws_instance" "webserver-2" {
ami = lookup(var.AMIS, var.AWS_REGION)
instance_type = "t2.micro"
vpc_security_group_ids = [aws_security_group.allow_ssh_http.id]
key_name = aws_key_pair.my_ssh_key.key_name
tags = {
Name = "my_instance"
}
}
resource "aws_security_group" "allow_ssh_http" {
name = "allow_ssh_http"
description = "security group allowing SSH/HTTP connections from all IPs to VM"
tags = {
Name = "allow_ssh_http"
}
}
resource "aws_vpc_security_group_ingress_rule" "allow_ssh" {
security_group_id = aws_security_group.allow_ssh_http.id
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "tcp"
from_port = 22
to_port = 22
}
resource "aws_vpc_security_group_ingress_rule" "allow_http" {
security_group_id = aws_security_group.allow_ssh_http.id
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "tcp"
from_port = 80
to_port = 80
}
resource "aws_vpc_security_group_egress_rule" "allow_all_traffic_ipv4" {
security_group_id = aws_security_group.allow_ssh_http.id
cidr_ipv4 = "0.0.0.0/0" # all IPs
ip_protocol = "-1" # semantically equivalent to all ports
}
output "loadbalancer_connection_information" {
value = {Public_IP = aws_instance.loadbalancer.public_ip, Public_DNS = aws_instance.loadbalancer.public_dns}
}
output "webserver-1_connection_information" {
value = {Public_IP = aws_instance.webserver-1.public_ip, Public_DNS = aws_instance.webserver-1.public_dns}
}
output "webserver-2_connection_information" {
value = {Public_IP = aws_instance.webserver-2.public_ip, Public_DNS = aws_instance.webserver-2.public_dns}
}