Skip to content

Instantly share code, notes, and snippets.

@gmirsky
Created July 22, 2020 20:06
Show Gist options
  • Select an option

  • Save gmirsky/f7e87dcae3e54cfdbe85c93e7e15209f to your computer and use it in GitHub Desktop.

Select an option

Save gmirsky/f7e87dcae3e54cfdbe85c93e7e15209f to your computer and use it in GitHub Desktop.
AWS List Unused Key Pairs
Param( $AWSRegion = 'us-east-1', $AWSProfileName = 'default')
#
# Store your AWS credentials using the following Powershell AWS command:
#
# Set-AWSCredentials -AccessKey {xx} -SecretKey {xx} -StoreAs {MyProfileName}
#
# Example:
#
# Set-AWSCredentials -AccessKey 'AKIAVJL...KWJKOB4XN' -SecretKey 'oxLcrpnd3S+...1Y5eg3m92E8e2Me' -StoreAs 'testprofile'
# Set-DefaultAWSRegion us-east-1
#
# Verify your profile exists using:
#
# Get-AWSCredential -ListProfileDetail
#
#
# Call this script with the following command:
#
# .\AwsListUnusedKeyPairs.ps1 -AWSRegion us-east-1 -AWSProfileName testprofile
#
#
#Write-Output "`r`nInput parameter for AWSRegion ==> $AWSRegion"
#Write-Output "Input parameter for AWSProfileName ==> $AWSProfileName `r`n"
#
try {
Import-Module AWSPowerShell
}
catch {
Write-Host "Import-Module AWSPowerShell failed!"
exit
}
$keys_in_use = @()
$keys_not_in_use = @()
# Set AWS Credential
Set-DefaultAWSRegion $AWSRegion
#Set-AWSCredential -AccessKey $access_Key -SecretKey $secret_key
try { Set-AWSCredential -ProfileName $AWSProfileName }
catch {
Write-Host "Set-AWSCredential -ProfileName $AWSProfileName failed!"
exit
}
# Get the AWS Account number and print it.
try {
$accountId = @(get-ec2securitygroup -GroupNames "default")[0].OwnerId
Write-Host "`n`rAWS Account number: $accountid"
}
catch {
Write-Host "Encountered an issue obtaining the AWS Account ID."
exit.
}
# Alternate method to obtain AWS Acccount ID.
# $awsAccountNumber = (get-ec2securitygroup -ProfileName saml -Region $AWSRegion)[0].OwnerId
# Get ec2 key name from each instance
$allInstancesKeys = (Get-EC2instance -Region $AWSRegion).Instances.KeyName
If ($allInstancesKeys -lt 1 ) {
Write-Output "`r`nNo keypairs found in region: $AWSRegion`r`n`r`n"
}
else {
Write-Output "The following key pairs were found in region: $AWSRegion"
# Get all key based on region and check if there's an instance who use this key
Get-EC2KeyPair -Region $AWSRegion | ForEach-Object {
if ($_.KeyName -notin $allInstancesKeys) {
$keys_not_in_use += $_.KeyName
}
else {
$keys_in_use += $_.KeyName
}
}
# Write the output of keys used and unused.
Write-Output "`r`nKeys not in use:`r`n`t$($keys_not_in_use -join "`r`n`t")"
"`r`nKeys in use:`r`n`t$($keys_in_use -join "`r`n`t")"
}
Write-Output "`n`r"
Exit
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment