Search code examples
gokubernetescronkubernetes-ingress

How can I make authorized requests to secured API endpoint from cronjobs?


I have a golang application which has API key authorization via the JWT token

I am using Kubernetes. So, this golang app is in a pod.

Now, I want to create another application for cronjobs to hit golang endpoint once a week.

What I need:

How to do / skip the authorization?

skip: Ingress is not required here as I can simply call it internally. Can that help this case?

What I Tried:

I tried keeping the cronjobs and api in the same application so I can simply call the service instead of the endpoint, But that also has a drawback. I am not able to create replicas as they will also replicate the cronjobs and the same endpoint will be hit 1*no of replicas times

I want to call "abc.com" endpoint once a week. It requires a token and I cannot simply pass a token. I hope there is some way around this.


Solution

  • If you just have to call them internally without exposing them, it can certainly help.
    Provided both Pods (and therefore Deployments) are running under the same Cluster you can use Kubernetes' internal DNS.

    K8s automatically creates DNS records for Services you create that can be used for internal communication by following this specific format: <service-name>.<service-namespace>.svc.cluster.local

    More information from the official docs here: DNS for Services and Pods

    If it sounds weird or if it can help understanding the gist of it, try to think of the "endpoint" as a rule you add to your system's hosts file: it boils down to basicly adding a rule where <service-name>.<service-namespace>.svc.cluster.local points to your pod's IP address, except it's done automatically

    E.g.

    • Your golang app is running inside a Pod.
    • You created a Service pointing to it, named go-api and under the namespace go-apps.
    • If your cron-job worker is running in a Pod inside the same cluster, you can use go-api.go-apps.svc.cluster.local[:<port>] to reach your app without using an Ingress

    The authorization is up to you, since you're usually handling it either directly or by using specific frameworks. You could, for example, add a custom endpoint path inside your app where you make sure that the only accepted clients come from the same, private IP subnet of your cluster, either without a token (not recommended) or with a specific semi-fixed one that you generate and control, so that you would send a request to something like this from your crons: go-api.go-apps.svc.cluster.local:8080/api/v1/callWithNoAuth