[英]create a Powershell code that works with AWS: to list EC2 Key Pairs that are not in use by instances
I am looking to 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] --output text|
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] --输出文本| uniq
独特的
this code dosent work for powershell此代码适用于 powershell
You need to work with AWS Powershell Module.您需要使用 AWS Powershell 模块。
The trick here is work with 2 cmdlet function - Get-EC2instance
and Get-EC2KeyPair
.这里的技巧是使用 2 个 cmdlet function -
Get-EC2instance
和Get-EC2KeyPair
。 First of all, you need to get all the keys that in use right now.首先,您需要获取所有正在使用的密钥。 Later, you need to get all key pairs and filter them by basic for each and if statement.
稍后,您需要获取所有密钥对,并为每个 if 语句按基本过滤它们。
Take a look at the following code snippet:看看下面的代码片段:
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 ',')"
The instances i own and key name:我拥有的实例和键名:
Output: Output:
How to create new AccessKey and SecretKey - Managing Access Keys for Your AWS Account .如何创建新的 AccessKey 和 SecretKey - 为您的 AWS 账户管理访问密钥。
AWSPowerShell Module installation. AWSPowerShell 模块安装。
More about Get-EC2KeyPair Cmdlet. 有关 Get-EC2KeyPair Cmdlet 的更多信息。
From the docs:从文档:
Describes the specified key pairs or all of your key pairs.
描述指定的密钥对或您的所有密钥对。
More about Get-EC2instance 有关获取 EC2 实例的更多信息
Returns information about instances that you own.
返回有关您拥有的实例的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.