AWS ec2实例标记名称Powershell

时间:2018-09-24 14:22:33

标签: amazon-web-services powershell amazon-ec2

我试图基于标签字母来获取EC2实例的卷ID,我可以做得很好,但是我想获取名为name的标签,它是EC2实例的描述,因此我可以根据卷ID创建快照,并为其分配EC2实例描述

#gets current date
$backupDate = Get-Date -f 'yyyy-MM-dd'

#Retrieve all volumes that should be backed up based on the Key called Backup with the Value of D
$backupVolumes = Get-Ec2Volume -ProfileName qa | ? { $.Tags.Key -eq "Backup" -and $.Tags.Value -eq "D" } | select -expand VolumeId

#This gets all instances running and lists them
$instanceName = Get-EC2Tag -ProfileName qa | ? { $.ResourceType -eq 'instance' -and $.Key -eq 'Name'}

#Backup each volume and apply tag information to the volume and snapshot
Foreach ($backupVolume in $backupVolumes)
{
    $snapshot = New-Ec2snapshot -ProfileName qa -VolumeId $backupvolume -Description "Backup for $instanceName - $backupDate"
}

以上是我要运行的内容,因此第一行基于D的标记值获取volumeid,然后第二行获取实例名称,但是我希望它仅获取实例名称基于列出的卷ID,因此我可以将其传递到Foreach循环并设置-Description

1 个答案:

答案 0 :(得分:0)

从实例获取Name标签的代码需要在循环内,然后获取与每个卷关联的标签:

我还更改了过滤方式,使用-Filter而不是where更加有效,因为它可以直接返回过滤后的数据。

$backupDate = Get-Date -f 'yyyy-MM-dd'
$backupVolumes = Get-Ec2Volume -Filter @{ Name='tag:Backup';Value='D'}

foreach ($backupVolume in $backupVolumes) {
    $instanceId = $backupVolume.Attachment.instanceid
    $volumeId = $backupvolume.VolumeId
    $instanceName = Get-EC2Tag -Filter @{ Name='resource-id';Value=$instanceid} | Where-Object Key -EQ Name | Select-Object -ExpandProperty Value

    New-EC2Snapshot -VolumeId $volumeId -Description "Backup for $instanceName - $backupDate" -WhatIf
}

注意:您需要在适当的位置重新添加ProfileName,并删除WhatIf,因为这仅是测试代码所需要的。

相关问题