Bootstrapping EC2 in Terraform: hide secrets in user_data

Posted: March 14, 2019 in terraform

In case we need to pass some credentials to template file, these secrets are seen as pain text in User Data section, to “encrypt” UserData section we can use base64 encoding.

cloudinit.tf

data "template_file" "myuserdata" {
template = "${file("./vpn_01.tpl")}"
vars = {
aws_access_key_id = "${var.aws_access_key_id}"
secret_access_key_id = "${var.secret_access_key_id}"
}
}

data "template_cloudinit_config" "config" {
gzip = true
base64_encode = true

# Main cloud-config configuration file.
part {
content_type = "text/x-shellscript"
content = "${data.template_file.myuserdata.rendered}"
}

}

instance.tf

resource "aws_instance" "ec2" {

  provider                = "aws.base"
  ami                     = "${var.deployment_image}"
  instance_type           = "${var.instance_type}"
  availability_zone       = "${var.vpn_01_availability_zone}"
  disable_api_termination = "${var.disable_api_termination}"
   .............................................
  #user_data              = "${template_file.myuserdata.rendered}"
   user_data_base64 = "${data.template_cloudinit_config.config.rendered}"

    ...................................................................
}

User Data section is now obfuscated

1.PNG

terraform apply output is also hidden

2

For troubleshooting first step is to look into var/log/cloud-init.log log

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s