簡體   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