[英]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-EC2instance
和Get-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 账户管理访问密钥。
有关 Get-EC2KeyPair Cmdlet 的更多信息。
从文档:
描述指定的密钥对或您的所有密钥对。
返回有关您拥有的实例的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.