这里是我做过什么:
注:虽然这是被标记的情况下,它可以很容易地修改与图像的工作。
注意:我不是PowerShell的高级用户,所以如果你看到明显的低效率,请让我知道。
我用詹金斯打造的机器,因此它有,我使用的标签化的环境变量,但它调用具有该签名PowerShell脚本,所以你可以手动调用或通过其他脚本中调用它:
param(
...
[Parameter(Mandatory=$true)][string]$Tag_Name,
[Parameter(Mandatory=$true)][string]$Tag_Version
)
这里面的脚本,我设置的实例标记,像这样:
#Get metadata from ec2 service
$identityDocument = (Invoke-WebRequest http://169.254.169.254/latest/dynamic/instance-identity/document/).Content | ConvertFrom-Json
$tags = @(
@{Key = "Name"; Value = $Tag_Name},
@{Key = "Version"; Value = $Tag_Version}
)
New-EC2Tag -Resource $identityDocument.instanceId -Tag $tags
在另一个脚本中,我可以通过名字查询,发现所有实例,解析结果成一个哈希表[INSTANCEID ,版本],按版本排序得到最高的一个。
$instanceName = "hello-world"
$instances = GetHashTableOfFilteredInstances $instanceName
$instanceId = GetNewestInstance($instances)
Write-Host 'Information for ' $instanceName
Write-Host '================='
Write-Host 'The newest instance is ' $instanceId
Write-Host '================='
function GetHashTableOfFilteredInstances($tagName){
$instances = Get-EC2Instance -Filter @(`
@{name='tag:Name'; values=$tagName};`
) | Select-Object -ExpandProperty instances
$actInstances= @{}
foreach($instance in $instances){
foreach($tag in $instance.Tag){
if ($tag.Key -ne "Version") {
Continue;
}
$actInstances.Add($tag.Value, $instance.InstanceId)
}
}
return $actInstances
}
function GetNewestInstance($instances){
return ($instances.GetEnumerator() | Sort-Object Key -descending)[0].Value
}
当然,我可以像创建时间一样过滤:$ ami = Get-EC2Image -Region $ Region -Owner self | Where-Object {$ _。Name.StartsWith(“windows-iis-ami”)} | ' Sort-Object -Property CreationDate -Descending | ' Select-Object -First 1 | ' 选择-ExpandProperty ImageId –