spring-bootkotlinamazon-eksfabric8

How to retrieve EKS services programatically?


I'm trying to get the list of services from EKS using Spring boot and Kotlin. I was able to make it work with the following using fabric8:

@Configuration
class AwsConfig {
  @Bean
  fun kubernetesClient(): KubernetesClient {
    return KubernetesClientBuilder()
      .withConfig(
        ConfigBuilder()
          .withMasterUrl("master-url")
          .withOauthToken(
            "hard-coded-oauth-token"
          )
          .withTrustCerts()
          .build(),
      )
      .build()


  }
}

and then:

@Service
class EksService(val kubernetesClient: KubernetesClient) {
  fun getServices() {
    val services = kubernetesClient.services().list()
    println(services)

  }
}

I generated the "hard-coded-oauth-token" via cli command: aws eks get-token --cluster-name <cluster-name>

I'm trying to figure out how I can generate this oauth token progrematically, I couldn't find any documentation on that


Solution

  • I finally figured it out, with the help of this answer: https://stackoverflow.com/a/60204304

    The code is in kotlin:

    @Configuration
    class AwsConfig {
      @Bean
      fun kubernetesClient(): KubernetesClient {
        return KubernetesClientBuilder()
          .withConfig(
            ConfigBuilder()
              .withMasterUrl("https://<clusterId>.<region>.eks.amazonaws.com")
              .withTrustCerts()
              .withOauthTokenProvider { getToken() }
              .build(),
          )
          .build()
      }
    
      fun getToken(): String {
        val stsUri = URI("https", "sts.${<region>}.amazonaws.com", "/", null)
        val requestToSign = SdkHttpFullRequest
          .builder()
          .method(SdkHttpMethod.GET)
          .uri(stsUri)
          .appendHeader("x-k8s-aws-id", "<cluster_name>")
          .appendRawQueryParameter("Action", "GetCallerIdentity")
          .appendRawQueryParameter("Version", "2011-06-15")
          .build()
    
        val presignerParams = Aws4PresignerParams.builder()
          .awsCredentials(
            AwsSessionCredentials.create(.....),
          )
          .signingRegion(EU_CENTRAL_1)
          .signingName("sts")
          .signingClockOverride(Clock.systemUTC())
          .expirationTime(Instant.now().plus(60, ChronoUnit.SECONDS))
          .build()
    
        val signedRequest = Aws4Signer.create().presign(requestToSign, presignerParams)
    
        val encodedUrl: String = Base64.getUrlEncoder().withoutPadding().encodeToString(
          signedRequest.uri.toString().toByteArray(),
        )
        return ("k8s-aws-v1.$encodedUrl")
      }