- Newest
- Most votes
- Most comments
We had the same issue and shifted to a twostep approach… then taught datacenter how to do it and they prefer to launch manually so we post launch tag, e.g. the adjusted sequence actually worked out better for us.
Capturing the instance ID from the result set on the, e.g. from the example:
$NewInstances = New-EC2Instance -ImageId "ami-1a2b3c4d" -KeyName "my-key-pair" -MaxCount 2 -InstanceType "t2.large" -SubnetId "subnet-1a2b3c4d";
Note added the $NewInstances.
From there we can tag the instance and the children:
$Region=[string]"us-east-1";
Foreach( $InstanceID in ($NewInstance.Instances).InstanceId ){ # Check, for typos.
$InstanceName=[string]"My Instance Name";
New-EC2Tag -Resources $( $InstanceID ) -region $Region -Tags @(
@{ Key="Name"; Value=$InstanceName}
# @{ Key="SomeOtherTag"; Value=$AnotherTagValue}
);
# We generally include in the loop a lookup to find network and volumes that need to be tagged.
# Filter for instance id.
$vf = New-Object Amazon.EC2.Model.Filter
$vf.Name="attachment.instance-id"
$vf.Values.Add($InstanceID);
# Get all volumes
$v=Get-EC2Volume -Filters $vf -Region $Region;
# Get all network adapters.
$i=Get-EC2NetworkInterface -Filters $vf -Region $Region;
# Then sub-loop and tag for the $v's and #i's, omitted for brevity.
}
PS, Sorry for any typographical errors, I re-typed some of it.
General idea came from: https://aws.amazon.com/blogs/developer/tagging-amazon-ec2-instances-at-launch/ But the post didn't include the adapters and EBS volumes.
Try it with:
New-Object Amazon.EC2.Model.Tag
instead of:
New-Object Amazon.EC2.Model.TagSpecification
This page uses "Tag":
https://aws.amazon.com/blogs/developer/tagging-amazon-ec2-instances-at-launch/
I've got a similar script on RDS (not EC2) that works:
$Tag = New-Object amazon.RDS.Model.Tag
$Tag.Key = 'CostAllocation'
$Tag.Value = 'DeptABC'
New-RDSDBInstance -DBInstanceIdentifier "db123" -Tag $Tag
Just went down a rabbit hole trying to figure this out too. I found out that PowerShell doesn't pull in the module type until you import the module (duh) or run a command from that module. This might seem obvious, but since is the first thing that pops up if you google "Amazon.EC2.Model.Tag", I figured I'd post.
So you can either run a command from the AWS.Tools.EC2 module before trying to create objects from the module's types or you can run:
Import-Module -Name AWS.Tools.EC2
and now creating objects from that module's types will work
Like this:
$tagspec1 = new-object Amazon.EC2.Model.TagSpecification
and this:
$tagspec1 = new-object Amazon.EC2.Model.Tag
Hope this helps any other lost soul.
Relevant content
- asked 3 years ago
- AWS OFFICIALUpdated 3 years ago
