Cody M.
Cody M.

Reputation: 11

How can I put a Kubernetes Secret in a Cronjob curl command?

In kubernetes I have a secret defined, and in my deploy-templates YAML files, I have that secret set as ${mySecret}.

I am trying to create a CronJob that uses the following CURL to run the Job with the header info defined in the secret. No matter what I do, the ${mySecret} doesn't seem to get turned into the correct information.

Do I have to define it some other way in the YAML?

apiVersion: myjob/v1
kind: CronJob
metadata:
  name: {{ .Values.name }}-cronjobs
spec:
  schedule: "0 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          initContainers:
          - name: my-job
            image: curlimages/curl
            command: ["sh", "-c", "curl --location --request POST \"http://myservice:8080/api/endpoint\" --header \"my-secret: ${mySecret}\""]

Tried to use ${} in a yaml-based curl command. I expected the value to be parsed and run the job correctly. In reality, I get a BAD REQUEST error from the job every hour.

Upvotes: 1

Views: 4807

Answers (1)

Kristian Ferkić
Kristian Ferkić

Reputation: 498

You have to add the secret to the env-vars of your container. Suppose you have a my-secret secret:

apiVersion: v1
metadata:
  name: my-secret
type: Opaque
data:
  THE_SECRET: dG9wU2VjcmV0MTIz

Then you can reference the value in THE_SECRET in your cron-job like this:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: {{ .Values.name }}-cronjobs
spec:
  schedule: "0 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: my-job
            image: curlimages/curl
            command: ["sh", "-c", "curl --location --request POST \"http://myservice:8080/api/endpoint\" --header \"my-secret: ${THE_SECRET}\""]
            envFrom:
            - secretRef:
                name: my-secret
            - secretRef:
                name: other-secret

Upvotes: 4

Related Questions