繁体   English   中英

创建与 AWS 一起使用的 Powershell 代码:列出实例未使用的 EC2 密钥对

[英]create a Powershell code that works with AWS: to list EC2 Key Pairs that are not in use by instances

我正在寻找创建与 AWS 一起使用的 Powershell 代码:列出实例未使用的 EC2 密钥对。

aws ec2 --profile default describe-key-pairs --query KeyPairs[].[KeyName] --output text |xargs -I {} aws ec2 --profile default describe-instances --filters Name=key-name,Values ={} --query Reservations[].Instances[].[KeyName,InstanceId] --输出文本| 独特的

此代码适用于 powershell

您需要使用 AWS Powershell 模块。

这里的技巧是使用 2 个 cmdlet function - Get-EC2instanceGet-EC2KeyPair 首先,您需要获取所有正在使用的密钥。 稍后,您需要获取所有密钥对,并为每个 if 语句按基本过滤它们。

看看下面的代码片段:

Import-Module AWSPowerShell
$keysInUse = @()
$keysNotInUse = @()

#Set AWS Credential        
Set-AWSCredential -AccessKey "AccessKey" -SecretKey "SecretKey"        

#Get ec2 key name from each instance
$allInstancesKeys = (Get-EC2instance  -Region "YourRegion").Instances.KeyName

#Get all key based on region and check if there's an instance who use this key
Get-EC2KeyPair -Region "YourRegion" | % {

    if($_.KeyName -notin $allInstancesKeys)
    {
        $keysNotInUse += $_.KeyName
    }

    else
    {
        $keysInUse += $_.KeyName
    }

} 

Write-Output "Keys not in use: $($keysNotInUse -join ',')\n
Keys in use: $($keysInUse -join ',')"

我拥有的实例和键名:

在此处输入图像描述

Output:

在此处输入图像描述

如何创建新的 AccessKey 和 SecretKey - 为您的 AWS 账户管理访问密钥

AWSPowerShell 模块安装。

有关 Get-EC2KeyPair Cmdlet 的更多信息。

从文档:

描述指定的密钥对或您的所有密钥对。

有关获取 EC2 实例的更多信息

返回有关您拥有的实例的信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM