Issue
While using S3Client
in java, I used to initialize S3Client like this and it worked perfectly on local machine (where I have environment variables set) as well as EC2 instance (where I have IAM role):
AWSCredentials credentials = DefaultAWSCredentialsProviderChain.getInstance().getCredentials();
AmazonS3 s3client = new AmazonS3Client(credentials);
I want to do the same in C#.net. For that, I have to use different methods to run it on local machine and EC2 instance. Right now, I am doing it somewhat like this :
var awsCredentials = new EnvironmentVariablesAWSCredentials(); //For local
var awsCredentials2 = new InstanceProfileAWSCredentials(); //For EC2 instance
var awsRegion = Environment.GetEnvironmentVariable("AWS_REGION");
AmazonS3Client s3Client = new AmazonS3Client(awsCredentials, RegionEndpoint.GetBySystemName(awsRegion));
I have gone through official AWS SDK for .Net's documentation
But what I can not find is, equivalent of this Java Method
DefaultAWSCredentialsProviderChain.getInstance().getCredentials()
Is there any method in C#.net that follows hierarchy of retrieving credentials and provide it?
Thanks in advance.
Solution
Solution is very simple:
Use an empty constructor for all AmazonClients
(AmazonSQSClient/AmazonSNSClient/AmazonS3Client
) or use constructor without AWSCredentials
argument.
So code looks like this :
AmazonS3Client s3Client = new AmazonS3Client();
OR
var awsRegion = Environment.GetEnvironmentVariable("AWS_REGION");
AmazonS3Client s3Client = new AmazonS3Client(RegionEndpoint.GetBySystemName(awsRegion));
Documentation of empty constructor reads like this :
Constructs AmazonS3Client with the credentials loaded from the application's default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
Answered By - Utsav Chokshi Answer Checked By - Gilberto Lyons (WPSolving Admin)