AWS Security Cookbook

4.5 (2 reviews total)
By Heartin Kanikathottu
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Managing AWS Accounts with IAM and Organizations

About this book

As a security consultant, securing your infrastructure by implementing policies and following best practices is critical. This cookbook discusses practical solutions to the most common problems related to safeguarding infrastructure, covering services and features within AWS that can help you implement security models such as the CIA triad (confidentiality, integrity, and availability), and the AAA triad (authentication, authorization, and availability), along with non-repudiation.

The book begins with IAM and S3 policies and later gets you up to speed with data security, application security, monitoring, and compliance. This includes everything from using firewalls and load balancers to secure endpoints, to leveraging Cognito for managing users and authentication. Over the course of this book, you'll learn to use AWS security services such as Config for monitoring, as well as maintain compliance with GuardDuty, Macie, and Inspector. Finally, the book covers cloud security best practices and demonstrates how you can integrate additional security services such as Glacier Vault Lock and Security Hub to further strengthen your infrastructure.

By the end of this book, you'll be well versed in the techniques required for securing AWS deployments, along with having the knowledge to prepare for the AWS Certified Security – Specialty certification.

Publication date:
February 2020


Managing AWS Accounts with IAM and Organizations

The security of an application or a platform is generally considered as providing authentication, authorization, integrity, and confidentiality. Availability and accounting are two other aspects of security that are often overlooked. The Confidentiality, Integrity, and Availability (CIA) model and Authentication, Authorization, and Accounting (AAA) model are two popular models related to cloud security. CIA is generally referred to as the CIA triad. Apart from these, we should also consider non-repudiation while securing our application or platform.

In this chapter, we will learn about the AWS Identity and Access Management (IAM) service, the primary service in AWS for managing users, groups, roles, and permissions. We will learn how to write security policies. We will also discuss using the AWS Organizations service to create multiple accounts from within a single master account. We can use the AWS Organizations service to switch between the associated accounts without logging out of AWS, which helps to work with multiple accounts easily. We will also discuss core security concepts related to the cloud. 

This chapter will cover the following recipes:

  • Configuring IAM for a new account
  • Creating IAM policies
  • Creating a master account for AWS Organizations
  • Creating a new account under an AWS Organization
  • Switching roles with AWS Organizations

Technical requirements

We need a working AWS account to practice the recipes within this chapter. We should install and configure the AWS Command-Line Interface (CLI) in our local machine. It's assumed that you have basic knowledge of S3. 

The AWS Management Console is generally used for one-time activities. For repetitive tasks, we should use Application Programming Interfaces (APIs). I will be providing CLI API usages for most cases with code files. You may follow these CLI API usages and implement them in a programming language of your choice using the AWS SDK or automate them using CloudFormation templates, as applicable.

The code files for this book are available at The code files for this chapter are available at


Configuring IAM for a new account

IAM is the primary service in AWS for managing access to AWS services. IAM is a universal service and is not region-specific. After creating an AWS account, we should do some basic IAM configuration in order to secure our AWS account. IAM provides a checklist for these activities. Though not part of this checklist, we will also provide an account alias and create a billing alarm.

Getting ready

We need a newly created AWS account to complete all the steps in this recipe. Our IAM dashboard should look as follows. Even if you do not have a new account, you can still follow this recipe and verify whether everything has been configured correctly:

You need to install an authenticator app on your mobile if you are planning to set up multi-factor authentication (MFA) using a virtual MFA device. Google Authenticator is one popular option. You can also use a YubiKey U2F security key, any U2F-compliant device, or a hardware MFA device. 

Universal 2nd Factor (U2F) is an authentication standard for securely accessing online services with only a security key without any drivers or client software.

How to do it...

Follow these steps on a new IAM dashboard. If your account isn't new, verify whether everything has been configured correctly:

  1. Give a unique and meaningful alias for the account within the IAM users sign-in link. 

This is not a security requirement, but it makes it easier for our IAM users to log in to our account. By default, the account ID is used. Next, we will follow the IAM security checklist and make all the fields of the checklist green.

  1. Activate MFA on our root account. Expand the Activate MFA checklist item and click on Manage MFA:

  1. On the MFA selection page, select Virtual MFA device and click Next. You may select other options if they're applicable:


AWS will now provide a QR code.

  1. Scan the QR code using an authenticator app (installed in the Getting ready section) and enter two successful token keys to activate it. After MFA has been activated, we will need to provide a token from this app, along with a username and password, to log in to the AWS console.
You should save the QR code image in a secure place if you ever want to reconfigure the authenticator app without accessing the current authenticator app setup; for example, in the event that your current mobile stops working. Alternatively, you can contact AWS support in case of such an event and they can help you reset the authenticator app configuration.
  1. Create a user after expanding the Create Individual IAM Users checklist. We can also use the left menu item to go to the Users page.
  2. Provide a username by using the option to add the user to a group.
  3. Create a group.
  4. Assign some policies to the group.
Policies are JSON documents that are used by IAM that authorize us to use various AWS services. It is good practice to assign policies to groups rather than to individual users.
  1. Expand the checklist item for the password policy and set a decent password policy. 
  2. Go back to the IAM dashboard and check that all the checkmarks are green:

Now, let's create a billing alarm.

Creating a billing alarm

In this section, we will set up a billing alarm that will let us know when we exceed a set limit:

  1. Go to your billing dashboard from the drop-down menu next to your account name on the upper-right corner of the screen:

  1. From the billing dashboard, click on Billing preferences, select the Receive Billing Alerts checkbox, and click Save preferences:

  1. Go to the CloudWatch service dashboard and click on Billing on the left. From the Billing alarm page, click on Create alarm. On the Create alarm page, provide our usage limit and an email for sending notifications:

At the time of writing this book, only AWS allows us to create a billing alarm if our region is set to US East (N. Virginia).

How it works...

IAM is the AWS service that helps us manage the identity of users within AWS in order to verify their identity (authentication) and their permissions to AWS services (authorization). 

IAM has four core concepts:

  • Users: A user can be created in IAM and given the necessary permissions to access AWS resources.
  • Groups: Users can be added to groups. Permissions can now be given to groups instead of individual users. This is a recommended best practice.
  • Policies: Policies are JSON documents that define the permissions for users or groups.
  • Roles: Roles are generally used for giving users temporary permissions to access an AWS service. For example, we can attach a role with S3 permissions to an EC2 service.

The IAM dashboard provides a set of checklist items to keep our account secure. It is good practice to keep them all green. The first checklist item checks whether we have active access keys for our root account that can be used for programmatic access. The root account is the account that we log into using the primary email and has access to everything in our account. It is good practice to use root for creating other accounts and then use those accounts for our day-to-day activities. 

The next checklist item checks whether we have enabled MFA for our root account. MFA will enforce an additional level of authentication, apart from the username and password, using tokens from a virtual or hardware MFA device. The next two checklist items make sure that we create at least one user and a group. The last checklist item is for setting a password rotation policy for our account.

Finally, we also set up a billing alarm. Though not part of the IAM checklist, it is good practice to set a billing alarm. This will trigger an alarm and let us know when we exceed the set limit.

There's more...

Let's quickly go through some important concepts related to IAM and security:

  • Authentication is the process of verifying a user's identity with a username and password, or credentials such as the access key and the secret access key.
  • There are primarily two types of access credentials in AWS for authenticating users:
    • Access key ID and secret access key: This is used for programmatic access, and is used with AWS APIs, CLI, SDK, and any development tools.
    • Username and password: For managing console access. 
  • Authorization is the process of checking whether a user has the right permissions to perform an action and is usually defined using the permission's policies.
  • Confidentiality is done to make sure the data that's sent from the source is not read by anyone in between. This can be made possible using cryptography. 
  • Data integrity is done to make sure the data has come from the right person and has not been tampered in between. This is also generally made possible using cryptography. 
  • Availability makes sure the service can be used when it is needed. 
  • Accounting helps us identify the responsible parties in case of a security event.
  • Non-repudiation prevents a user from denying an activity. Cryptography comes to our aid here.
  • The AWS shared responsibility model defines the responsibilities of AWS and its customers in securing our solutions on the AWS cloud. In summary, it states that the security of the cloud, for example, securing the global infrastructure, hardware, networking, and so on is AWS's responsibility; while security in the cloud, for example, updates and security patches for the servers we provision, protecting credentials and keys, and so on is the customer's responsibility. 
  • AWS IAM supports Payment Card Industry Data Security Standard (PCI-DSS) compliance. This is an information security standard required for organizations that handle credit cards.

See also


Creating IAM policies

In this recipe, we will learn how to create IAM policies from the Management Console, as well as the AWS CLI. We will create an IAM policy for an S3 bucket.

Getting ready

We need a working AWS account with the following resources configured:

  • A user with no permissions and a user with administrator permissions. Add these users to two groups. We should configure CLI profiles for these users. I will be calling the users and their CLI profiles testuser and awssecadmin and the groups awstestusergroup and awssecadmingroup, respectively.
awssecadmin is a user with full administrator permissions. In real-world projects, we won't have a single user with all permissions. Instead, we will segregate permissions into different user groups. If we are practicing these recipes from an office account, it is unlikely that we will be provided with full administrative permissions. We may have to list the exact permissions that we need. Therefore, I will also be providing the minimal permissions needed by the administrator user for each applicable recipe with the code files.
  • An S3 bucket with default permissions. I will be using a bucket name of awsseccookbook. S3 bucket names are globally unique. Therefore, select an available name and replace my bucket with your bucket name wherever applicable. 
  • Check the contents of the S3 bucket from the CLI using testuser and verify that it has no permissions:

How to do it...

First, we will create IAM policies from the Management Console using the IAM policy editor. Then, we will create the same policy from the AWS CLI. 

Creating policies with the IAM visual editor

We can create a policy using the IAM visual editor as follows:

  1. Log in to the console as an administrator and go to the IAM dashboard.
  2. Click on Policies from the left sidebar. 
  3. Click on Create Policy. This will provide us with a visual editor:

We can also click on the JSON tab and enter the JSON directly if we have already created the policy JSON.

  1. Set the Service to S3.
  2. Select ListBucket under Actions.
  3. Under Resources, select Specific, click on Add ARN, and enter our bucket's ARN in the format arn:aws:s3:::<bucket_name>.
  4. Under Request conditions, click Add condition and add a condition, as follows, with an EPOCH time from the future (we can find many online tools that do the time conversion for us):


Click Add

  1. Click Review Policy
  2. Provide a name (for example, MyS3ListPolicy), add a description (for example, My S3 ListPolicy), and click Create Policy.
  3. Verify the policy that was generated from the JSON tab:

  1. Click on Groups from the left sidebar of the IAM dashboard and go to our testuser group. Click on Attach Policy and attach the policy we created in the previous step.
You can also attach policies to groups or users from the Policy tab of the IAM dashboard. 
  1. Verify this by running the s3 ls command from the command line with the testuser profile name (the same command from the Getting ready section). We should see a successful response, as follows:

Now, let's look at how to create policies using the AWS CLI.

Creating policies using the AWS CLI

In this section, we will create a policy with the JSON we generated in the previous recipe. If you are following along from the previous section, detach the current policy from the group (or user) and confirm that the testuser user cannot list the contents of the bucket. Let's get started:

  1. Create a file called my-s3-list-bucket-policy.json with the following JSON policy:
"Version": "2012-10-17",
"Statement": [
"Sid": "MyS3ListBucketPolicy",
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::awsseccookbook",
"Condition": {
"DateLessThan": {
"aws:EpochTime": "1609415999"

The preceding policy will only allow access if the current EPOCH timestamp is less than the EPOCH timestamp represented by the value of aws:EpochTime. The value of 1609415999 in the preceding policy denotes Thursday, 31 December 2020 11:59:59 GMT. We can use one of the free EPOCH time converters available online to generate an EPOCH time corresponding to a date we want to test the policy with.

  1. Create the policy using the create-policy subcommand:
aws iam create-policy \
--policy-name MyS3ListPolicyCLI \
--policy-document file://resources/my-s3-list-bucket-policy.json \
--profile awssecadmin

This should return the policy's details, along with its ARN:

  1. Attach the policy to the group using the attach-group-policy subcommand while providing the policy ARN from the previous command:
aws iam attach-group-policy \
--group-name testusergroup \
--policy-arn arn:aws:iam::135301570106:policy/MyS3ListPolicyCLI \
--profile awssecadmin
  1. Verify that our testuser user can now list the files in the S3 bucket:

How it works...

In this recipe, we created an IAM policy from the console and the CLI. IAM policies are JSON documents and follow a structure that is followed by most policy types within AWS, with the exception of access control lists (ACLs), which are XML-based.

The policy document is composed of statements that are added as arrays to the Statement element. A Statement element for an IAM policy may contain the following subelements:

  • Sid is the statement ID, which is optional. This can be used to provide a description of the policy.
  • Effect specifies whether we want to allow or deny access to a resource. The supported values are Allow and Deny.
  • Action specifies the permission or permissions (s3:ListBucket) for which this statement has been applied: 

We can also specify * to denote any action.

  • Resource specifies the ARN of the resource (for example, S3 bucket) that the statement is applied to. For S3 buckets, ARN should follow the following format: arn:aws:s3:::<bucket_name>/<key_name>.
    We can use a comma to separate multiple values. We can specify * to denote any resources.
  • Condition allows us to conditionally execute policies. We use Boolean operators to match the condition against values in the request. For example, the following condition checks whether a canned ACL of "public-read" is used in the request:

"Condition": { 
"StringEquals": {
"s3:x-amz-acl": [

There are conditional keys that are common to all AWS services that support policies: those that are specific to S3 bucket operations and those that are specific to S3 object operations. In this recipe, we added a condition to check whether the current time is less than a particular time as an EPOCH timestamp. This is an optional element. We will look at conditions in a bit more detail in Chapter 2Securing Data on S3 with Policies and Techniques.

There's more...

Let's quickly go through some important concepts related to policies in AWS:

  • Types of AWS policies include identity-based policies (for example, IAM policies), resource-based policies (for example, S3 bucket policies and IAM role trust policies), permissions boundaries, an organization's service control policy (SCP), ACLs, and session policies. 
  • An AWS IAM policy's type can be either AWS managed, Job function, or Customer managed. We can check the type from the console on the Policies page within IAM:

  • Job function is a subset of AWS managed and is designed to align with common IT job functions. The current list of job functions includes Administrator, Billing, Database Administrator, Data Scientist, Developer Power User, Network Administrator, Security Auditor, Support User, System Administrator, and View-Only User.
  • AWS Policy Generator can generate the following policies: IAM Policy, S3 Bucket Policy, SNS Topic Policy, a VPC Endpoint Policy, and an SQS Queue Policy. It is currently available at
  • If there is an allow and deny effect for the same action and resource in a policy, deny will always take precedence.
  • An IAM policy cannot be used to grant permissions for anonymous users, unlike S3 ACL and the Bucket Policy.
  • The IAM policy cannot be applied to a root user and can only be applied to IAM users.
  • The NotPrincipal policy element denotes the principal entity to deny access. 
  • NotAction excludes the specified list of actions. 
  • The following are some of the predefined condition keys that are supported by all AWS services that support IAM access control: aws:CurrentTime, aws:EpochTime, aws:MultiFactorAuthAge, aws:MultiFactorAuthPresent, aws:PrincipalOrgID, aws:PrincipalArn, aws:RequestedRegion, aws:SecureTransport, and aws:UserAgent.

See also


Creating a master account for AWS Organizations

In this recipe, we will learn how to set up an AWS master account for AWS Organizations. Many organizations have multiple AWS accounts for development, deployment (production), and more. The AWS Organizations service helps us centrally manage all our AWS accounts. 

Getting ready

We'll need a working AWS account to complete this recipe.

How to do it...

We can create a master account with AWS Organizations as follows:

  1. Log in to the console as an administrator and go to the AWS Organizations service dashboard:

  1. Click on Create organization. We will be shown a popup containing important details and restrictions:

  1. Click on Create organization in the popup.
  2. AWS will now send a verification email to the account's registered email address. Verify your email to finish setting up the master account. The master account will be denoted by a star next to the account name in the Accounts tab.
  1. Go to the Organize accounts tab. Click on the New organizational unit tab and create two organizational units (OUs):

We will create accounts under the OUs in the next recipe.

How it works...

In this recipe, we created an AWS Organizations master account and a few OUs under it. The AWS Organizations service dashboard has three tabs now. The Accounts tab contains the account name, email, account ID, and status for all accounts, including the master account. The master account is denoted by a star next to the account name. We can create OUs and manage the hierarchy structure of OUs and accounts in the Organize accounts tab.

We can create sub-OUs within an OU. We can move an account to an OU by navigating to the root or OU that currently contains the account, selecting the account, and choosing Move. The third tab, Policies, within the Organizations dashboard allows us to create and manage policies. We can attach a policy to an OU by going to the Organize accounts tab, selecting the OU from the list, and then attaching the policy in the details pane. 

There's more...

Let's quickly go through some important details about the AWS Organizations service:

  • The AWS Organizations service is supported in all regions; however, the endpoints are located in US East (N. Virginia) for commercial organizations and AWS GovCloud (US-West) for AWS GovCloud (US) organizations.
  • We can use the AWS Organizations service using one of the following: AWS Management Console, the AWS Organizations Query API, AWS CLI, or AWS SDKs.
  • The AWS Organizations service is a global service. We don't need to select or specify any region to create organization entities.
  • There is no additional cost for using AWS Organizations.
  • The number of accounts we can manage within an AWS Organization varies for accounts. We can ask AWS Support to increase this limit.
  • We can only initiate the creation of a new organization from an AWS account that is not a member of any organization. We cannot change the master account once created.
  • An account can only be part of one organization at a time and within an organization, an account can only be part of one OU at a time. 
  • We can nest the hierarchy of OUs and accounts up to 5 levels (including root).
  • We can use SCPs to restrict AWS service actions to root accounts, IAM users, and IAM roles in the accounts of our organization.
  • SCPs can only deny access; they cannot allow access.
  • When both the permissions boundary (an IAM feature) and SCP are present, the action is only allowed if the permission boundary, the SCP, and the identity-based policy all allow the action.
  • We can integrate supported services with AWS Organizations to manage services across accounts. The current supported list of services that can be integrated includes AWS Artifact, AWS CloudTrail, Amazon CloudWatch Events, AWS Config, AWS Directory Service, AWS Firewall Manager, AWS License Manager, AWS RAM, AWS Service Catalog, and AWS Single Sign-On. We can enable integration from the supported service's dashboard.

We can enable SCP for our organization as follows:

  1. Go to the AWS Organizations service in the master account's console.
  2. Go to the Organize accounts tab.
  1. Click on Root from the left sidebar. We should see the ENABLE/DISABLE POLICY TYPES section on the right pane.
  2. Click Enable for Service control policies.

After enabling SCP for an organization, we can add an SCP as follows:

  1. Go to the AWS Organizations service in the master account's console.
  2. Go to the Policies tab.
  3. Click on Service control policies.
  4. Click on Create policy.
  5. Provide a Policy name and Description.
  6. Add a policy, as follows:
"Version": "2012-10-17",
"Statement": [
"Effect": "Deny",
"Action": "cloudtrail:StopLogging",
"Resource": "*"

This policy will restrict anyone within the OU.

  1. Click on Create policy.
  2. Click on Root or an OU from the left sidebar.
  3. Click on Service control policies on the right pane.
  4. Click on Attach against our new policy.

See also


Creating a new account under an AWS Organization

In this recipe, we will create a new OU called Test. We will create an AWS account from the CLI under one of those OUs. We will also look at account creation from the console. 

Getting ready

You'll need to create an AWS Organization account with a master account to complete this recipe. Follow the Creating a master account for AWS Organizations recipe to do so.

For executing the command from the CLI, we need to configure AWS CLI with credentials for a user with administrator access in your master account. I will be using a user with a CLI profile called awssecadmin.

How to do it...

In this recipe, we will create accounts using CLI commands. After that, we will discuss account creation from the console.

Creating an account and OU from the CLI

Follow these steps from the AWS CLI:

  1. We can create an AWS account from the CLI using the create-account subcommand, like so:
aws organizations create-account \
--email [email protected] \
--account-name awsseccookbookchild1 \
--profile awssecadmin

This should give us the following response:

  1. We can check the status of our request using the describe-create-account-status subcommand by providing the request ID we received in the previous step:
aws organizations describe-create-account-status \
--create-account-request-id car-bb6f15308b7311e98b7112a0c7517226 \
--profile awssecadmin

If the request succeeded, we should get the following response:

  1. We can verify that the account was created under ROOT and get the root's ID using the list-parents subcommand using the account ID we received in the previous step:
aws organizations list-parents \
--child-id 380701114427 \
--profile awssecadmin

This should give us the following response:

  1. Create an OU called Test under root using the create-organizational-unit subcommand using the ID of the root we received in the previous step:
aws organizations create-organizational-unit \
--parent-id r-9dp3 \
--name Test \
--profile awssecadmin

This should give us the following response:

  1. Move our new account from root into our new OU while providing the account ID, root's ID, and OU's ID from the previous steps using the move-account subcommand, like so:
aws organizations move-account \
--account-id 380701114427 \
--source-parent-id r-9dp3 \
--destination-parent-id ou-9dp3-moeksvq4 \
--profile awssecadmin

This command does not return anything.

  1. Check the parent for our account using the list-parents subcommand, as we did in step 3. We should get a response with the OU as the parent:

  1. We can list all the OUs under root using the list-children subcommand with the child type set to ORGANIZATIONAL_UNIT:
aws organizations list-children \
--parent-id r-9dp3 \
--profile awssecadmin

This should give us the following response if we have a total of three OUs, assuming we created two in the previous recipe:

To get details of the OU, along with its name, we can use the describe-organizational-unit subcommand with a single parameter named organizational-unit-id by passing in the ID.

Creating and moving an account from the console

Since we already saw how to create OUs from the console in the previous recipe, we will only discuss creating an account in this section. Let's get started:

  1. Log in as an administrator in the master account and go to the AWS Organizations dashboard.
  2. Go to the Accounts tab and click on Add Account. We will be provided with options to either invite an account or create one.
  3. Click on Create Account and enter values for Full name and Email. Note that the default role is populated as OrganizationAccountAccessRole:

Full name here will be our account name. We can change the account name later by logging into the account with the root user email. We can reset the password using the Forgot password option the first time we sign in as the root account. 
  1. Click on Create to create the account. If you are unable to create the account due to the limit being reached, please contact AWS support. This limit varies from account to account. If successful, we should see all three accounts (master, child1, and child2) under the Accounts tab. 
Removing an account from an organization lets us run the account as a standalone account. If we try to remove the newly created account now, we will get an error stating that the sign-in process for the account hasn't been completed. To work as a standalone account, we need to sign in as a root user and provide additional information, including credit card details.
  1. We can add the newly created account under the Prod OU as follows:
    1. Go to the Organize Accounts tab.
    2. Select the account to move (child2, in this case) and click Move.
    3. From the popup, select Prod and click Move.
    4. Go inside the configuration for the Prod OU by clicking on it and verifying whether the account is under it.

How it works...

In this recipe, we created an account from the CLI using the create-account subcommand. This command works asynchronously and returns immediately with a request ID. We can check the status of our request using the describe-create-account-status subcommand while providing the request ID. To check whether an account was created, we can check the AWS CloudTrail log for the CreateAccountResult event.

The create-account subcommand also accepts other parameters, namely role-name and iam-user-access-to-billing. The role-name parameter is used to specify the name of an IAM role that will be automatically pre-configured in the new member account. This role provides administrator permissions to the member account and trusts the master account. This means that users in the master account can assume the role, provided the master account administrator allows this. The default value is OrganizationAccountAccessRole. If we log in to the child account and check the OrganizationAccountAccessRole role, we will see that it has the Administrator Access policy attached to it. If we check the Trust relationships section, we will see that our master account has been added as a trusted entity. An administrator from the master account can now switch roles to the child account and have administrator access. 

The iam-user-access-to-billing parameter needs to be set to ALLOW for IAM users to access account billing information. If it is set to DENY, only the root user can access account billing information. The default value is ALLOW.  We also created an OU and moved our account under the OU. Within the examples, we used the list-children subcommand with the child type as ORGANIZATIONAL_UNIT to list all the OUs under root. We can set child-type to ACCOUNT to list all the accounts instead. 

There's more...

Let's quickly go through some of the other useful AWS CLI subcommands for AWS Organizations:

  • create-gov-cloud-account can be used to create accounts in the AWS GovCloud (US) region if we are authorized to do so.
  • invite-account-to-organization sends an invitation to another account to join our organization.
  • remove-account-from-organization removes an account from the organization.
  • create-organization creates an AWS Organization, while delete-organization deletes an AWS Organization
  • leave-organization removes an account from its parent organization. 
  • create-organizational-unit creates an OU, while delete-organizational-unit deletes an OU. To delete an OU, we must remove all accounts and child OUs.
  • update-organizational-unit renames an OU. 
  • describe-account retrieves information about that account and should be called from the master account. describe-organization retrieves information about the organization. describe-organizational-unit retrieves information about an OU.
  • list-accounts lists all the accounts in the organization. list-accounts-for-parent lists the child accounts of the given target root or OU. list-create-account-status lists the account creation requests that match the given status. list-roots lists the roots that are defined in the current organization.
  • tag-resource and untag-resource can be used for managing tags.

See also


Switching roles with AWS Organizations

In this recipe, we will learn how to switch from the master account to a member account from within the console. Switching between accounts from the console without having to log out from AWS is a great feature that is used extensively in many organizations. For example, a user may be given a basic user in one account and they can switch to other accounts with the appropriate roles (for example, Admin for Dev and ReadOnly for Prod).

Getting ready

We need to create a master account and a child account with AWS Organizations. We can do this by following the Creating a master account for AWS Organizations and Creating a new account under an Organization recipes of this chapter.

How to do it...

First, we'll learn how to switch between accounts as an administrator user in the master account and then allow a non-admin user to switch accounts.

Switching as an administrator

An administrator from the master account can switch into a child account by following these steps:

  1. Log in to the master account as an IAM user with administrator permissions.
  1. Click on the drop-down menu next to username and click on Switch Role:

  1. On the role switch page, click Switch Role.
  2. On the next screen, enter the following:
    1. Enter the account ID of the child account (available from AWS Organization's Account tab).
    2. Set the Role to OrganizationAccountAccessRole.
    3. Enter a value for Display Name (for example, [email protected]):

We should be logged in to our child account with the specified role. We can verify these details from the dropdown next to our account name:

  1. Switch back to the parent account by clicking on the Back to awssecadmin link from the dropdown. If we try to switch roles with a non-admin user by following the preceding steps (with no permissions attached), switching roles will fail with an error, as follows: 

Now, let's look at how to grant permission for a non-admin user in order to switch roles.

Granting permission for a non-admin user to switch roles

For switching role, the non-admin user should be given the AssumeRole permission for the role on the master account. Let's take a look:

  1. Sign in to the master account as an administrator.
  2. Create a policy that allows AssumeRole on the child account role, that is, OrganizationAccountAccessRole:
"Version": "2012-10-17",
"Statement": [
"Sid": "AssumeRoleForChildAccount",
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": "arn:aws:iam::380701114427:role/OrganizationAccountAccessRole"

Save this policy as AssumeRolePolicyChild1.

  1. Attach this policy to our testusergroup group. 
  2. Sign out and sign back in as testuser user.
  3. Follow the steps in the previous section and enter the following details on the Switch Role screen:

  1. Click on Switch Role.

This time, we should be able to switch role into the new account. We can verify this from the drop-down menu next to our account name in the taskbar:

In this recipe, a user with no permission in the master account received full administrator access in the child account. In the real world, administrators will create different roles in different child accounts (for example, Dev, Testing, Prod, and so on) and then the user groups in the master account will be granted access to the respective roles in those accounts.

Granting permission for a non-admin user to switch roles using the CLI

We can grant permission for a non-admin user from the CLI as follows:

  1. Create a policy document that allows AssumeRole on the child account role, that is, OrganizationAccountAccessRole and save it as assume-role-policy-document.json. Refer to the previous section for the JSON document structure.
  2. Create the policy, as follows:
aws iam create-policy \
--policy-name MyAssumeRolePolicyCLI \
--policy-document file://resources/assume-role-policy-document.json \
--profile awssecadmin

We should get the following response:

  1. Attach this policy to the user group:
aws iam attach-group-policy \
--group-name testusergroup \
--policy-arn arn:aws:iam::135301570106:policy/MyAssumeRolePolicyCLI \
--profile awssecadmin

We should now be able to switch roles.

How it works...

In this recipe, we switched roles from our master account to a child account within an AWS Organization without any additional configuration. Then, we granted permission for another non-admin user's group to assume the default role, that is, OrganizationAccountAccessRole, that was created by AWS as part of creating the child account. 

Both roles and users are AWS identities with permission policies that specify what they can do. Users have standard credentials such as password or access keys. However, users, groups, applications, or other AWS services can assume a role and will be provided with temporary security credentials for the role session.

Granting permissions to allow access to resources that we control is called delegation. To perform delegation, we need to set up a trust between the account that owns the resource (the trusting account) and the account with users that need access (the trusted account). The trusting and trusted accounts can be the same account or different accounts. 

While delegating permission, in addition to the standard permissions policy that grants the user the needed permissions, the IAM role in the trusting account will also have a trust policy defined. The trust policy specifies which accounts are allowed to assume the role. The trust policy is written in JSON format according to the rules of the IAM policy language.

As we saw in the previous recipe, the master account is added as a trusted entity by default when we created the member under our organization. In this recipe, the trusted account (master account) granted further permission for the testusergroup to assume the default role from the member account through a policy. This policy granted the AssumeRole permission of the Security Token Service (STS) service.

In this recipe, we didn't create any role since AWS already created one for us. The create-role CLI command can be used to create a role. The get-role command gathers information about a role, while delete-role can be used to delete a role. update-role can be used to update the description or maximum session duration for the role.

Switching roles between any two accounts

Please note that it is not necessary for the accounts to be a part of an AWS Organization to perform role switching. This can be configured between any two accounts. To allow a user group, for example, testusergroup, from account A to switch role to account B, we can follow these steps:

  1. Create a policy in account B with required access permissions to resources in account B.
  2. Create a role in account B with the trusted entity as account A and attach the policy we created in the previous step.
  3. Account A's admin should grant the STS:AssumeRole permission for the role we created in the previous step by providing the complete role ARN to the required users or groups in account A so that they can assume that role from account B.
  4. Verify the setup by signing in as a user from testusergroup into account A and switch roles to account B.

There's more...

Let's quickly go through some important details about IAM roles:

  • The trust policy for a role allows a user in the trusted account to switch to or assume that role.
  • A wildcard (*) cannot be specified as a principal for a trust policy.
  • When a user assumes a role, it temporarily gives up its own permissions until the user stops using the role.
  • Some services allow attaching a policy directly to a resource without needing to use a role as a proxy. These resources include S3 buckets, Glacier vaults, Amazon simple notification service (SNS) topics, and Amazon simple queue service (SQS) queues. 
  • Roles can be used by the external users authenticated by an external identity provider service to get access to AWS resources. Roles allow mobile apps to use AWS resources without embedding AWS keys within the app.
  • Role chaining is the process where a role assumes a second role through the AWS CLI or API.
  • To pass the role information to an EC2 instance when the instance starts, we can add the role within an instance profile. An instance profile can be considered a container for an IAM role. The list-instance-profiles-for-role CLI command lists the instance profiles for a role. 
  • The permissions boundary is a feature we can use to set the maximum permissions that an identity-based policy can grant to an IAM entity such as a user or role. The put-role-permissions-boundary CLI command creates or updates the permissions boundary for a role, while delete-role-permissions-boundary deletes the permissions boundary for the role. 
  • The attach-role-policy CLI command attaches a policy to a role, while detach-role-policy detaches a policy from a role.
  • The put-role-policy CLI command creates or updates an inline policy, get-role-policy retrieves the specified inline policy in a role, and delete-role-policy deletes the specified inline policy.

See also

About the Author

  • Heartin Kanikathottu

    Heartin Kanikathottu is an author, architect, and tech evangelist with over 12 years of IT experience. He has worked for companies including VMware, IG Infotech, Software AG, SAP Ariba, American Express, and TCS. His degrees include a B-Tech in computer science, an MS in cloud computing, and an M-Tech in software systems. He has over 10 professional certifications in the areas of the cloud, security, coding, and design from providers such as AWS, Pivotal, Oracle, Microsoft, IBM, and Sun. His blogs on computer science, the cloud, and programming have followers from countries across the globe. He mentors others and leads technical sessions at work, meetups, and conferences. He likes reading and maintains a big library of technical, fictional, and motivational books.

    Browse publications by this author

Latest Reviews

(2 reviews total)
livre bien et tres lisible
Very good updated contents

Recommended For You

Book Title
Access this book, plus 7,500 other titles for FREE
Access now