AWS SDK 또는 CLI와 함께 CreateRole 사용 - AWS Identity and Access Management

AWS SDK 또는 CLI와 함께 CreateRole 사용

다음 코드 예제는 CreateRole의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.

.NET
AWS SDK for .NET
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

/// <summary> /// Create a new IAM role. /// </summary> /// <param name="roleName">The name of the IAM role.</param> /// <param name="rolePolicyDocument">The name of the IAM policy document /// for the new role.</param> /// <returns>The Amazon Resource Name (ARN) of the role.</returns> public async Task<string> CreateRoleAsync(string roleName, string rolePolicyDocument) { var request = new CreateRoleRequest { RoleName = roleName, AssumeRolePolicyDocument = rolePolicyDocument, }; var response = await _IAMService.CreateRoleAsync(request); return response.Role.Arn; }
Bash
Bash 스크립트와 함께 AWS CLI사용
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function iam_create_role # # This function creates an IAM role. # # Parameters: # -n role_name -- The name of the IAM role. # -p policy_json -- The assume role policy document. # # Returns: # The ARN of the role. # And: # 0 - If successful. # 1 - If it fails. ############################################################################### function iam_create_role() { local role_name policy_document response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function iam_create_user_access_key" echo "Creates an AWS Identity and Access Management (IAM) role." echo " -n role_name The name of the IAM role." echo " -p policy_json -- The assume role policy document." echo "" } # Retrieve the calling parameters. while getopts "n:p:h" option; do case "${option}" in n) role_name="${OPTARG}" ;; p) policy_document="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$role_name" ]]; then errecho "ERROR: You must provide a role name with the -n parameter." usage return 1 fi if [[ -z "$policy_document" ]]; then errecho "ERROR: You must provide a policy document with the -p parameter." usage return 1 fi response=$(aws iam create-role \ --role-name "$role_name" \ --assume-role-policy-document "$policy_document" \ --output text \ --query Role.Arn) 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 세부 정보는 AWS CLI 명령 참조의 CreateRole을 참조하십시오.

C++
SDK for C++
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

bool AwsDoc::IAM::createIamRole( const Aws::String &roleName, const Aws::String &policy, const Aws::Client::ClientConfiguration &clientConfig) { Aws::IAM::IAMClient client(clientConfig); Aws::IAM::Model::CreateRoleRequest request; request.SetRoleName(roleName); request.SetAssumeRolePolicyDocument(policy); Aws::IAM::Model::CreateRoleOutcome outcome = client.CreateRole(request); if (!outcome.IsSuccess()) { std::cerr << "Error creating role. " << outcome.GetError().GetMessage() << std::endl; } else { const Aws::IAM::Model::Role iamRole = outcome.GetResult().GetRole(); std::cout << "Created role " << iamRole.GetRoleName() << "\n"; std::cout << "ID: " << iamRole.GetRoleId() << "\n"; std::cout << "ARN: " << iamRole.GetArn() << std::endl; } return outcome.IsSuccess(); }
CLI
AWS CLI

예제 1: IAM 역할 생성

다음 create-role 명령은 이름이 Test-Role인 역할을 생성하고 해당 역할에 신뢰 정책을 연결합니다.

aws iam create-role \ --role-name Test-Role \ --assume-role-policy-document file://Test-Role-Trust-Policy.json

출력:

{ "Role": { "AssumeRolePolicyDocument": "<URL-encoded-JSON>", "RoleId": "AKIAIOSFODNN7EXAMPLE", "CreateDate": "2013-06-07T20:43:32.821Z", "RoleName": "Test-Role", "Path": "/", "Arn": "arn:aws:iam::123456789012:role/Test-Role" } }

신뢰 정책은 Test-Role-Trust-Policy.json 파일에 JSON 문서로 정의됩니다. (파일 이름과 확장자는 중요하지 않습니다.) 신뢰 정책에서 보안 주체를 지정해야 합니다.

역할에 권한 정책을 연결하려면 put-role-policy 명령을 사용합니다.

자세한 내용은 AWS IAM 사용 설명서의 IAM 역할 생성을 참조하세요.

예제 2: 지정된 최대 세션 시간을 포함한 IAM 역할 생성

다음 create-role 명령은 이름이 Test-Role인 역할을 생성하고 최대 세션 지속 시간을 7,200초(2시간)로 설정합니다.

aws iam create-role \ --role-name Test-Role \ --assume-role-policy-document file://Test-Role-Trust-Policy.json \ --max-session-duration 7200

출력:

{ "Role": { "Path": "/", "RoleName": "Test-Role", "RoleId": "AKIAIOSFODNN7EXAMPLE", "Arn": "arn:aws:iam::12345678012:role/Test-Role", "CreateDate": "2023-05-24T23:50:25+00:00", "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Sid": "Statement1", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::12345678012:root" }, "Action": "sts:AssumeRole" } ] } } }

자세한 내용은 AWS IAM 사용 설명서의 역할 최대 세션 기간 수정(AWS API)을 참조하세요.

예제 3: 태그가 포함된 IAM 역할 생성

다음 명령은 태그가 포함된 IAM 역할 Test-Role을 생성합니다. 이 예제에서는 다음 JSON 형식의 태그('{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}')에 --tags 파라미터 플래그를 사용합니다. 또는 --tags 플래그를 짧은 형식의 태그('Key=Department,Value=Accounting Key=Location,Value=Seattle')에 사용할 수도 있습니다.

aws iam create-role \ --role-name Test-Role \ --assume-role-policy-document file://Test-Role-Trust-Policy.json \ --tags '{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'

출력:

{ "Role": { "Path": "/", "RoleName": "Test-Role", "RoleId": "AKIAIOSFODNN7EXAMPLE", "Arn": "arn:aws:iam::123456789012:role/Test-Role", "CreateDate": "2023-05-25T23:29:41+00:00", "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Sid": "Statement1", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::123456789012:root" }, "Action": "sts:AssumeRole" } ] }, "Tags": [ { "Key": "Department", "Value": "Accounting" }, { "Key": "Location", "Value": "Seattle" } ] } }

자세한 내용은 AWS IAM 사용 설명서의 IAM 역할 태그 지정을 참조하세요.

  • API 세부 정보는 AWS CLI 명령 참조의 CreateRole을 참조하십시오.

Go
SDK for Go V2
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions // used in the examples. // It contains an IAM service client that is used to perform role actions. type RoleWrapper struct { IamClient *iam.Client } // CreateRole creates a role that trusts a specified user. The trusted user can assume // the role to acquire its permissions. // PolicyDocument shows how to work with a policy document as a data structure and // serialize it to JSON by using Go's JSON marshaler. func (wrapper RoleWrapper) CreateRole(roleName string, trustedUserArn string) (*types.Role, error) { var role *types.Role trustPolicy := PolicyDocument{ Version: "2012-10-17", Statement: []PolicyStatement{{ Effect: "Allow", Principal: map[string]string{"AWS": trustedUserArn}, Action: []string{"sts:AssumeRole"}, }}, } policyBytes, err := json.Marshal(trustPolicy) if err != nil { log.Printf("Couldn't create trust policy for %v. Here's why: %v\n", trustedUserArn, err) return nil, err } result, err := wrapper.IamClient.CreateRole(context.TODO(), &iam.CreateRoleInput{ AssumeRolePolicyDocument: aws.String(string(policyBytes)), RoleName: aws.String(roleName), }) if err != nil { log.Printf("Couldn't create role %v. Here's why: %v\n", roleName, err) } else { role = result.Role } return role, err }
Java
SDK for Java 2.x
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import software.amazon.awssdk.services.iam.model.CreateRoleRequest; import software.amazon.awssdk.services.iam.model.CreateRoleResponse; import software.amazon.awssdk.services.iam.model.IamException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iam.IamClient; import java.io.FileReader; /* * This example requires a trust policy document. For more information, see: * https://aws.amazon.com/blogs/security/how-to-use-trust-policies-with-iam-roles/ * * * In addition, 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 CreateRole { public static void main(String[] args) throws Exception { final String usage = """ Usage: <rolename> <fileLocation>\s Where: rolename - The name of the role to create.\s fileLocation - The location of the JSON document that represents the trust policy.\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String rolename = args[0]; String fileLocation = args[1]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() .region(region) .build(); String result = createIAMRole(iam, rolename, fileLocation); System.out.println("Successfully created user: " + result); iam.close(); } public static String createIAMRole(IamClient iam, String rolename, String fileLocation) throws Exception { try { JSONObject jsonObject = (JSONObject) readJsonSimpleDemo(fileLocation); CreateRoleRequest request = CreateRoleRequest.builder() .roleName(rolename) .assumeRolePolicyDocument(jsonObject.toJSONString()) .description("Created using the AWS SDK for Java") .build(); CreateRoleResponse response = iam.createRole(request); System.out.println("The ARN of the role is " + response.role().arn()); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static Object readJsonSimpleDemo(String filename) throws Exception { FileReader reader = new FileReader(filename); JSONParser jsonParser = new JSONParser(); return jsonParser.parse(reader); } }
JavaScript
SDK for JavaScript (v3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

역할을 생성합니다.

import { CreateRoleCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} roleName */ export const createRole = (roleName) => { const command = new CreateRoleCommand({ AssumeRolePolicyDocument: JSON.stringify({ Version: "2012-10-17", Statement: [ { Effect: "Allow", Principal: { Service: "lambda.amazonaws.com", }, Action: "sts:AssumeRole", }, ], }), RoleName: roleName, }); return client.send(command); };
PHP
SDK for PHP
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

$uuid = uniqid(); $service = new IAMService(); $assumeRolePolicyDocument = "{ \"Version\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\", \"Principal\": {\"AWS\": \"{$user['Arn']}\"}, \"Action\": \"sts:AssumeRole\" }] }"; $assumeRoleRole = $service->createRole("iam_demo_role_$uuid", $assumeRolePolicyDocument); echo "Created role: {$assumeRoleRole['RoleName']}\n"; /** * @param string $roleName * @param string $rolePolicyDocument * @return array * @throws AwsException */ public function createRole(string $roleName, string $rolePolicyDocument) { $result = $this->customWaiter(function () use ($roleName, $rolePolicyDocument) { return $this->iamClient->createRole([ 'AssumeRolePolicyDocument' => $rolePolicyDocument, 'RoleName' => $roleName, ]); }); return $result['Role']; }
PowerShell
PowerShell용 도구

예제 1: 이 예제는 MyNewRole이라는 새 역할을 생성하고 여기에 NewRoleTrustPolicy.json 파일에 있는 정책을 연결합니다. JSON 정책 파일을 성공적으로 처리하려면 -Raw 스위치 파라미터를 사용해야 합니다. 출력에 표시된 정책 문서는 URL로 인코딩됩니다. 이 예제에서는 UrlDecode .NET 메서드를 사용하여 디코딩됩니다.

$results = New-IAMRole -AssumeRolePolicyDocument (Get-Content -raw NewRoleTrustPolicy.json) -RoleName MyNewRole $results

출력:

Arn : arn:aws:iam::123456789012:role/MyNewRole AssumeRolePolicyDocument : %7B%0D%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%0D%0A%20%20%22Statement%22 %3A%20%5B%0D%0A%20%20%20%20%7B%0D%0A%20%20%20%20%20%20%22Sid%22%3A%20%22%22%2C %0D%0A%20%20%20%20%20%20%22Effect%22%3A%20%22Allow%22%2C%0D%0A%20%20%20%20%20%20 %22Principal%22%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20%22AWS%22%3A%20%22arn%3Aaws %3Aiam%3A%3A123456789012%3ADavid%22%0D%0A%20%20%20%20%20%20%7D%2C%0D%0A%20%20%20 %20%20%20%22Action%22%3A%20%22sts%3AAssumeRole%22%0D%0A%20%20%20%20%7D%0D%0A%20 %20%5D%0D%0A%7D CreateDate : 4/15/2015 11:04:23 AM Path : / RoleId : V5PAJI2KPN4EAEXAMPLE1 RoleName : MyNewRole [System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility") [System.Web.HttpUtility]::UrlDecode($results.AssumeRolePolicyDocument) { "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::123456789012:David" }, "Action": "sts:AssumeRole" } ] }
  • API 세부 정보는 AWS Tools for PowerShell Cmdlet 참조의 CreateRole을 참조하세요.

Python
SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

def create_role(role_name, allowed_services): """ Creates a role that lets a list of specified services assume the role. :param role_name: The name of the role. :param allowed_services: The services that can assume the role. :return: The newly created role. """ trust_policy = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": {"Service": service}, "Action": "sts:AssumeRole", } for service in allowed_services ], } try: role = iam.create_role( RoleName=role_name, AssumeRolePolicyDocument=json.dumps(trust_policy) ) logger.info("Created role %s.", role.name) except ClientError: logger.exception("Couldn't create role %s.", role_name) raise else: return role
  • API 세부 정보는 AWSSDK for Python (Boto3) API 참조CreateRole를 참조하십시오.

Ruby
SDK for Ruby
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

# Creates a role and attaches policies to it. # # @param role_name [String] The name of the role. # @param assume_role_policy_document [Hash] The trust relationship policy document. # @param policy_arns [Array<String>] The ARNs of the policies to attach. # @return [String, nil] The ARN of the new role if successful, or nil if an error occurred. def create_role(role_name, assume_role_policy_document, policy_arns) response = @iam_client.create_role( role_name: role_name, assume_role_policy_document: assume_role_policy_document.to_json ) role_arn = response.role.arn policy_arns.each do |policy_arn| @iam_client.attach_role_policy( role_name: role_name, policy_arn: policy_arn ) end role_arn rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating role: #{e.message}") nil end
Rust
SDK for Rust
참고

GitHub에 더 많은 내용이 있습니다. AWS코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

pub async fn create_role( client: &iamClient, role_name: &str, role_policy_document: &str, ) -> Result<Role, iamError> { let response: CreateRoleOutput = loop { if let Ok(response) = client .create_role() .role_name(role_name) .assume_role_policy_document(role_policy_document) .send() .await { break response; } }; Ok(response.role.unwrap()) }
  • API 세부 정보는 AWS SDK for Rust API 참조CreateRole을 참조하십시오.

Swift
SDK for Swift
참고

이 사전 릴리스 설명서는 평가판 버전 SDK에 관한 것입니다. 내용은 변경될 수 있습니다.

참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

public func createRole(name: String, policyDocument: String) async throws -> String { let input = CreateRoleInput( assumeRolePolicyDocument: policyDocument, roleName: name ) do { let output = try await client.createRole(input: input) guard let role = output.role else { throw ServiceHandlerError.noSuchRole } guard let id = role.roleId else { throw ServiceHandlerError.noSuchRole } return id } catch { throw error } }
  • API 세부 정보는 Swift용 AWS SDK API 참조CreateRole을 참조하세요.

AWS SDK 개발자 가이드 및 코드 예시의 전체 목록은 AWS SDK와 함께 IAM 사용 단원을 참조하세요. 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.