简体   繁体   中英

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 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| uniq

this code dosent work for powershell

You need to work with AWS Powershell Module.

The trick here is work with 2 cmdlet function - Get-EC2instance and 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.

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:

在此处输入图像描述

How to create new AccessKey and SecretKey - Managing Access Keys for Your AWS Account .

AWSPowerShell Module installation.

More about Get-EC2KeyPair Cmdlet.

From the docs:

Describes the specified key pairs or all of your key pairs.

More about Get-EC2instance

Returns information about instances that you own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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