CloudFormation YAML: EC2 Instance with PowerShell UserData

Someone recently was asking for an AWS CloudFormation template, in YAML format as opposed to JSON, that would deploy an EC2 instance running Windows Server, and supported a PowerShell-based UserData script. In response to this, I created the YAML snippet below.

Note that the Amazon Machine Image (AMI) ID is unique to the us-west-2 (Oregon) AWS Region. AMIs also become outdated over time, as they only contain security updates. If you want to deploy this CloudFormation template to a different region, you will need to select a different AMI ID.

Note that you will also need to specify a different key pair name, as the “Trevor” key pair name is unique to my AWS account.

Resources:
  Instance1:
    Type: AWS::EC2::Instance
    Properties: 
      EbsOptimized: true
      ImageId: ami-343ef84c
      InstanceType: r4.large
      KeyName: Trevor
      UserData:
        !Base64 |
          <powershell>
          1..10 | % { Set-Content -Path ('c:\{0}.txt' -f $PSItem) -Value $PSItem }
          </powershell>
          <persist>true</persist>