Last active
June 10, 2021 02:13
-
-
Save pgreze/04bce7ca50a0a5b8f2f470acaefe91db to your computer and use it in GitHub Desktop.
Google Secret Manager with Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@file:DependsOn("com.google.cloud:google-cloud-secretmanager:1.6.2") | |
import com.google.api.gax.core.FixedCredentialsProvider | |
import com.google.api.gax.rpc.PermissionDeniedException | |
import com.google.auth.oauth2.ServiceAccountCredentials | |
import com.google.cloud.secretmanager.v1.AccessSecretVersionResponse | |
import com.google.cloud.secretmanager.v1.ProjectName | |
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient | |
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings | |
import java.io.File | |
fun main(args: Array<String>) = | |
serviceAccountManagedSecretManager( | |
serviceAccount = File(args.first()) | |
).use { service -> | |
val serviceAccount = args.first() | |
println("ServiceAccount: $serviceAccount") | |
// Requires the "secretmanager.secrets.list" permission. | |
if (serviceAccount.contains("local").not()) { | |
service.printAllSecrets() | |
} | |
service.printSecret("projects/78375415386/secrets/X_MERCARI_AUTOMATION") | |
try { | |
service.printSecret("projects/78375415386/secrets/google-services-prod") | |
} catch (e: PermissionDeniedException) { | |
System.err.println(e.toString()) | |
} | |
} | |
private fun SecretManagerServiceClient.printAllSecrets() { | |
listSecrets(ProjectName.of("78375415386")).iterateAll().forEach { secret -> | |
printSecret(secret.name) | |
} | |
} | |
private fun SecretManagerServiceClient.printSecret(name: String, version: String = "latest") { | |
val secretId = "$name/versions/$version" | |
val secretValue = accessSecretVersion(secretId).payload.data.toStringUtf8() | |
.replace("\n", "").substring(0, 10) // Debug purpose | |
println("$secretId: $secretValue") | |
} | |
private fun serviceAccountManagedSecretManager(serviceAccount: File): SecretManagerServiceClient = | |
serviceAccount.inputStream().buffered().use { | |
val credentials = ServiceAccountCredentials.fromStream(it) | |
val credentialsProvider = FixedCredentialsProvider.create(credentials) | |
val serviceSettings = SecretManagerServiceSettings.newBuilder() | |
.setCredentialsProvider(credentialsProvider) | |
.build() | |
SecretManagerServiceClient.create(serviceSettings) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment