How to Create a Bastion Server in CloudFormation


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

AWSTemplateFormatVersion: "2010-09-09"
Resources:
  BastionSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Bastion Security Group
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0
      VpcId: "your-vpc-id"
  BastionInstance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: "your-ami-id"
      InstanceType: "t2.micro"  # Update with the desired instance type
      SecurityGroupIds:
        - !Ref BastionSecurityGroup
      KeyName: "your-key-pair-name"
      UserData:
        Fn::Base64: !Sub |
          #!/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
  BastionEIP:
    Type: AWS::EC2::EIP
    Properties:
      InstanceId: !Ref BastionInstance

In the CloudFormation template:

  1. The BastionSecurityGroup resource creates a security group allowing SSH access on port 22 from any IP address (0.0.0.0/0). Make sure to replace "your-vpc-id" with the ID of your VPC.
  2. The BastionInstance 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 UserData property 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 BastionEIP resource associates an Elastic IP (EIP) 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 deploying this CloudFormation template. Adjust the template according to your specific requirements.