amazon-web-servicesamazon-ec2aws-cloudformation

Userdata not working in Custom AMI (built on Windows 2019 Base AMI)?


I am using the Custom AMI built on top of Windows 2019 Base AMI(ami-0fa60543f60171fe3) to create a windows server. But I see the Userdata is not working. This is the CFT I am using.

RabbitMQServer:
    Type: AWS::EC2::Instance
    Properties:
      KeyName: !Ref PublicKeyName
      IamInstanceProfile: !Ref IamInstanceProfile      
      ImageId: !Ref RabbitMQServerAMI 
      InstanceType: !Ref RabbitMQServerInstanceType
      Monitoring: true
      SecurityGroupIds:
        - !Ref PrivateInstanceSG
      SubnetId: !Ref PrivateSubnetID 
      UserData: !Base64 |
          <script>
          echo Current date and time >> C:\test.log
          echo %DATE% %TIME% >> C:\test.log
          </script>
          <persist>true</persist>

Solution

  • In Windows by design, this task is disabled after it is run for the first time for security reasons. To enable it please execute the following command,

    C:\ProgramData\Amazon\EC2-Windows\Launch\Scripts\InitializeInstance.ps1 –Schedule
    

    However, using the persist tag causes Invoke-UserData to schedule a separate task via Register-FunctionScheduler, to persist your user data on subsequent boots. You can see this for yourself at C:\ProgramData\Amazon\EC2-Windows\Launch\Module\Scripts\Invoke-Userdata.ps1.

    For further analysis If you're having additional issues with your user data scripts, you can find the user data execution logs at C:\ProgramData\Amazon\EC2-Windows\Launch\Log\UserdataExecution.log(This is a hidden folder)

    for other options please refer https://blog.kloud.com.au/2017/04/23/re-execute-the-userdata-script-in-an-aws-windows-instance/