Software Engineering

How to create a Bastion server in Terraform


To create a Bastion server using Terraform, you need to define the necessary resources in a Terraform configuration file. Here’s an example of how you can create a Bastion server using Terraform:

# Define the security group
resource "aws_security_group" "bastion_sg" {
  name        = "bastion-security-group"
  description = "Bastion Security Group"
  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  vpc_id = "your-vpc-id"
}

# Define the Bastion instance
resource "aws_instance" "bastion_instance" {
  ami           = "your-ami-id"
  instance_type = "t2.micro"  # Update with the desired instance type
  key_name      = "your-key-pair-name"
  security_group_ids = [aws_security_group.bastion_sg.id]
  user_data     = <<-EOF
    #!/bin/bash
    echo "AllowTcpForwarding yes" >> /etc/ssh/sshd_config
    service sshd restart
    iptables -t nat -A PREROUTING -p tcp --dport 22 -j REDIRECT --to-port 2222
    iptables-save > /etc/sysconfig/iptables
    systemctl enable iptables
    systemctl restart iptables
    EOF
}

# Allocate an Elastic IP and associate it with the Bastion instance
resource "aws_eip" "bastion_eip" {
  instance = aws_instance.bastion_instance.id
}

In the Terraform configuration:

  1. The aws_security_group resource creates a security group allowing SSH access on port 22 from any IP address (0.0.0.0/0). Replace "your-vpc-id" with the ID of your VPC.
  2. The aws_instance resource creates an EC2 instance using the specified Amazon Machine Image (AMI) and instance type. Update "your-ami-id" with the ID of the desired AMI, and "your-key-pair-name" with the name of your EC2 key pair.
  3. The user_data block runs a series of commands on the Bastion instance to enable SSH forwarding, redirect SSH traffic from port 22 to 2222 (useful if you have other services already using port 22), and restart the necessary services.
  4. The aws_eip resource allocates an Elastic IP (EIP) and associates it with the Bastion instance, providing it with a static public IP address.

Make sure you have the necessary permissions to create EC2 instances, security groups, and EIPs in your AWS account before running Terraform. Adjust the configuration according to your specific requirements. Run terraform init, terraform plan, and terraform apply to provision the infrastructure based on the configuration.