Search code examples
powershellaws-powershell

Add tag to an AWS EC2 instance using AWS PowerShell?


How do I use the Amazon Web Services (AWS) PowerShell module to add a tag (key-value pair) to an EC2 instance?


Solution

  • 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
      }