Movatterモバイル変換


[0]ホーム

URL:


Using an IAM role in the AWS CLI - AWS Command Line Interface
DocumentationAWS Command Line InterfaceUser Guide for Version 2
PrerequisitesOverview of using IAM rolesConfiguring and using a roleUsing MFACross-account roles and external IDSpecifying a role session name for easier auditingAssume role with web identityClearing cached credentials

Using an IAM role in the AWS CLI

AnAWS Identity and Access Management (IAM) role is an authorization tool that lets a user gain additional (or different) permissions, or get permissions to perform actions in a different AWS account.

Prerequisites

To run theiam commands, you need to install and configure the AWS CLI. This includes setting up a configured profile, as assuming a role is paired with another credential method. For more information, seeInstalling or updating to the latest version of the AWS CLI.

Overview of using IAM roles

You can configure the AWS Command Line Interface (AWS CLI) to use an IAM role by defining a profile for the role in the~/.aws/config file.

The following example shows a role profile namedmarketingadmin. If you run commands with--profile marketingadmin (or specify it with theAWS_PROFILE environment variable), the AWS CLI uses the credentials defined in a separate profileuser1 to assume the role with the Amazon Resource Name (ARN)arn:aws:iam::123456789012:role/marketingadminrole. You can run any operations that are allowed by the permissions assigned to that role.

[profilemarketingadmin]role_arn = arn:aws:iam::123456789012:role/marketingadminrolesource_profile = user1

You can then specify asource_profile that points to a separate named profile that contains user credentials with permission to use the role. In the previous example, themarketingadmin profile uses the credentials in theuser1 profile. When you specify that an AWS CLI command is to use the profilemarketingadmin, the AWS CLI automatically looks up the credentials for the linkeduser1 profile and uses them to request temporary credentials for the specified IAM role. The CLI uses thests:AssumeRole operation in the background to accomplish this. Those temporary credentials are then used to run the requested AWS CLI command. The specified role must have attached IAM permission policies that allow the requested AWS CLI command to run.

To run a AWS CLI command from within an Amazon Elastic Compute Cloud (Amazon EC2) instance or an Amazon Elastic Container Service (Amazon ECS) container, you can use an IAM role attached to the instance profile or the container. If you specify no profile or set no environment variables, that role is used directly. This enables you to avoid storing long-lived access keys on your instances. You can also use those instance or container roles only to get credentials for another role. To do this, you usecredential_source (instead ofsource_profile) to specify how to find the credentials. Thecredential_source attribute supports the following values:

  • Environment – Retrieves the source credentials from environment variables.

  • Ec2InstanceMetadata – Uses the IAM role attached to the Amazon EC2 instance profile.

  • EcsContainer – Uses the IAM role attached to the Amazon ECS container.

The following example shows the samemarketingadminrole role used by referencing an Amazon EC2 instance profile.

[profile marketingadmin]role_arn = arn:aws:iam::123456789012:role/marketingadminrolecredential_source = Ec2InstanceMetadata

When you invoke a role, you have additional options that you can require, such as the use of multi-factor authentication and an External ID (used by third-party companies to access their clients' resources). You can also specify unique role session names that can be more easily audited in AWS CloudTrail logs.

Configuring and using a role

When you run commands using a profile that specifies an IAM role, the AWS CLI uses the source profile's credentials to call AWS Security Token Service (AWS STS) and request temporary credentials for the specified role. The user in the source profile must have permission to callsts:assume-role for the role in the specified profile. The role must have a trust relationship that allows the user in the source profile to use the role. The process of retrieving and then using temporary credentials for a role is often referred to asassuming the role.

You can create a role in IAM with the permissions that you want users to assume by following the procedure underCreating a Role to Delegate Permissions to an IAM user in theAWS Identity and Access Management User Guide. If the role and the source profile's user are in the same account, you can enter your own account ID when configuring the role's trust relationship.

After creating the role, modify the trust relationship to allow the user to assume it.

The following example shows a trust policy that you could attach to a role. This policy allows the role to be assumed by any user in the account 123456789012,if the administrator of that account explicitly grants thests:AssumeRole permission to the user.

JSON

The trust policy doesn't actually grant permissions. The administrator of the account must delegate the permission to assume the role to individual users by attaching a policy with the appropriate permissions. The following example shows a policy that you can attach to a user that allows the user to assume only themarketingadminrole role. For more information about granting a user access to assume a role, seeGranting a User Permission to Switch Roles in theIAM User Guide.

JSON

The user doesn't need to have additional permissions to run the AWS CLI commands using the role profile. Instead, the permissions to run the command come from those attached to therole. You attach permission policies to the role to specify which actions can be performed against which AWS resources. For more information about attaching permissions to a role (which works identically to a user), seeChanging Permissions for an IAM user in theIAM User Guide.

Now that you have the role profile, role permissions, role trust relationship, and user permissions correctly configured, you can use the role at the command line by invoking the--profile option. For example, the following calls the Amazon S3ls command using the permissions attached to themarketingadmin role as defined by the example at the beginning of this topic.

$aws s3 ls --profilemarketingadmin

To use the role for several calls, you can set theAWS_PROFILE environment variable for the current session from the command line. While that environment variable is defined, you don't have to specify the--profile option on each command.

Linux or macOS

$export AWS_PROFILE=marketingadmin

Windows

C:\>setx AWS_PROFILE marketingadmin

For more information about configuring users and roles, seeIAM Identities (users, user groups, and roles) andIAM roles in theIAM User Guide.

Using multi-factor authentication

For additional security, you can require that users provide a one-time key generated from a multi-factor authentication (MFA) device, a U2F device, or mobile app when they attempt to make a call using the role profile.

First, you can choose to modify the trust relationship on the IAM role to require MFA. This prevents anyone from using the role without first authenticating by using MFA. For an example, see theCondition line in the following example. This policy allows the user namedanika to assume the role the policy is attached to, but only if they authenticate by using MFA.

JSON

Next, add a line to the role profile that specifies the ARN of the user's MFA device. The following sampleconfig file entries show two role profiles that both use the access keys for the useranika to request temporary credentials for the rolecli-role. The useranika has permissions to assume the role, granted by the role's trust policy.

[profile role-without-mfa]region = us-west-2role_arn= arn:aws:iam::128716708097:role/cli-rolesource_profile=cli-user[profile role-with-mfa]region = us-west-2role_arn= arn:aws:iam::128716708097:role/cli-rolesource_profile = cli-usermfa_serial = arn:aws:iam::128716708097:mfa/cli-user[profile cli-user]region = us-west-2output = json

Themfa_serial setting can take an ARN, as shown, or the serial number of a hardware MFA token.

The first profile,role-without-mfa, doesn't require MFA. However, because the previous example trust policy attached to the role requires MFA, any attempt to run a command with this profile fails.

$aws iam list-users --profile role-without-mfaAn error occurred (AccessDenied) when calling the AssumeRole operation: Access denied

The second profile entry,role-with-mfa, identifies an MFA device to use. When the user attempts to run a AWS CLI command with this profile, the AWS CLI prompts the user to enter the one-time password (OTP) that the MFA device provides. If the MFA authentication succeeds, the command performs the requested operation. The OTP is not displayed on the screen.

$aws iam list-users --profile role-with-mfaEnter MFA code for arn:aws:iam::123456789012:mfa/cli-user:{ "Users": [{ ...

Cross-account roles and external ID

You can enable users to use roles that belong to different accounts by configuring the role as a cross-account role. During role creation, set the role type toAnother AWS account, as described inCreating a Role to Delegate Permissions to an IAM user. Optionally, selectRequire MFA.Require MFA configures the appropriate condition in the trust relationship, as described inUsing multi-factor authentication.

If you use anexternal ID to provide additional control over who can use a role across accounts, you must also add theexternal_id parameter to the role profile. You typically use this only when the other account is controlled by someone outside your company or organization.

[profile crossaccountrole]role_arn = arn:aws:iam::234567890123:role/SomeRolesource_profile = defaultmfa_serial = arn:aws:iam::123456789012:mfa/saanviexternal_id =123456

Specifying a role session name for easier auditing

When many individuals share a role, auditing becomes more of a challenge. You want to associate each operation invoked with the individual who invoked the action. However, when the individual uses a role, the assumption of the role by the individual is a separate action from the invoking of an operation, and you must manually correlate the two.

You can simplify this by specifying unique role session names when users assume a role. You do this by adding arole_session_name parameter to each named profile in theconfig file that specifies a role. Therole_session_name value is passed to theAssumeRole operation and becomes part of the ARN for the role session. It is also included in the AWS CloudTrail logs for all logged operations.

For example, you could create a role-based profile as follows.

[profile namedsessionrole]role_arn = arn:aws:iam::234567890123:role/SomeRolesource_profile = defaultrole_session_name =Session_Maria_Garcia

This results in the role session having the following ARN.

arn:aws:iam::234567890123:assumed-role/SomeRole/Session_Maria_Garcia

Also, all AWS CloudTrail logs include the role session name in the information captured for each operation.

Assume role with web identity

You can configure a profile to indicate that the AWS CLI should assume a role usingweb identity federation and Open ID Connect (OIDC). When you specify this in a profile, the AWS CLI automatically makes the corresponding AWS STSAssumeRoleWithWebIdentity call for you.

To retrieve and use temporary credentials using web identity federation, you can specify the following configuration values in a shared profile.

role_arn

Specifies the ARN of the role to assume.

web_identity_token_file

Specifies the path to a file which contains an OAuth 2.0 access token or OpenID Connect ID token that is provided by the identity provider. The AWS CLI loads this file and passes its content as theWebIdentityToken argument of theAssumeRoleWithWebIdentity operation.

role_session_name

Specifies an optional name applied to this assume-role session.

The following is an example of the minimal amount of configuration needed to configure an assume role with web identity profile.

# In ~/.aws/config[profile web-identity]role_arn=arn:aws:iam:123456789012:role/RoleNameToAssumeweb_identity_token_file=/path/to/a/token

You can also provide this configuration by usingenvironment variables.

AWS_ROLE_ARN

The ARN of the role to assume.

AWS_WEB_IDENTITY_TOKEN_FILE

The path to the web identity token file.

AWS_ROLE_SESSION_NAME

The name applied to this assume-role session.

Clearing cached credentials

When you use a role, the AWS CLI caches the temporary credentials locally until they expire. The next time you try to use them, the AWS CLI attempts to renew them on your behalf.

If your role's temporary credentials arerevoked, they are not renewed automatically, and attempts to use them fail. However, you can delete the cache to force the AWS CLI to retrieve new credentials.

Linux or macOS

$rm -r ~/.aws/cli/cache

Windows

C:\>del /s /q %UserProfile%\.aws\cli\cache
Short-term credentials
IAM users

[8]
ページ先頭

©2009-2025 Movatter.jp