How to copy a file to aws ec2 instance and use it in the user-data?

I have an rpm file, which I want to install using user-data of ec2-instance using terraform. I got file provisioner in a search result, but found that it will do the step after user-data.

Any suggestions how to do that?

Please suggest.

Hi @uday-projectn,

From Terraform’s and EC2’s perspective, user_data is just an arbitrary bunch of bytes with no particular meaning, and so the interpretation of those bytes depends on what software you have installed in your AMI which retrieves that data and acts on it.

If you are using a typical Linux distribution AMI though, it’s likely that the software in question is cloud-init. If so, you can use any of the formats that cloud-init understands in order to direct it to take actions when your EC2 instance boots.

The most general way to configure cloud-init is to supply a YAML file using the “cloud config” structure, for which there are many examples. To install an RPM I guess you’d use a combination of Adding a yum repository and Install arbitrary packages, so that cloud-init will both add the yum repository which contains the RPM and then install that package.

Cloud-init expects the Cloud Config format to start with the comment #cloud-config to differentiate it from a shell script, so when you assign that to user_data you can combine that hard-coded comment with a call to Terraform’s yamlencode function in order to generate a YAML structure like what cloud-init is expecting:

  user_data = <<-EOT
    #cloud-config
    ${yamlencode({
      yum_repos = {
        example = {
          baseurl = "http://example.com/distro/testing/5/$basearch"
          enabled = true
          # ...
        }
      }
      packages = [
        "name-of-package",
      ]
    })}
  EOT

Since this is cloud-init behavior rather than Terraform behavior, I can’t promise that this is exactly right but hopefully it shows you the part that is relevant to Terraform – how to generate cloud config YAML using yamlencode – and you can find help in cloud-init communities online for any challenges you might have with cloud-init in particular.