Search code examples
amazon-ec2terraformssh-keysterraform-provider-aws

EC2 and key_pair - How to use different ssh_key


I build a little plateforme on AWS using Terraform script. There is, for now, one EC2 where I can ssh. I have filled the variable key_name in a aws_instance to do that.

How can I do to add another ssh_key if I want a colleague to ssh to the instance too ? key_name accept a string and not a list.

resource "aws_instance" "airflow" {
  ami                    = "ami-0d3f551818b21ed81"
  instance_type          = "t3a.xlarge"
  key_name               = "admin"
  vpc_security_group_ids = [aws_security_group.ssh-group.id, aws_security_group.airflow_webserver.id]
  tags = {
    "Name" = "airflow"
  }
  subnet_id = aws_subnet.subnet1.id
}

resource "aws_key_pair" "admin" {
  key_name   = "admin"
  public_key = file(var.public_key_path)
}

output "public_airflow_ip" {
  value = aws_instance.airflow.public_ip
}

Solution

  • The configuration through the API allows only for one keypair. However, you can manually (or via a script) add a second user account with their own keys. Please have a look at How do I add new user accounts with SSH access to my Amazon EC2 Linux instance?

    Having that said, it is recommended to log into the instances using AWS Systems Manager Session Manager instead of direct SSH. This way you can control access to the instances through IAM policies and don't need to expose the SSH port to the internet.