How can I get AWS Instance Tags in user-data?

随声附和 提交于 2019-11-30 19:00:27

问题


I use aws ec2 userdata with windows powershell scripts. I need instance bootstrapping. My idea is:

  • EC2 instance tag adds.It's key name "Version", it's value "1.0.0.158-branchname"

I have tried to get version tag value in userdata. I checked aws http api. It can't return tags. I wrote simple powershell scripts:

$instanceId = (New-Object System.Net.WebClient).DownloadString("http://169.254.169.254/latest/meta-data/instance-id")
aws ec2 describe-tags --filters $filter --query 'Tags[*]'

I can get instance Id with aws http api. I can't get instance tags because AWS ec2 userdata can't start "aws.exe".

This script is correct - it is manually run before the instance is started.

Note: "aws" is "aws.exe" (https://aws.amazon.com/cli/)


回答1:


I resolve it, my problem is using aws cli . I use powershell api and fix it.

$instanceId = (New-Object System.Net.WebClient).DownloadString("http://169.254.169.254/latest/meta-data/instance-id")
$versionTag =  Get-EC2Tag | ` Where-Object {$_.ResourceId -eq $instanceId -and $_.Key -eq 'Version'}



回答2:


Just some clarifications as I was facing similar issue..

If the Instance has an IAM role with EC2 Read access..

# My need to use AWSDefaults cmdlet to get temp credentials from STS
Initialize-AWSDefaults
$instanceId = irm -uri http://169.254.169.254/latest/metadata/instance-id
$instance = (Get-Instance -InstanceId $instanceId).Instances[0]
$instanceName = ($instance.Tags | ? { $_.Key -eq "Name"} | select -expand Value)


来源:https://stackoverflow.com/questions/23559469/how-can-i-get-aws-instance-tags-in-user-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!