I have a user data Powershell script that I would like my EC2 instances to execute upon launch.
It is a simple script which retrieves the tags of the current EC2 instance.
$InstanceId = (Invoke-WebRequest -Uri http://169.254.169.254/latest/meta-data/instance-id -UseBasicParsing).Content
$Env = (Get-EC2Tag -Filter @{Name="resource-type";Value="instance"},@{Name="key";Value="Environment"} | Where-Object ResourceId -eq "$InstanceId").Value
$Role = (Get-EC2Tag -Filter @{Name="resource-type";Value="instance"},@{Name="key";Value="Role"} | Where-Object ResourceId -eq "$InstanceId").Value
This code works perfectly when I run it inside EC2 however it fails to work possibly due to Internet connectivity when I run it as a User Data/Launch script:
Get-EC2Tag : Name resolution failure attempting to reach service in region ap-southeast-2 (as supplied to the -Region parameter or from configured shell default). Unable to connect to the remote server. Possible causes: - The region may be incorrectly specified (did you specify an availability zone?). - The service may not be available in the region. - No network connectivity.
I suspect the Internet connection must be the root cause because initially, I tried to clone the git repo that included my script and that failed with a Timeout error too!
How can I retrieve the tags of the current instance at instance launch?
If I run this once I am remotely connected to my Windows EC2 instance it works perfectly.