Coder Social home page Coder Social logo

k8s-kotlin-dsl's Introduction

Build Status

Kotlin DSL for Kubernetes and Openshift Container Platform on top of fabric8 client.

screencast

Usage

k8s-kotlin-dsl package can be found on jitpack. Simply add following lines to your build.gradle:

allprojects {
   	repositories {
   		 maven { url 'https://jitpack.io' }
   	}
}

dependencies {
   implementation("com.github.fkorotkov:k8s-kotlin-dsl:${kubernetes_dsl_version}")
}

Using with kubernetes-client

Let's check out how to create an Ingress via fabric8 client. Don't forget to add a dependency on io.fabric8:kubernetes-client:${kubernetes_client_version}.

import com.fkorotkov.kubernetes.extensions.*
import io.fabric8.kubernetes.api.model.IntOrString
import io.fabric8.kubernetes.client.DefaultKubernetesClient


fun main() {
  val client = DefaultKubernetesClient().inNamespace("default")
  client.extensions().ingresses().createOrReplace(
    newIngress {
      metadata {
        name = "example-ingress"
      }
      spec {
        backend {
          serviceName = "example-service"
          servicePort = IntOrString(8080)
        }
      }
    }
  )
}

Apply modifications

By leveraging awesomeness of Kotlin it becomes super easy to have a base service template that every microservice is created from:

val baseService = defaultServiceTemplate()
baseService.apply {
  metadata {
    name = "foo"
  }
}

Complete Deployment example

Here is an example of BaseDeployment that defines a deployment with one replica and mounts a secret that can be used by the service.

import com.fkorotkov.kubernetes.*
import com.fkorotkov.kubernetes.apps.*
import io.fabric8.kubernetes.api.model.IntOrString
import io.fabric8.kubernetes.api.model.apps.Deployment

class BaseDeployment : Deployment {
  constructor(serviceName: String) {
    metadata {
      name = "$serviceName-service-deployment"
      labels = mapOf(
        "app" to serviceName,
        "tier" to "backend"
      )
    }
    spec {
      replicas = 1
      template {
        metadata {
          labels = mapOf(
            "app" to serviceName,
            "tier" to "backend"
          )
        }
        spec {
          containers = listOf(
            newContainer {
              name = "$serviceName-service"
              image = "gcr.io/fkorotkov/$serviceName-service:latest"
              volumeMounts = listOf(
                newVolumeMount {
                  name = "gcp-credentials"
                  mountPath = "/etc/credentials"
                  readOnly = true
                }
              )
              env = listOf(
                newEnvVar {
                  name = "GOOGLE_APPLICATION_CREDENTIALS"
                  value = "/etc/credentials/service-account-credentials.json"
                }
              )
              ports = listOf(
                newContainerPort {
                  containerPort = 8080
                }
              )
              livenessProbe {
                httpGet {
                  path = "/healthz"
                  port = IntOrString(8080)
                }
                periodSeconds = 60
              }
              readinessProbe {
                httpGet {
                  path = "/healthz"
                  port = IntOrString(8080)
                }
                initialDelaySeconds = 10
                periodSeconds = 60
              }
            }
          )
          volumes = listOf(
            newVolume {
              name = "gcp-credentials"
              secret {
                secretName = "gcp-credentials"
              }
            }
          )
        }
      }
    }
  }
}

Contribution

Check CONTRIBUTING.md

k8s-kotlin-dsl's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

k8s-kotlin-dsl's Issues

More examples if possible

Hi just to say a big thanks for this repo it is very cool, and I have been exploring using it. I have found that maybe some examples maybe in the for of test per Kubernetes object type would be useful to start understanding how to use the builders.

Thank you. kindly
Oscar

Maven

Can you put this on maven to make it easier to integrate

Jcenter is a pita to set this up with

Openshift variant

Hello.

We are looking into using this project but we are targetting Openshift. I see that you exclude those classes in a configuration settings. How do you want us to proceeed here? Can you create an artifact for oc-kotlin-dsl aswell as one for k8s-kotlin-dsl or should we just fork and create it ourselves?

We here is skatteetaten/tax norway IT.

Defining ingress backend with port instead of servicePort

If I have a desired yaml definition of an ingress like this

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: myapp-reader-feature-internal
  namespace: myteam
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
      proxy_set_header l5d-dst-override $service_name.$namespace.svc.$clusterDomain:$service_port;
      grpc_set_header l5d-dst-override $service_name.$namespace.svc.$clusterDomain:$service_port;
  labels:
    app: myapp-reader-feature

spec:
  tls:
  - hosts:
    - myteam-myapp-feature.dev.example.com
  rules:
  - host: myteam-myapp-feature.dev.example.com
    http:
      paths:
      - backend:
          service:
            name: myapp-reader-feature
            port:
              number: 8080
        pathType: ImplementationSpecific

I have not found a way to model the spec.rules.http.paths.backend correctly. What I am doing is this

fun myingress(): HasMetadata {
    return newIngress {
        apiVersion = "networking.k8s.io/v1"
        metadata {
            name = "myapp-feature-internal"
            namespace = "myteam"
            annotations = mapOf(
                "nginx.ingress.kubernetes.io/configuration-snippet" to
                        """
                           proxy_set_header l5d-dst-override ${"$"}service_name.${"$"}namespace.svc.${"$"}clusterDomain:${"$"}service_port;
                           grpc_set_header l5d-dst-override ${"$"}service_name.${"$"}namespace.svc.${"$"}clusterDomain:${"$"}service_port;""".trimIndent()
            )
            labels = mapOf("app" to "myapp-feature")
        }
        spec {
            newIngressTLS {
                hosts = listOf("myteam-myapp-feature.example.com")
            }
            rules = listOf(newIngressRule {
                host = "myteam-myapp-feature.example.com"
                http = newHTTPIngressRuleValue {
                    paths = listOf(newHTTPIngressPath {
                        backend {
                            serviceName = "myapp-feature"
                            servicePort = IntOrString(8080)
                        }
                        pathType = "ImplementationSpecific"
                    })
                }
            })
        }
    }
}

Which gives me

---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |-
      proxy_set_header l5d-dst-override $service_name.$namespace.svc.$clusterDomain:$service_port;
      grpc_set_header l5d-dst-override $service_name.$namespace.svc.$clusterDomain:$service_port;
  labels:
    app: myapp-feature
  name: myapp-feature-internal
  namespace: myteam
spec:
  rules:
  - host: myteam-myapp-feature.example.com
    http:
      paths:
      - backend:
          serviceName: myapp-feature
          servicePort: 8080
        pathType: ImplementationSpecific

There seems to be no way to express this part:

      - backend:
          service:
            name: myapp-feature
            port:
              number: 8080

The resulting yaml from the above kotlin code is even flagged as invalid kubernetes yaml when linting it.

Using these versions:

    implementation("com.github.fkorotkov:k8s-kotlin-dsl:3.1.1")
    implementation("io.fabric8:kubernetes-client:5.11.1")

Getting java doc on the dsl

Hi,

Even if type and autocompletion done by IDE are great auto-documentation, It would be even nicer to have java doc. So when you require doc from your IDE you can have something better than:
Screenshot 2020-03-15

Tx man

Fabric8 moved or dead?

I noticed the the link in the README.md points to an "archived" repository: fabric8 models

[fabric8 models](https://github.com/fabric8io/kubernetes-model)

I couldn't determine what the status of that dependency now is -- is it still maintained? What does it mean for this project?

Thank you.

fabric8 non RC version available

There is no urgent need for me to update, but fabric8 is now on stable version 6.4. Maybe we could update the version as well to get rid of the RC version?

Idea: Use ScopeControl with DslMarker

Thank you for this nice library!

I made the occasional error where the nesting of my code did not reflect the nesting of the document structure.

Maybe that could be improved via @DslMarker?

Unfortunately, that would be a potentially breaking change.

Issue generating deployment template

Hi,

I'm having issues generating a valid deployment, hopefully this is just an easy error in my DSL. In trying to follow the kubernetes docs for deployments, I thought it would be a good "hello world" to try to recreate this deployment with Kotlin

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

My attempt thus far has lead me to the following DSL

class SimpleDeployment : Deployment() {
  init {
    metadata {
      name = "nginx-deployment"
      labels = mapOf("app" to "nginx")
    }
    spec {
      replicas = 3
      selector {
        matchLabels = mapOf(
          "app" to "nginx"
        )
      }
      template {
        metadata {
          labels = mapOf("app" to "nginx")
        }
        spec {
          newContainer {
            name = "nginx"
            image = "nginx:1.14.2"
            ports = listOf(newContainerPort { containerPort = 80 })
          }
        }
      }
    }
  }
}

Unfortunately, this code block seems to sorta fizzle out at the template block, because the resulting YAML is

apiVersion: "apps/v1"
kind: "Deployment"
metadata:
  labels:
    app: "nginx"
  name: "nginx-deployment"
spec:
  replicas: 3
  selector:
    matchLabels:
      app: "nginx"
  template: {}

I'm pretty new to Kotlin and in all honest am kind of struggling to debug it ๐Ÿ˜•

Currently I am using the following versions

  val kFabric8Version = "2.8"
  val fabric8Version = "4.10.3"
  ... 
  implementation("com.fkorotkov:kubernetes-dsl:$kFabric8Version")
  implementation("io.fabric8:kubernetes-client:$fabric8Version")

Any tips/advice would be amazing!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.