Setting EC2 Volume Tags for Cost Tracking

Like many AWS users, our company needs to track our AWS costs by project and client for accounting purposes.  Amazon makes it pretty easy to do this using tags and some settings in the billing console.  In our case, we added a CostCenter tag to each instance and ELB to indicate how to allocate the cost. Because most of our instances have at least two volumes, setting the tags manually for the volumes would have been very tedious and error prone. Therefore, I put together this little Powershell script to do the work for us by copying the CostCenter tag from the instance to all its associated volumes:

$volumes = Get-EC2Volume

Write-Host "Setting cost center tag on " $volumes.Count " volumes"
foreach ($vol in $volumes) {
  $tags = $vol.Attachments | %{$_.InstanceId} | Select-Object -First 1 | Get-EC2Instance | %{ $_.Instances} | %{ $_.Tag}
  $name = ($tags | where {$_.Key -eq 'Name'} | %{$_.Value}) -join ','
  $costCenter = ($tags | where {$_.Key -eq 'CostCenter'} | %{$_.Value}) -join ','

  $tag = New-Object Amazon.EC2.Model.Tag
  $tag.Key = "CostCenter"
  $tag.Value = $costCenter
  New-EC2Tag -Resource $vol.VolumeId -Tag $tag
  Write-Host "Volume: " $vol.VolumeId " Cost Center Set To: " $costCenter
}

You will need the AWS Tools for Windows Powershell installed.