opensource-developer
opensource-developer

Reputation: 3068

Is there a way to use environment variables in deployment spec file

I have a cron job with below spec. I am sending a POST request to end point after specific intervals. I need to change the urls based on the environment like staging or production

Is there a way i can use the ENV variable in place of domain name and not create two separate files to use two different urls.

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: testing
spec:
  schedule: "*/20 * * * *"
  suspend: false
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - name: testing
              image: image
              ports:
                - containerPort: 3000
              args:
              - /bin/sh
              - -c
              - curl -X POST #{USE_ENV_VARIABLE_HERE}/api/v1/automated_tests/workflows #how to make this generic
          restartPolicy: Never

Upvotes: 0

Views: 876

Answers (2)

mario
mario

Reputation: 11158

If you don't want to set environment variables in your Pods via Secrets or ConfigMaps but rather use your locally set env vars, you could use a fairly simple sed trick, which I described some time ago in this answer (Update section).

In your CronJob yaml you need to set {{URL}} placeholder:

args:
- /bin/sh
- -c
- curl -X POST {{URL}}/api/v1/automated_tests/workflows #how to make this generic

then, when applying the CronJob yaml definition, instead of simple kubectl apply -f testing-cronjob.yaml run this one-liner:

sed "s/{{URL}}/$URL/g" testing-cronjob.yaml | kubectl apply -f -

The above command tells sed to search through testing-cronjob.yaml document for {{URL}} string and each time this string occurs, to substitute it with the actual value of $URL environment variable, set on your local system (from which you run the command).

Upvotes: 0

Pulak Kanti Bhowmick
Pulak Kanti Bhowmick

Reputation: 1255

You can use env variable via secret or config map. Here I have given an example with secret.

# secrets.yaml
apiVersion: v1
kind: Secret
metadata:
  name: demo-secret
type: Opaque
stringData:
   BASE_URL: "example.com"

Then you can use that secret as env in container.

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: testing
spec:
  schedule: "*/20 * * * *"
  suspend: false
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - name: testing
              image: image
              ports:
                - containerPort: 3000
              envFrom:
                - secretRef:
                     name: demo-secret
              args:
              - /bin/sh
              - -c
              - curl -X POST ${BASE_URL}/api/v1/automated_tests/workflows
          restartPolicy: Never

Upvotes: 1

Related Questions