|
# Sync EBS tags with their instances. |
|
# Script for non-CloudFormation managed tag cleanup. |
|
|
|
# Credit: https://www.yobyot.com/aws/tag-aws-ec2-ebs-volumes-with-the-instance-name-tag/2017/02/05/ |
|
|
|
# Uses legacy AWSPowerShell monolith module. |
|
# Assumes appropriate Exec Policy, Allow Gallery, etc... |
|
# Install-Module AWSPowershell |
|
|
|
Import-Module AWSPowerShell # Must import the module if you haven't already. |
|
Set-AWSCredentials -ProfileName default # Update as needed. |
|
Set-DefaultAWSRegion -Region us-east-1 # Update as needed. |
|
|
|
(Get-EC2Instance).Instances | ` |
|
ForEach-Object -Process { # For each instance, |
|
$instance = $_ # Store instance details for later use within another ForEach |
|
|
|
$instance.Tags | ` |
|
ForEach-Object -Process { # For each tag on on the current instance, |
|
$instanceTagKey = $_ | Select-Object -ExpandProperty Key # Store Tag Key, its name. |
|
$instanceTagValue = $_ | Select-Object -ExpandProperty Value # Store Tag Value. |
|
|
|
$instance.BlockDeviceMappings | ` |
|
ForEach-Object -Process { # For each ebs volume related to the current instance, |
|
$volumeId = $_.ebs.volumeid # Store volumeId for current ebs volume |
|
$volumeTagKey = Get-EC2Tag -Filter @(@{ name = "tag:$instanceTagKey"; values = "*" }; @{ name = "resource-type"; values = "volume" }; @{ name = "resource-id"; values = $volumeid }) | Select-Object -ExpandProperty Value # If exists, get the value of the current tag from the ebs volumeid |
|
|
|
if (-not $volumeTagKey) { # if the tag isn't already present, no overwrites only additions |
|
New-EC2Tag -Resources $volumeid -Tags @{ Key = $instanceTagKey; Value = $instanceTagValue } # add the current tag to the current ebs volume |
|
"New-EC2Tag -Resources $volumeid -Tags `@{ Key = `"$instanceTagKey`"; Value = `"$instanceTagValue`"}" # console output |
|
} |
|
} |
|
} |
|
} |
|
|
|
# Delete unused tags: |
|
# Get-EC2Tag | ? {$_.key -eq 'Example Key'} | % { |
|
# Remove-EC2Tag -Resources $_.resourceId -Tags @{ Key = $_.key } |
|
# "Remove-EC2Tag -Resources $($_.resourceId) -Tags @{ Key = $($_.key) }" |
|
# } |
|
|
|
# Find RDS tags: |
|
# Get-RDSDBInstance | select -ExpandProperty DBInstanceArn | Get-RDSTagForResource |