Versions
- .net core sdk v3.1.301
- AWSSDK.Extensions.NETCore.Setup v3.3.101
- AWSSDK.IdentityManagement v3.3.106.19
- AWSSDK.SecurityToken v3.3.105.30
Definitions
Since this question talks about different types of AWS credentials I thought it would be helpful to define the terms I'm using
Application credentials - AWS credentials loaded by the .NET Core AWS SDK when on startup
Assume role credentials - Temporary AWS credentials obtained at runtime from the STS
Problem
I'm writing some code that interacts with AWS using the AWS SDKs. When using the AWS SDKs I tend to inject the service clients using the ASP.NET Core built in Dependency Injection container:
services.AddAWSService<IAmazonIdentityManagementService>();
services.AddAWSService<IAmazonSecurityTokenService>();
This works fine when you want to use the application credentials. Injecting and instance of the AWS client works as expected
public class IamService : IIamService
{
private readonly IAmazonIdentityManagementService _iamClient;
public IamService(IAmazonIdentityManagementService iamClient)
{
_iamClient = iamClient;
}
}
However, my application needs to assume multiple roles in multiple accounts
The only way I can think to do this is to make a call to the STS to get the assume role credentials:
AssumeRoleRequest request = new AssumeRoleRequest()
{
RoleSessionName = "MySession",
RoleArn = "arn:aws:iam::123456789012:role/MyRole"
};
AssumeRoleResponse response = await _service.AssumeRoleAsync(request);
Where _service
is of type IAmazonSecurityTokenService
And then new
up all my calls to the AWS SDKs
AmazonIdentityManagementServiceClient service =
new AmazonIdentityManagementServiceClient(response.Credentials);
Question
Is there a cleaner way this can be handled which means I don't have to instantiate new SDK clients all over the place?
I was hoping there might be some magical way you could configure the DI container to say, if Assume role credentials are provided then inject an instance of the AWS SDK with these credentials, otherwise use the application credentials - after a lot of Googling I couldn't find anything that suggested this would be possible...