ps/Modules/Alkami.PowerShell.Common/Public/Get-ImdsV2Token.ps1

66 lines
2.2 KiB
PowerShell
Raw Permalink Normal View History

2023-05-30 22:51:22 -07:00
function Get-ImdsV2Token {
<#
.SYNOPSIS
This gets the token needed for IMDS V2 validation
.DESCRIPTION
For IMDS V2 calls, a token must be retrieved that has a short lifespan. That token is then
used in the header for subsequent calls to the IMDS service.
This function takes care of the lifecycle of the token. Callers need not worry about
caching or storing the token or when/how to refresh it.
The token is an instance-specific key. The token is not valid on other EC2 instances
and will be rejected if you attempt to use it outside of the instance on which it was generated.
.PARAMETER InvalidateCache
When set, this will bust the cache for the token currently set and cause this function
to generate a new token and set it in the cache.
.PARAMETER TTL
How long the token should live, in seconds. This is set default at 5 minutes (300 seconds). The service
minimum is 1 second and maximum of 6 hours (21,600 seconds).
.EXAMPLE
$token = Get-ImdsV2Token
.NOTES
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html
#>
[CmdletBinding()]
[OutputType([System.String])]
Param (
[Parameter(Mandatory = $false)]
[switch]$InvalidateCache,
[Parameter(Mandatory = $false)]
[int]$TTL = 300
)
$logLead = (Get-LogLeadName)
# Test bounds of $TTL.
if(($TTL -lt 1) -or ($TTL -gt 21600)) {
throw "TTL is out of bounds. Must be between 1 and 21600."
}
# Get the token from cache.
$token = $Global:AlkamiImdsSessionToken
# Token is not null and $InvalidateCache is not set, return cached token.
if(!$InvalidateCache -and ($null -ne $token) ) {
Write-Verbose "$logLead token is not null and InvalidateCache is false. Returning cached token."
return $token
}
$uri = (Get-ImdsBaseUri)
$endpoint = ("{0}/api/token" -f $uri)
Write-Verbose "$logLead getting new token with TTL of $TTL seconds."
$token = (Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = $TTL} -Method PUT -Uri $endpoint)
# Cache token.
$Global:AlkamiImdsSessionToken = $token
return $token
}