AWS SDK 또는 CLI로 AssumeRole 사용하기

AWS SDK 또는 CLI로 AssumeRole 사용하기

이 코드 예제들은 AssumeRole을 사용하는 방법을 보여드려요. 액션 예제는 더 큰 프로그램에서 발췌한 코드 조각이라 맥락 안에서 실행해야 해요. 이 액션의 맥락은 다음 코드 예제에서 확인할 수 있어요.

출처: 문서

본문

  • MFA 토큰이 필요한 IAM 역할 맡기
  • 페더레이션 사용자를 위한 URL 구성

.NET (SDK for .NET)

Note GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예제와 설정·실행 방법을 확인할 수 있어요.

using System;
using System.Threading.Tasks;
using Amazon;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;

namespace AssumeRoleExample
{
	class AssumeRole
	{
		/// <summary>
		/// This example shows how to use the AWS Security Token
		/// Service (AWS STS) to assume an IAM role.
		///
		/// NOTE: It is important that the role that will be assumed has a
		/// trust relationship with the account that will assume the role.
		///
		/// Before you run the example, you need to create the role you want to
		/// assume and have it trust the IAM account that will assume that role.
		///
		/// See https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html
		/// for help in working with roles.
		/// </summary>

		// A region property may be used if the profile or credentials loaded do not specify a region,
		// or to use a specific region.
		private static readonly RegionEndpoint REGION = RegionEndpoint.USWest2;

		static async Task Main()
		{
		// Create the SecurityToken client and then display the identity of the
		// default user.
		var roleArnToAssume = "arn:aws:iam::123456789012:role/testAssumeRole";

		var client = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(REGION);

		// Get and display the information about the identity of the default user.
		var callerIdRequest = new GetCallerIdentityRequest();
		var caller = await client.GetCallerIdentityAsync(callerIdRequest);
		Console.WriteLine($"Original Caller: {caller.Arn}");

		// Create the request to use with the AssumeRoleAsync call.
		var assumeRoleReq = new AssumeRoleRequest()
		{
			DurationSeconds = 1600,
			RoleSessionName = "Session1",
			RoleArn = roleArnToAssume
		};

		var assumeRoleRes = await client.AssumeRoleAsync(assumeRoleReq);

		// Now create a new client based on the credentials of the caller assuming the role.
		var client2 = new AmazonSecurityTokenServiceClient(credentials: assumeRoleRes.Credentials, REGION);

		// Get and display information about the caller that has assumed the defined role.
		var caller2 = await client2.GetCallerIdentityAsync(callerIdRequest);
		Console.WriteLine($"AssumedRole Caller: {caller2.Arn}");
		}
	}
}

API 상세는 AssumeRole in AWS SDK for .NET API Reference를 참고해요.

Bash (AWS CLI with Bash script)

Note GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예제와 설정·실행 방법을 확인할 수 있어요.

###############################################################################
# function iecho
#
# This function enables the script to display the specified text only if
# the global variable $VERBOSE is set to true.
###############################################################################
function iecho() {
	if [[ $VERBOSE == true ]]; then
		echo "$@"
	fi
}

###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
	printf "%s\n" "$*" 1>&2
}

###############################################################################
# function sts_assume_role
#
# This function assumes a role in the AWS account and returns the temporary
# credentials.
#
# Parameters:
# -n role_session_name -- The name of the session.
# -r role_arn -- The ARN of the role to assume.
#
# Returns:
# [access_key_id, secret_access_key, session_token]
# And:
# 0 - If successful.
# 1 - If an error occurred.
###############################################################################
function sts_assume_role() {
	local role_session_name role_arn response
	local option OPTARG # Required to use getopts command in a function.

	# bashsupport disable=BP5008
	function usage() {
		echo "function sts_assume_role"
		echo "Assumes a role in the AWS account and returns the temporary credentials:"
		echo " -n role_session_name -- The name of the session."
		echo " -r role_arn -- The ARN of the role to assume."
		echo ""
	}

	while getopts n:r:h option; do
		case "${option}" in
		n) role_session_name=${OPTARG} ;;
		r) role_arn=${OPTARG} ;;
		h)
			usage
			return 0
			;;
		\?)
			echo "Invalid parameter"
			usage
			return 1
			;;
		esac
	done

	response=$(aws sts assume-role \
		--role-session-name "$role_session_name" \
		--role-arn "$role_arn" \
		--output text \
		--query "Credentials.[AccessKeyId, SecretAccessKey, SessionToken]")

	local error_code=${?}

	if [[ $error_code -ne 0 ]]; then
		aws_cli_error_log $error_code
		errecho "ERROR: AWS reports create-role operation failed.\n$response"
		return 1
	fi

	echo "$response"

	return 0
}

API 상세는 AssumeRole in AWS CLI Command Reference를 참고해요.

C++ (SDK for C++)

Note GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예제와 설정·실행 방법을 확인할 수 있어요.

bool AwsDoc::STS::assumeRole(const Aws::String &roleArn,
	const Aws::String &roleSessionName,
	const Aws::String &externalId,
	Aws::Auth::AWSCredentials &credentials,
	const Aws::Client::ClientConfiguration &clientConfig) {
	Aws::STS::STSClient sts(clientConfig);
	Aws::STS::Model::AssumeRoleRequest sts_req;

	sts_req.SetRoleArn(roleArn);
	sts_req.SetRoleSessionName(roleSessionName);
	sts_req.SetExternalId(externalId);

	const Aws::STS::Model::AssumeRoleOutcome outcome = sts.AssumeRole(sts_req);

	if (!outcome.IsSuccess()) {
		std::cerr << "Error assuming IAM role. " <<
			outcome.GetError().GetMessage() << std::endl;
	}
	else {
		std::cout << "Credentials successfully retrieved." << std::endl;
		const Aws::STS::Model::AssumeRoleResult result = outcome.GetResult();
		const Aws::STS::Model::Credentials &temp_credentials = result.GetCredentials();

		// Store temporary credentials in return argument.
		// Note: The credentials object returned by assumeRole differs
		// from the AWSCredentials object used in most situations.
		credentials.SetAWSAccessKeyId(temp_credentials.GetAccessKeyId());
		credentials.SetAWSSecretKey(temp_credentials.GetSecretAccessKey());
		credentials.SetSessionToken(temp_credentials.GetSessionToken());
	}

	return outcome.IsSuccess();
}

API 상세는 AssumeRole in AWS SDK for C++ API Reference를 참고해요.

CLI (AWS CLI)

IAM 역할 s3-access-example에 대한 단기 자격 증명을 가져오려면 다음 assume-role 명령을 실행해요.

aws sts assume-role \
	--role-arn arn:aws:iam::123456789012:role/xaccounts3access \
	--role-session-name s3-access-example

출력:

{
	"AssumedRoleUser": {
		"AssumedRoleId": "AROA3XFRBF535PLBIFPI4:s3-access-example",
		"Arn": "arn:aws:sts::123456789012:assumed-role/xaccounts3access/s3-access-example"
	},
	"Credentials": {
		"SecretAccessKey": "9drTJvcXLB89EXAMPLELB8923FB892xMFI",
		"SessionToken": "AQoXdzELDDY//////////wEaoAK1wvxJY12r2IrDFT2IvAzTCn3zHoZ7YNtpiQLF0MqZye/qwjzP2iEXAMPLEbw/m3hsj8VBTkPORGvr9jM5sgP+w9IZWZnU+LWhmg+a5fDi2oTGUYcdg9uexQ4mtCHIHfi4citgqZTgco40Yqr4lIlo4V2b2Dyauk0eYFNebHtYlFVgAUj+7Indz3LU0aTWk1WKIjHmmMCIoTkyYp/k7kUG7moeEYKSitwQIi6Gjn+nyzM+PtoA3685ixzv0R7i5rjQi0YE0lf1oeie3bDiNHncmzosRM6SFiPzSvp6h/32xQuZsjcypmwsPSDtTPYcs0+YN/8BRi2/IcrxSpnWEXAMPLEXSDFTAQAM6Dl9zR0tXoybnlrZIwMLlMi1Kcgo5OytwU=",
		"Expiration": "2016-03-15T00:05:07Z",
		"AccessKeyId": "ASIAJEXAMPLEXEG2JICEA"
	}
}

출력에는 AWS에 인증할 때 쓸 수 있는 액세스 키, 시크릿 키, 세션 토큰이 담겨 있어요. AWS CLI를 쓴다면 역할과 연결된 명명된 프로필을 설정하고, 그 프로필을 사용하면 AWS CLI가 assume-role을 호출해 자격 증명을 관리해줘요. 자세한 내용은 AWS CLI User Guide의 Use an IAM role in the AWS CLI를 참고해요.

API 상세는 AssumeRole in AWS CLI Command Reference를 참고해요.

Java (SDK for Java 2.x)

Note GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예제와 설정·실행 방법을 확인할 수 있어요.

이 예제를 실행하려면 맡으려는 역할을 만들고 AWS 콘솔에서 신뢰 관계(Trust Relationship)를 정의해야 해요.

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
import software.amazon.awssdk.services.sts.model.StsException;
import software.amazon.awssdk.services.sts.model.AssumeRoleResponse;
import software.amazon.awssdk.services.sts.model.Credentials;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;

/**
 * To make this code example work, create a Role that you want to assume.
 * Then define a Trust Relationship in the AWS Console. You can use this as an
 * example:
 *
 * {
 *   "Version":"2012-10-17",
 *   "Statement": [
 *     {
 *       "Effect": "Allow",
 *       "Principal": {
 *         "AWS": "<Specify the ARN of your IAM user you are using in this code example>"
 *       },
 *       "Action": "sts:AssumeRole"
 *     }
 *   ]
 * }
 *
 * For more information, see "Editing the Trust Relationship for an Existing
 * Role" in the AWS Directory Service guide.
 *
 * Also, set up your development environment, including your credentials.
 *
 * For information, see this documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class AssumeRole {
	public static void main(String[] args) {
		final String usage = """

			Usage:
			<roleArn> <roleSessionName>\s

			Where:
			roleArn - The Amazon Resource Name (ARN) of the role to assume (for example, arn:aws:iam::000008047983:role/s3role).\s
			roleSessionName - An identifier for the assumed role session (for example, mysession).\s
			""";

		if (args.length != 2) {
			System.out.println(usage);
			System.exit(1);
		}

		String roleArn = args[0];
		String roleSessionName = args[1];
		Region region = Region.US_EAST_1;
		StsClient stsClient = StsClient.builder()
			.region(region)
			.build();

		assumeGivenRole(stsClient, roleArn, roleSessionName);
		stsClient.close();
	}

	public static void assumeGivenRole(StsClient stsClient, String roleArn, String roleSessionName) {
		try {
			AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
				.roleArn(roleArn)
				.roleSessionName(roleSessionName)
				.build();

			AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
			Credentials myCreds = roleResponse.credentials();

			// Display the time when the temp creds expire.
			Instant exTime = myCreds.expiration();
			String tokenInfo = myCreds.sessionToken();

			// Convert the Instant to readable date.
			DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
				.withLocale(Locale.US)
				.withZone(ZoneId.systemDefault());

			formatter.format(exTime);
			System.out.println("The token " + tokenInfo + " expires on " + exTime);

		} catch (StsException e) {
			System.err.println(e.getMessage());
			System.exit(1);
		}
	}
}

API 상세는 AssumeRole in AWS SDK for Java 2.x API Reference를 참고해요.

JavaScript (SDK for JavaScript v3)

Note GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예제와 설정·실행 방법을 확인할 수 있어요.

클라이언트를 만들어요.

import { STSClient } from "@aws-sdk/client-sts";
// Set the AWS Region.
const REGION = "us-east-1";
// Create an AWS STS service client object.
export const client = new STSClient({ region: REGION });

IAM 역할을 맡아요.

import { AssumeRoleCommand } from "@aws-sdk/client-sts";

import { client } from "../libs/client.js";

export const main = async () => {
	try {
	// Returns a set of temporary security credentials that you can use to
	// access Amazon Web Services resources that you might not normally
	// have access to.
	const command = new AssumeRoleCommand({
		// The Amazon Resource Name (ARN) of the role to assume.
		RoleArn: "ROLE_ARN",
		// An identifier for the assumed role session.
		RoleSessionName: "session1",
		// The duration, in seconds, of the role session. The value specified
		// can range from 900 seconds (15 minutes) up to the maximum session
		// duration set for the role.
		DurationSeconds: 900,
	});
	const response = await client.send(command);
	console.log(response);
	} catch (err) {
	console.error(err);
	}
};

API 상세는 AssumeRole in AWS SDK for JavaScript API Reference를 참고해요.

JavaScript (SDK for JavaScript v2)

Note GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예제와 설정·실행 방법을 확인할 수 있어요.

// Load the AWS SDK for Node.js
const AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

var roleToAssume = {
	RoleArn: "arn:aws:iam::123456789012:role/RoleName",
	RoleSessionName: "session1",
	DurationSeconds: 900,
};
var roleCreds;

// Create the STS service object
var sts = new AWS.STS({ apiVersion: "2011-06-15" });

//Assume Role
sts.assumeRole(roleToAssume, function (err, data) {
	if (err) console.log(err, err.stack);
	else {
	roleCreds = {
		accessKeyId: data.Credentials.AccessKeyId,
		secretAccessKey: data.Credentials.SecretAccessKey,
		sessionToken: data.Credentials.SessionToken,
	};
	stsGetCallerIdentity(roleCreds);
	}
});

//Get Arn of current identity
function stsGetCallerIdentity(creds) {
	var stsParams = { credentials: creds };
	// Create STS service object
	var sts = new AWS.STS(stsParams);

	sts.getCallerIdentity({}, function (err, data) {
	if (err) {
		console.log(err, err.stack);
	} else {
		console.log(data.Arn);
	}
	});
}

API 상세는 AssumeRole in AWS SDK for JavaScript API Reference를 참고해요.

PowerShell (Tools for PowerShell V4)

Example 1: 요청 사용자가 평소에는 접근할 수 없는 AWS 리소스에 접근하는 데 1시간 동안 쓸 수 있는 임시 자격 증명(액세스 키·시크릿 키·세션 토큰)을 반환해요. 반환된 자격 증명은 맡은 역할의 액세스 정책과 제공된 정책이 허용하는 권한을 가져요(제공된 정책으로 역할의 액세스 정책이 정의한 권한을 초과해 부여할 수는 없어요).

Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -Policy "...JSON policy..." -DurationInSeconds 3600

Example 2: 맡은 역할의 액세스 정책에 정의된 권한과 동일한 권한을 가진, 1시간 동안 유효한 임시 자격 증명을 반환해요.

Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600

Example 3: cmdlet을 실행하는 데 사용된 사용자 자격 증명과 연결된 MFA의 일련 번호·생성 토큰을 제공해 임시 자격 증명을 반환해요.

Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -SerialNumber "GAHT12345678" -TokenCode "123456"

Example 4: 고객 계정에 정의된 역할을 맡은 임시 자격 증명을 반환해요. 제3자가 맡을 수 있는 각 역할에 대해 고객 계정은 역할을 만들고, 역할을 맡을 때마다 -ExternalId 매개변수로 전달해야 하는 식별자를 사용해야 해요.

Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -ExternalId "ABC123"

API 상세는 AssumeRole in AWS Tools for PowerShell Cmdlet Reference (V4)를 참고해요.

PowerShell (Tools for PowerShell V5)

Example 1: 요청 사용자가 평소에는 접근할 수 없는 AWS 리소스에 접근하는 데 1시간 동안 쓸 수 있는 임시 자격 증명(액세스 키·시크릿 키·세션 토큰)을 반환해요.

Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -Policy "...JSON policy..." -DurationInSeconds 3600

Example 2: 맡은 역할의 액세스 정책에 정의된 권한과 동일한 권한을 가진, 1시간 동안 유효한 임시 자격 증명을 반환해요.

Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600

Example 3: MFA와 연결된 일련 번호·생성 토큰을 제공해 임시 자격 증명을 반환해요.

Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -SerialNumber "GAHT12345678" -TokenCode "123456"

Example 4: 고객 계정에 정의된 역할을 맡은 임시 자격 증명을 반환해요. -ExternalId 매개변수를 사용해요.

Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -ExternalId "ABC123"

API 상세는 AssumeRole in AWS Tools for PowerShell Cmdlet Reference (V5)를 참고해요.

Python (SDK for Python / Boto3)

Note GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예제와 설정·실행 방법을 확인할 수 있어요.

MFA 토큰이 필요한 IAM 역할을 맡고, 임시 자격 증명을 사용해 계정의 Amazon S3 버킷을 나열해요.

def list_buckets_from_assumed_role_with_mfa(
	assume_role_arn, session_name, mfa_serial_number, mfa_totp, sts_client
):
	"""
	Assumes a role from another account and uses the temporary credentials from
	that role to list the Amazon S3 buckets that are owned by the other account.
	Requires an MFA device serial number and token.

	The assumed role must grant permission to list the buckets in the other account.

	:param assume_role_arn: The Amazon Resource Name (ARN) of the role that
	grants access to list the other account's buckets.
	:param session_name: The name of the STS session.
	:param mfa_serial_number: The serial number of the MFA device. For a virtual MFA
	device, this is an ARN.
	:param mfa_totp: A time-based, one-time password issued by the MFA device.
	:param sts_client: A Boto3 STS instance that has permission to assume the role.
	"""
	response = sts_client.assume_role(
		RoleArn=assume_role_arn,
		RoleSessionName=session_name,
		SerialNumber=mfa_serial_number,
		TokenCode=mfa_totp,
	)
	temp_credentials = response["Credentials"]
	print(f"Assumed role {assume_role_arn} and got temporary credentials.")

	s3_resource = boto3.resource(
		"s3",
		aws_access_key_id=temp_credentials["AccessKeyId"],
		aws_secret_access_key=temp_credentials["SecretAccessKey"],
		aws_session_token=temp_credentials["SessionToken"],
	)

	print(f"Listing buckets for the assumed role's account:")
	for bucket in s3_resource.buckets.all():
		print(bucket.name)

API 상세는 AssumeRole in AWS SDK for Python (Boto3) API Reference를 참고해요.

Ruby (SDK for Ruby)

Note GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예제와 설정·실행 방법을 확인할 수 있어요.

 # Creates an AWS Security Token Service (AWS STS) client with specified credentials.
 # This is separated into a factory function so that it can be mocked for unit testing.
 #
 # @param key_id [String] The ID of the access key used by the STS client.
 # @param key_secret [String] The secret part of the access key used by the STS client.
 def create_sts_client(key_id, key_secret)
	Aws::STS::Client.new(access_key_id: key_id, secret_access_key: key_secret)
 end

 # Gets temporary credentials that can be used to assume a role.
 #
 # @param role_arn [String] The ARN of the role that is assumed when these credentials
 # are used.
 # @param sts_client [AWS::STS::Client] An AWS STS client.
 # @return [Aws::AssumeRoleCredentials] The credentials that can be used to assume the role.
 def assume_role(role_arn, sts_client)
	credentials = Aws::AssumeRoleCredentials.new(
	client: sts_client,
	role_arn: role_arn,
	role_session_name: 'create-use-assume-role-scenario'
	)
	@logger.info("Assumed role '#{role_arn}', got temporary credentials.")
	credentials
 end

API 상세는 AssumeRole in AWS SDK for Ruby API Reference를 참고해요.

Rust (SDK for Rust)

Note GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예제와 설정·실행 방법을 확인할 수 있어요.

async fn assume_role(config: &SdkConfig, role_name: String, session_name: Option<String>) {
	let provider = aws_config::sts::AssumeRoleProvider::builder(role_name)
	.session_name(session_name.unwrap_or("rust_sdk_example_session".into()))
	.configure(config)
	.build()
	.await;

	let local_config = aws_config::from_env()
	.credentials_provider(provider)
	.load()
	.await;
	let client = Client::new(&local_config);
	let req = client.get_caller_identity();
	let resp = req.send().await;
	match resp {
	Ok(e) => {
		println!("UserID : {}", e.user_id().unwrap_or_default());
		println!("Account: {}", e.account().unwrap_or_default());
		println!("Arn    : {}", e.arn().unwrap_or_default());
	}
	Err(e) => println!("{:?}", e),
	}
}

API 상세는 AssumeRole in AWS SDK for Rust API reference를 참고해요.

Swift (SDK for Swift)

Note GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예제와 설정·실행 방법을 확인할 수 있어요.

import AWSSTS

 public func assumeRole(role: IAMClientTypes.Role, sessionName: String)
 async throws -> STSClientTypes.Credentials
 {
	let input = AssumeRoleInput(
	roleArn: role.arn,
	roleSessionName: sessionName
	)
	do {
	let output = try await stsClient.assumeRole(input: input)

	guard let credentials = output.credentials else {
		throw ServiceHandlerError.authError
	}

	return credentials
	} catch {
	print("Error assuming role: ", dump(error))
	throw error
	}
 }

API 상세는 AssumeRole in AWS SDK for Swift API reference를 참고해요.

더 알아보기 (Learn more)