Search code examples
amazon-web-servicesamazon-ec2terraformwindow

How to copy a file to a new AWS EC2 Windows instance in Terraform


I have searched, but this specific case is not coherently documented that I can find.

I just want to spin up a new windows instance in EC2 and copy a file to it. This seems it should be trivial and common. But I must be missing something, I hope something simple aand obvious.

Most examples I see use a "connection" of type "winrm", but it needs a password. What is the password on a newly created instance?


Solution

  • A common method of performing an operation on an Amazon EC2 instance after it is launched is to Run commands when you launch an EC2 instance with user data input - Amazon Elastic Compute Cloud.

    Information passed via the User Data parameter is accessible from the EC2 instance. Amazon-provided AMIs have pre-installed cloud-init code that checks whether the User Data contains a script. If so, it executes the script the first time that a new instance is launched.

    Therefore, you can achieve your goal by:

    • Placing the file in an Amazon S3 bucket
    • Passing a script via User Data when launching the EC2 instance (make sure the instance is assigned an IAM Role that gives it access to the bucket)
    • Program the script to download the file from S3 to the local EC2 disk (using Powershell or the AWS CLI). Note that the script will only execute on the first boot of the instance.