CallumVass
CallumVass

Reputation: 11448

Switch between Accounts when hosted on EC2 Instance

We currently have 2 AWS accounts that we use. For most of the stuff we want to use the AWS account that our web app is hosted on in an EC2 instance so this works fine:

services.AddDefaultAWSOptions(this.Configuration.GetAWSOptions());
services.AddAWSService<IAmazonSQS>();
services.AddAWSService<IAmazonSimpleSystemsManagement>();

However, I want to access EC2 instances in another AWS account. I've configured it to work locally using credentials and from following this guide (where it mentions about using multiple services): https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-config-netcore.html

services.AddDefaultAWSOptions(this.Configuration.GetAWSOptions());
services.AddAWSService<IAmazonSQS>();
services.AddAWSService<IAmazonSimpleSystemsManagement>();

if (this.WebHostEnvironment.IsDevelopment())
{
   // This works fine locally, but I don't want to use credential file in production
    var other = this.Configuration.GetAWSOptions("other");
    services.AddAWSService<IAmazonEC2>(other);
}
else
{
    // How do I register other here without putting a credential file on my ec2 instance?
    services.AddAWSService<IAmazonEC2>();
}

I'm not sure how to register IAmazonEC2 to use my other account. I don't want to put a credential file on my instance which is how I get it working locally but it doesn't seem right to me on production servers.

I have configured an IAM role that has access to my other account and given it to my EC2 instance. But how do I translate that IAM role to a profile to use where I am registering IAmazonEC2 above?

Any help appreciated. Thanks

Upvotes: 0

Views: 333

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 269340

There are really two ways to do it...

Option 1: Use an IAM Role

Let's say that the Amazon EC2 instance is running in Account-A and it now wants to query information about Account-B. You could:

  • Create an IAM Role in Account-B, with a trust policy that trusts the IAM Role being used by the EC2 instance in Account-A
  • Your code running on the EC2 instance in Account-A can call AssumeRole() (using the normal credentials from Account-A). This will return a set of temporary credentials.
  • Use those temporary credentials to make API calls to Account-B

Option 2: Use credentials from Account-B

Alternatively, give your program a set of IAM User credentials from Account-B. These could be stored in AWS Systems Manager Parameter Store - AWS Systems Manager or AWS Secrets Manager, and retrieved by using the normal credentials assigned to the EC2 instance in Account-A.

Upvotes: 1

Related Questions