private static AmazonEC2Client GetEC2Client(string regionName) { AWSCredentials creds; //try the environment variables first try { creds = new EnvironmentVariablesAWSCredentials(); } //fall back to .aws folder / config catch (Exception) { creds = new StoredProfileAWSCredentials(); } return new AmazonEC2Client(creds, RegionEndpoint.GetBySystemName(regionName)); }
/// <summary> /// Resolves the set of <see cref="AWSCredentials">AWS Credentials</see> based on the /// combination of credential-related parameters that are specified. /// </summary> /// <remarks> /// The order of resolution is as follows: /// <list> /// <item> /// 1. If AccessKeyId is found /// <item>a. If Session Token is found, returns Session AWS Credential</item> /// <item>b. If no Session Token, returns a Base AWS Credential</item> /// </item> /// <item> /// 2. If Profile Name is found, return a Stored Profile AWS Credential, with /// an optional, overridden Profile Location /// </item> /// <item> /// 3. If an IAM Role Name is specified, get the credentials from the local /// EC2 instance IAM Role environment; if the special name '*' is used, /// it uses the first IAM Role found in the current EC2 environment /// </item> /// <item> /// 4. Otherwise, assume credentials are specified in environment variables /// accessible to the hosting process and retrieve them from the following /// variables: /// <item><code>AWS_ACCESS_KEY_ID</code></item> /// <item><code>AWS_SECRET_ACCESS_KEY</code></item> /// <item><code></code>AWS_SESSION_TOKEN</code> (optional)</code></item> /// </item> /// </list> /// </remarks> public AWSCredentials ResolveCredentials() { AWSCredentials cr; if (!string.IsNullOrEmpty(AwsAccessKeyId)) { if (!string.IsNullOrEmpty(AwsSessionToken)) { cr = new SessionAWSCredentials(AwsAccessKeyId, AwsSecretAccessKey, AwsSessionToken); } else { cr = new Amazon.Runtime.BasicAWSCredentials(AwsAccessKeyId, AwsSecretAccessKey); } } else if (!string.IsNullOrEmpty(AwsProfileName)) { cr = new StoredProfileAWSCredentials(AwsProfileName, AwsProfileLocation); } else if (!string.IsNullOrEmpty(AwsIamRole)) { if (AwsIamRole == IAM_ROLE_ANY) cr = new InstanceProfileAWSCredentials(); else cr = new InstanceProfileAWSCredentials(AwsIamRole); } else { cr = new EnvironmentVariablesAWSCredentials(); } return cr; }
public void EnvironmentalVariablesAWSCredentialsTest() { SetEnvironmentVariable("testKeyId", "testSecretAccessKey", "testSessionToken"); EnvironmentVariablesAWSCredentials EnvCredentials = new EnvironmentVariablesAWSCredentials(); Assert.AreEqual(EnvCredentials.GetCredentials(), new ImmutableCredentials("testKeyId", "testSecretAccessKey", "testSessionToken")); }