Teraform
Terraform¶
Module: can be external or local. Used to import configurations
Note
Use sub directories for different environments
Tools:
- Organize Terraform better
Secret Management¶
https://aorith.github.io/posts/secrets-sops/
Examples¶
Simple AWS Configuration:
variable "aws_region" {
default = "us-west-2"
}
variable "instance_type" {
default = "t2.micro"
}
provider "aws" {
region = var.aws_region
}
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
tags = {
Name = "example-instance"
}
}
Multi-Cloud Config:
# Define providers for AWS, Azure, and GCP
provider "aws" {
region = "us-west-2"
}
provider "azurerm" {
features {}
}
provider "google" {
project = "my-gcp-project"
region = "us-central1"
}
# Define common variables for consistency
variable "vm_name" {
default = "multi-cloud-vm"
}
variable "vm_size" {
default = "small"
}
variable "admin_username" {
default = "clouduser"
}
variable "ssh_public_key" {
default = "your-public-key" # Replace with your actual SSH public key
}
variable "disk_size_gb" {
default = 20
}
# AWS Instance
resource "aws_instance" "aws_vm" {
ami = "ami-0c55b159cbfafe1f0" # Amazon Linux 2
instance_type = "t2.small"
key_name = "my-ssh-key" # Ensure this key exists in AWS
root_block_device {
volume_size = var.disk_size_gb
}
tags = {
Name = var.vm_name
}
}
# Azure VM
resource "azurerm_resource_group" "rg" {
name = "multi-cloud-rg"
location = "East US"
}
resource "azurerm_network_interface" "nic" {
name = "${var.vm_name}-nic"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
ip_configuration {
name = "internal"
private_ip_address_allocation = "Dynamic"
subnet_id = azurerm_subnet.subnet.id
}
}
resource "azurerm_linux_virtual_machine" "azure_vm" {
name = var.vm_name
resource_group_name = azurerm_resource_group.rg.name
location = azurerm_resource_group.rg.location
size = "Standard_B1s"
admin_username = var.admin_username
network_interface_ids = [azurerm_network_interface.nic.id]
admin_ssh_key {
username = var.admin_username
public_key = var.ssh_public_key
}
os_disk {
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
disk_size_gb = var.disk_size_gb
}
source_image_reference {
publisher = "Canonical"
offer = "UbuntuServer"
sku = "20.04-LTS"
version = "latest"
}
}
# GCP Instance
resource "google_compute_instance" "gcp_vm" {
name = var.vm_name
machine_type = "e2-small"
zone = "us-central1-a"
boot_disk {
initialize_params {
image = "ubuntu-os-cloud/ubuntu-2004-lts"
size = var.disk_size_gb
}
}
metadata = {
ssh-keys = "${var.admin_username}:${var.ssh_public_key}"
}
network_interface {
network = "default"
access_config {
}
}
}
# Output Public IPs
output "aws_public_ip" {
value = aws_instance.aws_vm.public_ip
}
output "azure_public_ip" {
value = azurerm_linux_virtual_machine.azure_vm.public_ip_address
}
output "gcp_public_ip" {
value = google_compute_instance.gcp_vm.network_interface.0.access_config.0.nat_ip
}