How Do You Create a File on a Server with Terraform?

Problem scenario
You are trying to get user data to create a file on a server in Terraform. It is in a directory that requires sudo privileges. You use the "sudo" command in the Bash script. The Bash script executes except a file is never transferred. How do you get Terraform to copy a file to a new server?

Use the Terraform-supported cloud_config option instead of having a Bash script transfer the file.

Here is the content of the file:

provider "aws" {
  access_key = "AKIAabcd1234"
  secret_key = "secret/foobar"
  region     = "us-west-1"

resource "aws_instance" "example" {
  ami           = "ami-1234"
  instance_type = "t2.large"
  key_name      = "good_key"
  user_data     = local.cloud_config_config

locals {
  cloud_config_config = <<-END
      write_files = [
          path        = "/etc/yum.repos.d/fun.repo"
          permissions = "0644"
          owner       = "root:root"
          content     = file("sourcefile.repo")

Leave a comment

Your email address will not be published. Required fields are marked *