Skip to content

Instantly share code, notes, and snippets.

@webgtx
Last active July 2, 2023 11:01
Show Gist options
  • Save webgtx/09dd2fbbb58f243e5482a713b712ea38 to your computer and use it in GitHub Desktop.
Save webgtx/09dd2fbbb58f243e5482a713b712ea38 to your computer and use it in GitHub Desktop.
Usage example for cloudinit in terraform on AWS

Add the cloud-init script to the Terraform configuration

Open the main.tf file. Notice how the template_file.user_data data block retrieves the contents of the add-ssh-web-app.yaml file. Then, it is passed into aws_instance.web as a user_data value to be initialized when the instance is created.

data "template_file" "user_data" {
  template = file("../scripts/add-ssh-web-app.yaml")
}

resource "aws_instance" "web" {
  ami                         = data.aws_ami.ubuntu.id
  instance_type               = "t2.micro"
  subnet_id                   = aws_subnet.subnet_public.id
  vpc_security_group_ids      = [aws_security_group.sg_22_80.id]
  associate_public_ip_address = true
  user_data                   = data.template_file.user_data.rendered

  tags = {
    Name = "Learn-CloudInit"
  }
}

add-ssh-web-app.yaml

##...
users:
  - default
  - name: terraform
    gecos: terraform
    primary_group: hashicorp
    sudo: ALL=(ALL) NOPASSWD:ALL
    groups: users, admin
    ssh_import_id:
    lock_passwd: false
    ssh_authorized_keys:
      -  # Paste your created SSH key here
##...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment