Software Engineering

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"
    Type: AWS::EC2::SecurityGroup
      GroupDescription: Bastion Security Group
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
      VpcId: "your-vpc-id"
    Type: AWS::EC2::Instance
      ImageId: "your-ami-id"
      InstanceType: "t2.micro"  # Update with the desired instance type
        - !Ref BastionSecurityGroup
      KeyName: "your-key-pair-name"
        Fn::Base64: !Sub |
          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
    Type: AWS::EC2::EIP
      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 ( 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.