はじめに
オペレーション部の坂本です。 デベロッパープレビュー版のAWS SDK for Kotlinの一般利用が可能になりました。
AWS SDK for Kotlin is now generally available
ドキュメントを確認すると、サンプルコードがありましたので、サンプルコードを用いてAWS SDK for Kotlinを使ってみました。
検証環境
macOS: 14.11 Kotlin version 1.9.21-release-633 (JRE 17.0.9+7-b1087.7) JDK:openjdk 17.0.9 Gradle:8.5.
サンプルコードについて
Get started with the SDK for Kotlinで紹介されているS3バケットとバケット内にオブジェクトを作成して、削除する例を試します。
今回は削除部分をコメントアウトして、S3バケットの作成とオブジェクトの作成をします。 チュートリアルではIAM Identity Centerのセットアップ方法について案内がありますが、IAM ユーザーのアクセスキーを用いて検証をしております。
サンプルコード
▪️gradle.build.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.9.10"
application
}
group = "example.aws"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
implementation("aws.sdk.kotlin:s3:1.0.0")
testImplementation(kotlin("test"))
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.withType<KotlinCompile>() {
kotlinOptions.jvmTarget = "17"
}
application.mainClass.set("example.aws.getstarted.AppKt")
▪️src/main/kotlin/example/aws/getstarted/App.kt ※リージョンを"ap-northeast-1" に書き換えて、29行目のcleanUp(s3)をコメントアウトしています。
package example.aws.getstarted
import aws.sdk.kotlin.services.s3.*
import aws.sdk.kotlin.services.s3.model.BucketLocationConstraint
import aws.smithy.kotlin.runtime.content.ByteStream
import kotlinx.coroutines.runBlocking
import java.util.UUID
val REGION = "ap-northeast-1"
val BUCKET = "bucket-sample-bucket-${UUID.randomUUID()}"
val KEY = "key"
fun main(): Unit = runBlocking {
S3Client
.fromEnvironment { region = REGION }
.use { s3 ->
setupTutorial(s3)
println("Creating object $BUCKET/$KEY...")
s3.putObject {
bucket = BUCKET
key = KEY
body = ByteStream.fromString("Testing with the Kotlin SDK")
}
println("Object $BUCKET/$KEY created successfully!")
// cleanUp(s3)
}
}
suspend fun setupTutorial(s3: S3Client) {
println("Creating bucket $BUCKET...")
s3.createBucket {
bucket = BUCKET
createBucketConfiguration {
locationConstraint = BucketLocationConstraint.fromValue(REGION)
}
}
println("Bucket $BUCKET created successfully!")
}
suspend fun cleanUp(s3: S3Client) {
println("Deleting object $BUCKET/$KEY...")
s3.deleteObject {
bucket = BUCKET
key = KEY
}
println("Object $BUCKET/$KEY deleted successfully!")
println("Deleting bucket $BUCKET...")
s3.deleteBucket {
bucket = BUCKET
}
println("Bucket $BUCKET deleted successfully!")
}
実行結果
バケットとオブジェクトが作成されたことがわかります。
まとめ
Androidアプリ開発の際にとても良さそうですね。
Get started with the SDK for Kotlin はS3の例でしたが、GithubのawsdocsのKotlinのディレクトリにサービスやユースケース毎の例がありますので、ぜひご参照にください。