简体   繁体   中英

How to register an EC2 Instance with an ELBV2?

I'm trying to register a new EC2 instance with an ELBV2. I'm trying from the AWSPowershell Module but cannot get it to work.

$InstanceId = (Invoke-WebRequest 'http://169.254.169.254/latest/meta-data/instance-id').Content
Register-ELB2Target -TargetGroupArn 'arn:etc...' -Target $InstanceID

The error is:

Register-ELB2Target : Cannot bind parameter 'Target'. Cannot convert the "i-redacted" value of type "System.String" to type
"Amazon.ElasticLoadBalancingV2.Model.TargetDescription".

I've checked the documentation, and can see that it can take a port too (optional). Have tried adding the port, but still no luck.

You're not creating the TargetDescription object correctly, it should be something like:

$thisInstance = New-Object Amazon.ElasticLoadBalancingV2.Model.TargetDescription
$thisInstance.Id = $instanceId
$thisInstance.Port = 80

For anyone else who arrives here looking for an easy answer, we use the following script for instances to register themselves with the ALB when new packages are deployed:

Set-DefaultAWSRegion "ap-southeast-2"

# work out the id and load balancer for this instance
$instanceId = (wget -UseBasicParsing "http://169.254.169.254/latest/meta-data/instance-id").Content
$targetGroupArn = (Get-EC2Tag -Filter @{Name="resource-id"; Values=$instanceId}, @{Name="key";Values="<name of key>"}).Value # instances have the alb arn tagged in when created by an autoscaling group

$thisInstance = New-Object Amazon.ElasticLoadBalancingV2.Model.TargetDescription
$thisInstance.Id = $instanceId
$thisInstance.Port = 80

write-host "Adding $instanceId to $targetGroupArn"

# register instace with ALB
Register-ELB2Target -TargetGroupArn $targetGroupArn -Targets @( $thisInstance ) -Force

write-host "Done"

基本上,它与@CamM的答案相同,但语法较短:

Register-ELB2Target -TargetGroupArn $targetGroupArn -Target @{ Id = $instanceId; Port = 80 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM