Add tag to an AWS EC2 instance using AWS PowerShell? Add tag to an AWS EC2 instance using AWS PowerShell? powershell powershell

Add tag to an AWS EC2 instance using AWS PowerShell?


First, install the AWS PowerShell module on PowerShell 5.0 or later:

Install-Module -Name AWSPowerShell -Scope CurrentUser -Force

Now, go to the IAM console and generate an access key, and use the following command to set your credentials in PowerShell.

$AccessKey = '<YourAccessKey>'$SecretKey = '<SecretKey>'$Region = 'us-west-1'Initialize-AWSDefaults -AccessKey $AccessKey -SecretKey $SecretKey -Region $Region

Now that you're authenticated from PowerShell, use the following one-liner script to pop open a list of EC2 instances in a WPF window, and select the ones you want to tag.

(Get-EC2Instance).Instances |   Out-GridView -OutputMode Multiple |   ForEach-Object -Process {     New-EC2Tag -Tag (New-Object -TypeName Amazon.EC2.Model.Tag -ArgumentList @('Key', 'Value')) -Resource $PSItem.InstanceId  }


PS command

New-EC2Tag -ResourceId $Instances -Tags $Tags

From AWS documentation....

$tag = New-Object Amazon.EC2.Model.Tag$tag.Key = "myTag"$tag.Value = "myTagValue"New-EC2Tag -Resource i-12345678 -Tag $tag


Need to add more than one tag!

$Tags = @()

$1T=New-Object Amazon.EC2.Model.Tag;$1T.key="KEYNAME";$1T.Value="VALUE";$Tags += $1T$2T=New-Object Amazon.EC2.Model.Tag;$2T.key="2ndKEYNAME";$2T.Value="2ndVALUE";$Tags += $2T$3T=New-Object Amazon.EC2.Model.Tag;$3T.key="3rdKEYNAME";$3T.Value="3rdVALUE";$Tags += $3T$4T=New-Object Amazon.EC2.Model.Tag;$4T.key="4thKEYNAME";$4T.Value="4thVALUE";$Tags += $4T$5T=New-Object Amazon.EC2.Model.Tag;$5T.key="5thKEYNAME";$5T.Value="5thVALUE";$Tags += $5T

New-EC2Tag -Resource i-12345678 -Tag $tag