terraformcloud-init

instantiate VM with file inside


I have a terraform file to create a VM with a cloud-init configuration, that puts a file at location A with content 'CONTENT'. In particular, for openstack but I think that doesn't matter too much:

resource "openstack_compute_instance_v2" "VM" {
  name              = "VM1"
  user_data         = file("userdata_file")
}

The userdata_file then contains the following block:

write_files:
  - path: A
   content: |
      CONTENT

#some other stuff ...

That works all pretty nicely, but: I would want to have the file A as it own file in the repository. That is, there would be a plain text file A with the CONTENT inside , and ideally I could reference it either in the userdata_file or in the Terraform file. Something along the lines of

write_files: 
 - path: A
   content: readFromFile('A')  #this doesn't exist AFAIK

Is there some possibility to do this easily with Terraform ?


Solution

  • A function to read a file at a specific path and return its contents as a string is the file function, and you demonstrate you are already using it so you should be familiar with it already. The missing piece of the puzzle here is to render the file content of userdata_file dynamically. The templatefile function is typically utilized for this functionality as it allows separated string expression resolution:

    resource "openstack_compute_instance_v2" "VM" {
      name              = "VM1"
      user_data         = templatefile("userdata_file", {})
    }
    

    and then as you would expect:

    write_files: 
    - path: A
      content: ${file('A')}