Terraform

Terraform is a powerful open-source tool designed for building, managing, and versioning infrastructure as code (IaC). Developed by HashiCorp, Terraform allows you to define your infrastructure in a declarative configuration language, enabling consistent and repeatable deployments across cloud providers and on-premises environments. With Terraform, you can provision and manage resources such as virtual machines, networks, and storage with ease, using a unified workflow that works across multiple platforms. Its state management and dependency resolution features ensure your infrastructure remains predictable and aligned with your desired configurations. Whether you’re deploying a small application or managing enterprise-scale infrastructure, Terraform simplifies the process and provides a scalable solution for modern DevOps practices.

Install

sudo dnf install terraform -y

Example

# Define provider (example: AWS)
provider "aws" {
  region = "us-east-1"
}

# Create a security group to allow HTTP and SSH access
resource "aws_security_group" "rocky_security_group" {
  name        = "rocky-nginx-sg"
  description = "Allow HTTP and SSH"

  ingress {
    description = "Allow SSH"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    description = "Allow HTTP"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

# Create a Rocky Linux EC2 instance
resource "aws_instance" "rocky_instance" {
  ami           = "ami-0c6b1d09930fac512" # Replace with a Rocky Linux AMI ID for your region
  instance_type = "t2.micro"
  key_name      = "your-ssh-key-name"      # Replace with your SSH key name
  security_groups = [aws_security_group.rocky_security_group.name]

  tags = {
    Name = "rocky-nginx-server"
  }

  provisioner "remote-exec" {
    inline = [
      "sudo yum install -y nginx",
      "sudo systemctl enable nginx",
      "sudo systemctl start nginx"
    ]

    connection {
      type        = "ssh"
      user        = "rocky"                # Default user for Rocky Linux AMI
      private_key = file("~/.ssh/your-ssh-key.pem") # Replace with your SSH key path
      host        = self.public_ip
    }
  }
}

# Output the public IP of the instance
output "instance_public_ip" {
  value = aws_instance.rocky_instance.public_ip
}