Reputation: 793
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>
Upvotes: 1
Views: 1400
Reputation: 349
For Windows 2022 custom AMI,
ec2 instances created using custom AMI were not running userdata.
You need to run sysprep shutdown command while creating AMI. So when you create ec2 instance using this custom AMI, it will run userdata.
"& 'C:\Program Files\Amazon\EC2Launch\EC2Launch.exe' sysprep --shutdown"
I followed this references for sysprep command since I used Packer to create AMI. https://gonzalo.f-v.es/blog/2022-10-14-windows-2022-eks/
Upvotes: 0
Reputation: 2377
Note that User data is processed by EC2Launch v2
on Windows Server 2022
, EC2Launch
on Windows Server 2016 and 2019
, and EC2Config
on Windows Server 2012 R2
and earlier.
The solution quoted in @devanathan is applicable to EC2Config only.
In case of newer EC2Launch v2
AWS documentation provide a way. By default, the user data scripts are run one time when you launch the instance. To run the user data scripts every time you reboot or start the instance, add <persist>true</persist>
to the user data.
but if you just want the script to run once next tinme system boots (e.g. you are about to create an AMI out of this EC2 isntance, and you want the new instaces created from the AMI to respect userdata, you need to use ec2launch sysprep
<powershell>
....
</powershell>
<persist>true</persist>
Upvotes: 1
Reputation: 818
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/
Upvotes: 3