amazon-web-servicesamazon-ec2terraformaws-ec2-instance-connect

Cannot ping and ssh login to the ec2 instances after login to bastion host


I use the module "terraform-aws-modules/vpc/aws" and "terraform-aws-modules/ec2-instance/aws" provisioned VPC and ec2 instances. See the code below. I am able to ssh login to the bastion host via bastion host public ip. Inside bastion host, I am not able to ping and ssh login to other ec2 instances of their private ip. I added security group, sg_ssh to the ec2 instances. But, I still cannot logon to the ec2 instances from bastion host. Is the sg_ssh correct?

main.tf 
# Terraform configuration

provider "aws" {
  region = "us-west-2"
}

resource "aws_security_group" "sg_ssh" {
  vpc_id      = module.vpc.vpc_id
  name        = "sg_ssh"
  ingress {
    from_port   = "22"
    to_port     = "22"
    protocol    = "tcp"
    cidr_blocks = ["30.0.0.0/16"]
  }
  tags = {
    Name = "sg_ssh"
  }
}

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "2.21.0"

  name = var.vpc_name
  cidr = var.vpc_cidr

  azs             = var.vpc_azs
  private_subnets = var.vpc_private_subnets
  public_subnets  = var.vpc_public_subnets

  enable_nat_gateway = var.vpc_enable_nat_gateway

  tags = var.vpc_tags
}

module "ec2_instances" {
  source  = "terraform-aws-modules/ec2-instance/aws"
  version = "2.12.0"

  name           = "my-ec2-cluster"
  instance_count = 2

  ami                    = "ami-0c5204531f799e0c6"
  instance_type          = "t2.micro"
  vpc_security_group_ids = [module.vpc.default_security_group_id, aws_security_group.sg_ssh.id]
  subnet_id              = module.vpc.public_subnets[0]

  tags = {
    Terraform   = "true"
    Environment = "dev"
  }
}

# Bastion
resource "aws_security_group" "allow-ssh" {
  vpc_id      = module.vpc.vpc_id
  name        = "allow-ssh"
  description = "security group that allows ssh and all egress traffic"
  egress {
    from_port   = "0"
    to_port     = "0"
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = "22"
    to_port     = "22"
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  tags = {
    Name = "allow-ssh"
  }
}

resource "aws_instance" "bastion_instance" {
  ami                = "ami-0c5204531f799e0c6"
  instance_type      = "t2.micro"
  subnet_id          = module.vpc.public_subnets[0]
  vpc_security_group_ids = [aws_security_group.allow-ssh.id]

  key_name               = var.key_name

  tags = {
    Name = "bastion_instance"
  }
}

Solution

  • You have not added ssh ingress to the ec2's.

    in the ec2 module:

    vpc_security_group_ids = [module.vpc.default_security_group_id]
    

    You are only registering them with the default vpc security group, which is likely not configured to permit ssh.

    You will need to create a security group that permits ssh from the bastion, and attach this to your ec2s.