Programster's Blog

Tutorials focusing on Linux, programming, and open-source

AWS Cloud Init - Add SSH Access

Previously, we pasted a cloud-init configuration script in the "user data" form field in AWS in order to quickly spin up an AWS instance that would have docker installed. That cloud-init config works great, except when you want to use it inside Terraform, in which case it will deploy, but you won't be able to SSH into the server.

Below is an example terraform configuration, with a corresponding altered cloud-init configuration file, that will deploy an EC2 server that docker is installed on, and you can SSH into using your private key.

Steps

Copy the cloud configuration file below into a file called cloud-init.conf. Be sure to replace YOUR_SSH_KEY_HERE with your public ssh key.

If you don't have a public key for your private AWS key, you can generate it from the private key.

#cloud-config

packages:
  - docker.io

# create the docker group
groups:
  - docker

users:
  - name: ubuntu
    groups: docker
    home: /home/ubuntu
    shell: /bin/bash
    sudo: ALL=(ALL) NOPASSWD:ALL
    ssh-authorized-keys:
      - ssh-rsa YOUR_SSH_KEY_HERE

# Add default auto created user to docker group
system_info:
  default_user:
    groups: [docker]

Then copy the following terraform configuration file that will use the cloud-init config you just created:

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

# Create security group to allow port 8080
resource "aws_security_group" "instance" {
  name = "ssh-access"

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  # Allow the server to connect outwards. E.g. to apply updates etc.
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}


# Create the ubuntu 20.04 EC2 webserver resource 
# that uses the above security group
resource "aws_instance" "example" {
  ami                    = "ami-05c424d59413a2876"
  instance_type          = "t2.micro"
  vpc_security_group_ids = [aws_security_group.instance.id]

  user_data = file("./cloud-init.conf")

  tags = {
    Name = "terraform-example"
  }
}

Now if you run terraform init, and terraform apply, it will deploy an Ubuntu 20.04 EC2 instance that you can log into as the default ubuntu user, and the SSH key you specified. The instance will have docker installed and running.

References

Last updated: 2nd February 2024
First published: 28th September 2020

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch