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.


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.



# create the docker group
  - docker

  - name: ubuntu
    groups: docker
    home: /home/ubuntu
    shell: /bin/bash
      - ssh-rsa YOUR_SSH_KEY_HERE

# Add default auto created user to docker group
    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 = [""]

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

# 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 = []

  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.


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