User Data Persistance
If I create an image with Packer or other tool, I'll include normally a userdata initialization script that would allow connecting via WinRM. This is required as the default AMI settings wouldn't allow the tooling to connect. In this scenario Packer would create the instance from an AMI with my provided userdata.
However, when I then take an AMI of this configured instance and try to use it as a new instance, this new image has it's own userdata. If I wanted to run the exact same command, I would need to create the userdata in this new instance.
Userdata isn't persisted in your AMI, it's more an instance level configuration value.
Follow-Up Comments on This
The goal should be to create your AMI with the tooling, for example git, and then your new instance should not even need to run that command in the first place as you've "baked" it into your "golden ami". Consider this in your approach. Also consider decoupling any installation directly from userdata and use something like AWS Simple Systems Manager Command documents to run the installation. This would decouple your installation code from your infrastructure allowing you to apply automatically as well as on demand without having to repeat your work.
User Data Content
The code example above has a typo in the closing tag for PowerShell. I'd try replacing this and see if that's the root issue. If there's further issues after fixing that, post a comment on this answer and I'd be glad to look further.
Also as far as powershell syntax consider using join path for proper path parsing.
$exe = Join-Path $ENV:ProgramData 'git/git.exe
The. You can run
&$exe --config --global ....
I'd also recommend that you consider looking at Amazon systems manager documents. You can create a 📄 document that initializes a setting such as get config.
Then you create a AWS association to this document on a tag, at that point it will run automatically anytime a new instance is created without you having to continue to maintain it. It also allows you to update the document independently of the user data, and then ensure you can run it manually as needed as well. I'm a big fan of decoupling any type of configuration scripts from the userdata and using that as a last resort.🚀
One last item...
Remove-Item C:\c -Recurse -ErrorAction Ignore
Highly recommend you revisit that. That's seems super easy to mess up and start deleting stuff you didn't mean to. I'd make sure you use a fully qualified path with
Join-Path and also use the
-LiteralPath instead of positional argument by default. If anyone created a folder c on c drive I'd reject that in a heartbeat in a code review.😄