Search code examples
pythonamazon-web-servicesamazon-ec2boto3

How to create AWS EC2 instance using Boto3 for a specific account?


I currently have a regular/non-organization AWS account and I create EC2 instances via Boto3 using code like this:

ec2 = boto3.resource('ec2', region_name = region)

instances = ec2.create_instances(...)

I may need to change my account to an organization and create sub-accounts so I can use different credit cards to fund different accounts.

However, I am concerned how much my existing Boto3 scripts will need to change. Looking at the reference page for create_instances():

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2/service-resource/create_instances.html

I don't see an argument which refers to a sub account.

Using Boto3 how do you create an instance for a specific sub account?


Solution

  • tl;dr

    It is not possible to specify an AWS Account when making API calls to AWS. Instead, the account used is always the one that created the credentials being used to make the API call.

    Explanation

    AWS identity entities (eg IAM User, IAM Role) are created in an AWS Account. When these credentials are used to make API calls to AWS, the resources will always be created in the AWS Account that 'owns' those credentials. Let's call it Account-A.

    To create resources in a different account (Account-B), you will either need to use credentials from Account-B, or you can assume an IAM Role:

    • The IAM Role is defined in Account-B
    • You use credentials (eg IAM User) from Account-A to call AssumeRole on the IAM Role in Account-B
    • This requires permissions in Account-A to call AssumeRole() on that role and also a trust policy on the IAM Role in Account-B that permits the IAM entity in Account-A to assume that role
    • When calling AssumeRole(), a new set of temporary credentials is returned. These credentials belong to Account-B, so any resources created using those credentials will be in Account-B.

    So, using your AWS Organizations setup:

    • You will need an IAM Role in the 'sub-account'
    • You will can use credentials from the 'main-account' to call AssumeRole on the IAM Role in the sub-account
    • This will return a set of temporary credentials that you can use to interact with the sub-account