This is more a sanity check because I've solved the problem but I'm unconvinced I've done it the smart way.
The Problem
I have some instances that have been assigned an IAM roles that allow them to access an S3 bucket. I then need to run some PowerShell scripts that will access that S3 bucket to download some objects.
The Solution
To get/set the credentials to use I've written this PowerShell function:
function Set-MyInstanceProfileCredentials {
param(
[parameter()]
[string]
$StoredCredentialsName = "MyInstanceProfileCredentials"
)
$Uri = "http://169.254.169.254/latest/meta-data/iam/security-credentials/"
Write-Verbose "Retrieving instance profile from $($Uri)"
$Uri = "$Uri$(Invoke-RestMethod -Uri $Uri)"
Write-Verbose "Retrieving security credentials from $($Uri)"
$Response = Invoke-RestMethod -Uri $Uri
Set-AWSCredentials -AccessKey $Response.AccessKey -SecretKey $Response.SecretAccessKey -StoreAs $StoredCredentialsName
Get-AWSCredentials -StoredCredentials $StoredCredentialsName
}
Then when I need to run a PowerShell cmdlet from the AWS module I just call this function first.
However I can't shake the feeling that I've missed something from the AWS PowerShell module that is already taking care of this for me.
However I can't shake the feeling that I've missed something from the AWS PowerShell module that is already taking care of this for me.
:) - you will be delighted to hear that this simply works out of the box indeed, i.e. the AWS Tools for Windows PowerShell is build upon the AWS SDK for .NET, which is handling this automatically, see also Credentials Search Order:
When you run a command, PowerShell Tools searches for credentials in the following order and uses the first available set.
[...]
6) If you are using running the command on an Amazon EC2 instance that is configured for an IAM role, use EC2 instance credentials stored in an instance profile.
For more information about using IAM roles for Amazon EC2 Instances, go to the AWS Developer Guide for .NET.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With