将 CreateRole 与 Amazon SDK 或命令行工具配合使用 - Amazon Identity and Access Management
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

CreateRole 与 Amazon SDK 或命令行工具配合使用

以下代码示例演示如何使用 CreateRole

操作示例是大型程序的代码摘录,必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

在 GitHub 上查看更多内容。查找完整示例,了解如何在 Amazon 代码示例存储库中进行设置和运行。

/// <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; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NET API 参考中的 CreateRole

Bash
Amazon CLI 及 Bash 脚本
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

############################################################################### # 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 详细信息,请参阅《Amazon CLI Command Reference》中的 CreateRole

C++
适用于 C++ 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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(); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for C++ API 参考中的 CreateRole

CLI
Amazon 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 命令。

有关更多信息,请参阅《Amazon IAM 用户指南》中的创建 IAM 角色

示例 2:创建具有指定最长会话持续时间的 IAM 角色

以下 create-role 命令将创建一个名为 Test-Role 的角色,并将最长会话持续时间设置为 7200 秒(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" } ] } } }

有关更多信息,请参阅《Amazon IAM 用户指南》中的修改角色最长会话持续时间(Amazon API)

示例 3:创建带有标签的 IAM 角色

以下命令将创建带有标签的 IAM 角色 Test-Role。此示例使用带有以下 JSON 格式标签的 --tags 参数标志:'{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'。或者,--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" } ] } }

有关更多信息,请参阅《Amazon IAM 用户指南》中的标记 IAM 角色

  • 有关 API 详细信息,请参阅《Amazon CLI Command Reference》中的 CreateRole

Go
适用于 Go V2 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

// 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 }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Go API 参考中的 CreateRole

Java
SDK for Java 2.x
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考中的 CreateRole

JavaScript
SDK for JavaScript (v3)
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

创建角色。

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); };
  • 有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 CreateRole

PHP
适用于 PHP 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

$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']; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for PHP API 参考中的 CreateRole

PowerShell
适用于 PowerShell 的工具

示例 1:此示例创建一个名为 MyNewRole 的新角色,并将文件 NewRoleTrustPolicy.json 中的策略附加到该角色。请注意,必须使用 -Raw 开关参数才能成功处理 JSON 策略文件。输出中显示的策略文档采用 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 详细信息,请参阅《Amazon Tools for PowerShell Cmdlet 参考》中的 CreateRole

Python
SDK for Python(Boto3)
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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 详细信息,请参阅 Amazon SDK for Python(Boto3)API 参考中的 CreateRole

Ruby
适用于 Ruby 的 SDK
注意

查看 GitHub,了解更多信息。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# 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
  • 有关 API 详细信息,请参阅 Amazon SDK for Ruby API 参考中的 CreateRole

Rust
适用于 Rust 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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 详细信息,请参阅 Amazon SDK for Rust API 参考中的 CreateRole

Swift
SDK for Swift
注意

这是预览版 SDK 的预发布文档。本文档随时可能更改。

注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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 详细信息,请参阅 Amazon SDK for Swift API 参考中的 CreateRole

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将 IAM 与 Amazon 开发工具包配合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。