IAM用SDK于 Kotlin 的示例 - AWS SDK代码示例

AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

IAM用SDK于 Kotlin 的示例

以下代码示例向您展示了如何使用 for Kotlin 来执行操作和实现常见场景。 AWS SDK IAM

基础知识是向您展示如何在服务中执行基本操作的代码示例。

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景的上下文查看操作。

每个示例都包含一个指向完整源代码的链接,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

基础知识

以下代码示例展示了如何创建用户并代入角色。

警告

为避免安全风险,在开发专用软件或处理真实数据时,请勿使用IAM用户进行身份验证。而是使用与身份提供商的联合身份验证,例如 AWS IAM Identity Center

  • 创建没有权限的用户。

  • 创建授予列出账户的 Amazon S3 存储桶的权限的角色

  • 添加策略以允许用户代入该角色。

  • 代入角色并使用临时凭证列出 S3 存储桶,然后清除资源。

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

创建封装IAM用户操作的函数。

suspend fun main(args: Array<String>) { val usage = """ Usage: <username> <policyName> <roleName> <roleSessionName> <fileLocation> <bucketName> Where: username - The name of the IAM user to create. policyName - The name of the policy to create. roleName - The name of the role to create. roleSessionName - The name of the session required for the assumeRole operation. fileLocation - The file location to the JSON required to create the role (see Readme). bucketName - The name of the Amazon S3 bucket from which objects are read. """ if (args.size != 6) { println(usage) exitProcess(1) } val userName = args[0] val policyName = args[1] val roleName = args[2] val roleSessionName = args[3] val fileLocation = args[4] val bucketName = args[5] createUser(userName) println("$userName was successfully created.") val polArn = createPolicy(policyName) println("The policy $polArn was successfully created.") val roleArn = createRole(roleName, fileLocation) println("$roleArn was successfully created.") attachRolePolicy(roleName, polArn) println("*** Wait for 1 MIN so the resource is available.") delay(60000) assumeGivenRole(roleArn, roleSessionName, bucketName) println("*** Getting ready to delete the AWS resources.") deleteRole(roleName, polArn) deleteUser(userName) println("This IAM Scenario has successfully completed.") } suspend fun createUser(usernameVal: String?): String? { val request = CreateUserRequest { userName = usernameVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.createUser(request) return response.user?.userName } } suspend fun createPolicy(policyNameVal: String?): String { val policyDocumentValue: String = "{" + " \"Version\": \"2012-10-17\"," + " \"Statement\": [" + " {" + " \"Effect\": \"Allow\"," + " \"Action\": [" + " \"s3:*\"" + " ]," + " \"Resource\": \"*\"" + " }" + " ]" + "}" val request = CreatePolicyRequest { policyName = policyNameVal policyDocument = policyDocumentValue } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.createPolicy(request) return response.policy?.arn.toString() } } suspend fun createRole( rolenameVal: String?, fileLocation: String?, ): String? { val jsonObject = fileLocation?.let { readJsonSimpleDemo(it) } as JSONObject val request = CreateRoleRequest { roleName = rolenameVal assumeRolePolicyDocument = jsonObject.toJSONString() description = "Created using the AWS SDK for Kotlin" } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.createRole(request) return response.role?.arn } } suspend fun attachRolePolicy( roleNameVal: String, policyArnVal: String, ) { val request = ListAttachedRolePoliciesRequest { roleName = roleNameVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.listAttachedRolePolicies(request) val attachedPolicies = response.attachedPolicies // Ensure that the policy is not attached to this role. val checkStatus: Int if (attachedPolicies != null) { checkStatus = checkMyList(attachedPolicies, policyArnVal) if (checkStatus == -1) { return } } val policyRequest = AttachRolePolicyRequest { roleName = roleNameVal policyArn = policyArnVal } iamClient.attachRolePolicy(policyRequest) println("Successfully attached policy $policyArnVal to role $roleNameVal") } } fun checkMyList( attachedPolicies: List<AttachedPolicy>, policyArnVal: String, ): Int { for (policy in attachedPolicies) { val polArn = policy.policyArn.toString() if (polArn.compareTo(policyArnVal) == 0) { println("The policy is already attached to this role.") return -1 } } return 0 } suspend fun assumeGivenRole( roleArnVal: String?, roleSessionNameVal: String?, bucketName: String, ) { val stsClient = StsClient { region = "us-east-1" } val roleRequest = AssumeRoleRequest { roleArn = roleArnVal roleSessionName = roleSessionNameVal } val roleResponse = stsClient.assumeRole(roleRequest) val myCreds = roleResponse.credentials val key = myCreds?.accessKeyId val secKey = myCreds?.secretAccessKey val secToken = myCreds?.sessionToken val staticCredentials = StaticCredentialsProvider { accessKeyId = key secretAccessKey = secKey sessionToken = secToken } // List all objects in an Amazon S3 bucket using the temp creds. val s3 = S3Client { credentialsProvider = staticCredentials region = "us-east-1" } println("Created a S3Client using temp credentials.") println("Listing objects in $bucketName") val listObjects = ListObjectsRequest { bucket = bucketName } val response = s3.listObjects(listObjects) response.contents?.forEach { myObject -> println("The name of the key is ${myObject.key}") println("The owner is ${myObject.owner}") } } suspend fun deleteRole( roleNameVal: String, polArn: String, ) { val iam = IamClient { region = "AWS_GLOBAL" } // First the policy needs to be detached. val rolePolicyRequest = DetachRolePolicyRequest { policyArn = polArn roleName = roleNameVal } iam.detachRolePolicy(rolePolicyRequest) // Delete the policy. val request = DeletePolicyRequest { policyArn = polArn } iam.deletePolicy(request) println("*** Successfully deleted $polArn") // Delete the role. val roleRequest = DeleteRoleRequest { roleName = roleNameVal } iam.deleteRole(roleRequest) println("*** Successfully deleted $roleNameVal") } suspend fun deleteUser(userNameVal: String) { val iam = IamClient { region = "AWS_GLOBAL" } val request = DeleteUserRequest { userName = userNameVal } iam.deleteUser(request) println("*** Successfully deleted $userNameVal") } @Throws(java.lang.Exception::class) fun readJsonSimpleDemo(filename: String): Any? { val reader = FileReader(filename) val jsonParser = JSONParser() return jsonParser.parse(reader) }

操作

以下代码示例显示了如何使用AttachRolePolicy

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun attachIAMRolePolicy( roleNameVal: String, policyArnVal: String, ) { val request = ListAttachedRolePoliciesRequest { roleName = roleNameVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.listAttachedRolePolicies(request) val attachedPolicies = response.attachedPolicies // Ensure that the policy is not attached to this role. val checkStatus: Int if (attachedPolicies != null) { checkStatus = checkList(attachedPolicies, policyArnVal) if (checkStatus == -1) { return } } val policyRequest = AttachRolePolicyRequest { roleName = roleNameVal policyArn = policyArnVal } iamClient.attachRolePolicy(policyRequest) println("Successfully attached policy $policyArnVal to role $roleNameVal") } } fun checkList( attachedPolicies: List<AttachedPolicy>, policyArnVal: String, ): Int { for (policy in attachedPolicies) { val polArn = policy.policyArn.toString() if (polArn.compareTo(policyArnVal) == 0) { println("The policy is already attached to this role.") return -1 } } return 0 }
  • 有关API详细信息,请参阅AttachRolePolicy中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用CreateAccessKey

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun createIAMAccessKey(user: String?): String { val request = CreateAccessKeyRequest { userName = user } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.createAccessKey(request) return response.accessKey?.accessKeyId.toString() } }
  • 有关API详细信息,请参阅CreateAccessKey中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用CreateAccountAlias

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun createIAMAccountAlias(alias: String) { val request = CreateAccountAliasRequest { accountAlias = alias } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.createAccountAlias(request) println("Successfully created account alias named $alias") } }

以下代码示例显示了如何使用CreatePolicy

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun createIAMPolicy(policyNameVal: String?): String { val policyDocumentVal = "{" + " \"Version\": \"2012-10-17\"," + " \"Statement\": [" + " {" + " \"Effect\": \"Allow\"," + " \"Action\": [" + " \"dynamodb:DeleteItem\"," + " \"dynamodb:GetItem\"," + " \"dynamodb:PutItem\"," + " \"dynamodb:Scan\"," + " \"dynamodb:UpdateItem\"" + " ]," + " \"Resource\": \"*\"" + " }" + " ]" + "}" val request = CreatePolicyRequest { policyName = policyNameVal policyDocument = policyDocumentVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.createPolicy(request) return response.policy?.arn.toString() } }
  • 有关API详细信息,请参阅CreatePolicy中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用CreateUser

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun createIAMUser(usernameVal: String?): String? { val request = CreateUserRequest { userName = usernameVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.createUser(request) return response.user?.userName } }
  • 有关API详细信息,请参阅CreateUser中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用DeleteAccessKey

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun deleteKey( userNameVal: String, accessKey: String, ) { val request = DeleteAccessKeyRequest { accessKeyId = accessKey userName = userNameVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.deleteAccessKey(request) println("Successfully deleted access key $accessKey from $userNameVal") } }
  • 有关API详细信息,请参阅DeleteAccessKey中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用DeleteAccountAlias

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun deleteIAMAccountAlias(alias: String) { val request = DeleteAccountAliasRequest { accountAlias = alias } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.deleteAccountAlias(request) println("Successfully deleted account alias $alias") } }

以下代码示例显示了如何使用DeletePolicy

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun deleteIAMPolicy(policyARNVal: String?) { val request = DeletePolicyRequest { policyArn = policyARNVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.deletePolicy(request) println("Successfully deleted $policyARNVal") } }
  • 有关API详细信息,请参阅DeletePolicy中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用DeleteUser

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun deleteIAMUser(userNameVal: String) { val request = DeleteUserRequest { userName = userNameVal } // To delete a user, ensure that the user's access keys are deleted first. IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.deleteUser(request) println("Successfully deleted user $userNameVal") } }
  • 有关API详细信息,请参阅DeleteUser中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用DetachRolePolicy

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun detachPolicy( roleNameVal: String, policyArnVal: String, ) { val request = DetachRolePolicyRequest { roleName = roleNameVal policyArn = policyArnVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.detachRolePolicy(request) println("Successfully detached policy $policyArnVal from role $roleNameVal") } }
  • 有关API详细信息,请参阅DetachRolePolicy中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用GetPolicy

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun getIAMPolicy(policyArnVal: String?) { val request = GetPolicyRequest { policyArn = policyArnVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.getPolicy(request) println("Successfully retrieved policy ${response.policy?.policyName}") } }
  • 有关API详细信息,请参阅GetPolicy中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用ListAccessKeys

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun listKeys(userNameVal: String?) { val request = ListAccessKeysRequest { userName = userNameVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.listAccessKeys(request) response.accessKeyMetadata?.forEach { md -> println("Retrieved access key ${md.accessKeyId}") } } }
  • 有关API详细信息,请参阅ListAccessKeys中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用ListAccountAliases

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun listAliases() { IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.listAccountAliases(ListAccountAliasesRequest {}) response.accountAliases?.forEach { alias -> println("Retrieved account alias $alias") } } }

以下代码示例显示了如何使用ListUsers

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun listAllUsers() { IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.listUsers(ListUsersRequest { }) response.users?.forEach { user -> println("Retrieved user ${user.userName}") val permissionsBoundary = user.permissionsBoundary if (permissionsBoundary != null) { println("Permissions boundary details ${permissionsBoundary.permissionsBoundaryType}") } } } }
  • 有关API详细信息,请参阅ListUsers中的 Kotlin AWS SDK API 参考

以下代码示例显示了如何使用UpdateUser

SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun updateIAMUser( curName: String?, newName: String?, ) { val request = UpdateUserRequest { userName = curName newUserName = newName } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.updateUser(request) println("Successfully updated user to $newName") } }
  • 有关API详细信息,请参阅UpdateUser中的 Kotlin AWS SDK API 参考