Ada lebih banyak contoh AWS SDK yang tersedia di repo Contoh SDK AWS Doc
Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.
Contoh IAM menggunakan SDK untuk Kotlin
Contoh kode berikut menunjukkan cara melakukan tindakan dan mengimplementasikan skenario umum dengan menggunakan AWS SDK untuk Kotlin dengan IAM.
Dasar-dasar adalah contoh kode yang menunjukkan kepada Anda bagaimana melakukan operasi penting dalam suatu layanan.
Tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Sementara tindakan menunjukkan cara memanggil fungsi layanan individual, Anda dapat melihat tindakan dalam konteks dalam skenario terkait.
Setiap contoh menyertakan tautan ke kode sumber lengkap, di mana Anda dapat menemukan instruksi tentang cara mengatur dan menjalankan kode dalam konteks.
Hal-hal mendasar
Contoh kode berikut menunjukkan cara membuat pengguna dan mengambil peran.
Awas
Untuk menghindari risiko keamanan, jangan gunakan pengguna IAM untuk otentikasi saat mengembangkan perangkat lunak yang dibuat khusus atau bekerja dengan data nyata. Sebaliknya, gunakan federasi dengan penyedia identitas seperti AWS IAM Identity Center.
Buat pengguna tanpa izin.
Buat peran yang memberikan izin untuk mencantumkan bucket Amazon S3 untuk akun tersebut.
Tambahkan kebijakan agar pengguna dapat mengambil peran tersebut.
Asumsikan peran dan daftar bucket S3 menggunakan kredenal sementara, lalu bersihkan sumber daya.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS
. Buat fungsi yang membungkus tindakan pengguna 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) }
-
Untuk detail API, lihat topik berikut di referensi API SDK untuk Kotlin AWS .
-
Tindakan
Contoh kode berikut menunjukkan cara menggunakanAttachRolePolicy
.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 }
-
Untuk detail API, lihat AttachRolePolicy
di AWS SDK untuk referensi API Kotlin.
-
Contoh kode berikut menunjukkan cara menggunakanCreateAccessKey
.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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() } }
-
Untuk detail API, lihat CreateAccessKey
di AWS SDK untuk referensi API Kotlin.
-
Contoh kode berikut menunjukkan cara menggunakanCreateAccountAlias
.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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") } }
-
Untuk detail API, lihat CreateAccountAlias
di AWS SDK untuk referensi API Kotlin.
-
Contoh kode berikut menunjukkan cara menggunakanCreatePolicy
.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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() } }
-
Untuk detail API, lihat CreatePolicy
di AWS SDK untuk referensi API Kotlin.
-
Contoh kode berikut menunjukkan cara menggunakanCreateUser
.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 } }
-
Untuk detail API, lihat CreateUser
di AWS SDK untuk referensi API Kotlin.
-
Contoh kode berikut menunjukkan cara menggunakanDeleteAccessKey
.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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") } }
-
Untuk detail API, lihat DeleteAccessKey
di AWS SDK untuk referensi API Kotlin.
-
Contoh kode berikut menunjukkan cara menggunakanDeleteAccountAlias
.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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") } }
-
Untuk detail API, lihat DeleteAccountAlias
di AWS SDK untuk referensi API Kotlin.
-
Contoh kode berikut menunjukkan cara menggunakanDeletePolicy
.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS
. suspend fun deleteIAMPolicy(policyARNVal: String?) { val request = DeletePolicyRequest { policyArn = policyARNVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.deletePolicy(request) println("Successfully deleted $policyARNVal") } }
-
Untuk detail API, lihat DeletePolicy
di AWS SDK untuk referensi API Kotlin.
-
Contoh kode berikut menunjukkan cara menggunakanDeleteUser
.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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") } }
-
Untuk detail API, lihat DeleteUser
di AWS SDK untuk referensi API Kotlin.
-
Contoh kode berikut menunjukkan cara menggunakanDetachRolePolicy
.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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") } }
-
Untuk detail API, lihat DetachRolePolicy
di AWS SDK untuk referensi API Kotlin.
-
Contoh kode berikut menunjukkan cara menggunakanGetPolicy
.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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}") } }
-
Untuk detail API, lihat GetPolicy
di AWS SDK untuk referensi API Kotlin.
-
Contoh kode berikut menunjukkan cara menggunakanListAccessKeys
.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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}") } } }
-
Untuk detail API, lihat ListAccessKeys
di AWS SDK untuk referensi API Kotlin.
-
Contoh kode berikut menunjukkan cara menggunakanListAccountAliases
.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS
. suspend fun listAliases() { IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.listAccountAliases(ListAccountAliasesRequest {}) response.accountAliases?.forEach { alias -> println("Retrieved account alias $alias") } } }
-
Untuk detail API, lihat ListAccountAliases
di AWS SDK untuk referensi API Kotlin.
-
Contoh kode berikut menunjukkan cara menggunakanListUsers
.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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}") } } } }
-
Untuk detail API, lihat ListUsers
di AWS SDK untuk referensi API Kotlin.
-
Contoh kode berikut menunjukkan cara menggunakanUpdateUser
.
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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") } }
-
Untuk detail API, lihat UpdateUser
di AWS SDK untuk referensi API Kotlin.
-