1
votes

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.

1

1 Answers

2
votes

The error indicates that it cannot reach the remote site.

You can check the log file in:

C:\ProgramData\Amazon\EC2-Windows\Launch\Log\UserdataExecution.log

If you are using an older version of Windows, it would be in:

C:\Program Files\Amazon\Ec2ConfigService\Logs\Ec2Config.log

To have Internet connectivity, the instance must be either:

  • In a public subnet, or
  • In a private subnet, with a NAT Gateway configured in the public subnet

Also, check the Security Group associated with the instance. It should be using the default "Allow All" for Outbound rules.

Another possibility, as suggested by the error message, is that it does not know which region to use. You can append -Region ap-southeast-2 (or other region) to specify a particular region.