使用 Amazon 开发工具包创建 IAM 角色 - Amazon Identity and Access Management
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

使用 Amazon 开发工具包创建 IAM 角色

以下代码示例显示如何创建 IAM 角色。

.NET
Amazon SDK for .NET
注意

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

/// <summary> /// Create a new IAM role which we can attach to a user. /// </summary> /// <param name="client">The initialized IAM client object.</param> /// <param name="roleName">The name of the IAM role to create.</param> /// <param name="rolePermissions">The permissions which the role will have.</param> /// <returns>A Role object representing the newly created role.</returns> public static async Task<Role> CreateRoleAsync( AmazonIdentityManagementServiceClient client, string roleName, string rolePermissions) { var request = new CreateRoleRequest { RoleName = roleName, AssumeRolePolicyDocument = rolePermissions, }; var response = await client.CreateRoleAsync(request); return response.Role; }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 CreateRole

C++
SDK for C++
注意

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

Go
SDK for Go V2
注意

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

// CreateRole myRole, err := service.CreateRole(context.Background(), &iam.CreateRoleInput{ RoleName: aws.String(ExampleRoleName), Description: aws.String("My super awesome example role"), AssumeRolePolicyDocument: aws.String(`{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }`), }) if err != nil { panic("Couldn't create role: " + err.Error()) } fmt.Println("☑️ Create Role") fmt.Printf("The new role's ARN is %s \n", *myRole.Role.Arn)
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 CreateRole

Java
SDK for Java 2.x
注意

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

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 { IAMClient } from "@aws-sdk/client-iam"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". // Create an IAM service client object. const iamClient = new IAMClient({ region: REGION }); export { iamClient };

创建角色。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { CreateRoleCommand } from "@aws-sdk/client-iam"; // Sample assume role policy JSON. const role_json = { Version: "2012-10-17", Statement: [ { Effect: "Allow", Principal: { AWS: "USER_ARN", // The ARN of the user. }, Action: "sts:AssumeRole", }, ], }; // Stringify the assume role policy JSON. const myJson = JSON.stringify(role_json); // Set the parameters. const params = { AssumeRolePolicyDocument: myJson, Path: "/", RoleName: "ROLE_NAME" }; const run = async () => { try { const data = await iamClient.send(new CreateRoleCommand(params)); console.log("Success. Role created. Role Arn: ", data.Role.RoleName); } catch (err) { console.log("Error", err); } }; run();
  • 有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 CreateRole

PHP
SDK for PHP
注意

在 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

Python
适用于 Python (Boto3) 的 SDK
注意

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
SDK for Ruby
注意

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

# Creates a role that can be assumed by a user. # # @param role_name [String] The name to give the role. # @param user [Aws::IAM::User] The user who is granted permission to assume the role. # @return [Aws::IAM::Role] The newly created role. def create_role(role_name, user) role = @iam_resource.create_role( role_name: role_name, assume_role_policy_document: { Version: "2012-10-17", Statement: [{ Effect: "Allow", Principal: {'AWS': user.arn}, Action: "sts:AssumeRole" }] }.to_json) puts("Created role #{role.name}.") rescue Aws::Errors::ServiceError => e puts("Couldn't create a role for the demo. Here's why: ") puts("\t#{e.code}: #{e.message}") raise else role end
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 CreateRole

Rust
SDK for Rust
注意

本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。

注意

在 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

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