Variable substitution in a configuration file

3/11/2021

Variable substitution in Gitlab only seem to work inside the gitlab-ci.yml file.

However I have a configuration file (k8s secret) where I would like to set different values depending if I'm in a staging or a production environment.

apiVersion: v1
kind: Secret
metadata:
  name: tls-config
  namespace: myNamespace
type: kubernetes.io/tls
data:
  tls.crt: |
    ${TLS_CRT}

  tls.key: |
    ${TLS_KEY}

Where TLS_CRT & TLS_KEY would be variables defined in /settings/ci_cd/variables.

How should one handle variable substitution in this case?

-- Mit94
gitlab
gitlab-ci
kubernetes

1 Answer

3/13/2021

You could use an editor like sed

For example, if you had the file like:

data:
  tls.crt: |
    #TLS_CRT#

  tls.key: |
    #TLS_KEY#

You could use sed like this as part of your GitLab job to replace its contents:

myjob:
  script:
  - sed -i "s|#TLS_CRT#|${TLS_CRT}|" ./path/to/file
  - sed -i "s|#TLS_KEY#|${TLS_KEY}|" ./path/to/file

Then the file contents will be something like this:

data:
  tls.crt: |
        MIIC2DCCAcCgAwIBAgIBATANBgkqh ...
  tls.key: |
        MIIEpgIBAAKCAQEA7yn3bRHQ5FHMQ ...

Using the pattern #word# is not totally necessary. However, it does make using the sed easier, as it avoids needing to escape the literal ${} characters in the shell command.

As a short explanation of the sed command used here:

#    v shorthand for --in-place; edits the file directly
sed -i "s|FIRST_ARGUMENT|SECOND_ARGUMENT|" ./path/to/file
#         ^ replace this ^ with this       ^ in this file

Fore more info, see here: https://unix.stackexchange.com/a/112024/453397

-- sytech
Source: StackOverflow