0

Is there a way to pass GitHub Actions environment variables to the Kubernetes index file?

The workflow file, this part will get the run number:

- name: Taggig
  run: |
    echo "imageTag=${{ github.run_number }}" >> $GITHUB_ENV

And I want to pass it to the index like -

Example:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-container
        image: my-image:{{ env.imageTag }}
Azeem
  • 11,148
  • 4
  • 27
  • 40
Baequiraheal
  • 119
  • 1
  • 13
  • Relevant: https://stackoverflow.com/questions/75675348/how-can-i-use-github-secrets-in-a-npmrc-file – Azeem Mar 13 '23 at 09:49
  • With `image: my-image:$imageTag`, you can use `envsubst`. I've been using `envsubst` to populate k8s manifests for quite some time now without any issues so far. – Azeem Mar 13 '23 at 11:04
  • @Azeem tried one of the suggestions ( replacing with sed ), worked fine. Thanks! – Baequiraheal Mar 14 '23 at 12:07
  • Great! You're welcome! BTW, I'd prefer `envsubst` to `sed`. With `sed`, you have to write it explicitly. For one variable, it might not be an issue. But, with multiple variables, it becomes quite cumbersome in the long run. Anyways, you'll figure it out later. ;) – Azeem Mar 14 '23 at 12:30
  • The tip is really helpful! I had to use sed for 5-10 variables and I already don't feel it pretty. – Baequiraheal Mar 16 '23 at 08:14

1 Answers1

1

You can use envsubst as Azeem mentioned:

So you would have something like:

containers:
  - name: my-container
    image: my-image:$imageTag

In your deployment file, then with envsubst you would substitute that imageTag environment variable with:

envsubst < deployment.yml 

Supposedly you named your deployment file as deplyoment.template.yml, you'd have an something like:

steps:
  - name: Taggig
    run: |
      echo "imageTag=${{ github.run_number }}" >> $GITHUB_ENV
  - name: Render k8s manifests
    run: envsubst < deployment.template.yml > deployment.yml 
  
  - run: kubectl apply -f ./deployment.yml

One other approach is to use kubectl set image, for example:

  - name: Taggig
    run: |
      echo "imageTag=${{ github.run_number }}" >> $GITHUB_ENV

  - run: kubectl set image -f deployment.template.yml  my-container=my-image:$imageTag --local -o yaml > deployment.yml 

  - run: kubectl apply -f ./deployment.yml         

Alternatively, you can use kustomize or yq to set your image:tag value

Fcmam5
  • 4,888
  • 1
  • 16
  • 33