0

Am trying to create a new namespace once I run the pipeline in Gitlab, and this namespace will have the name of the branch I push to it!

So how I can pass a variable that namespace manifest file can read it? Is there any way to pass it with gitlab-ci.yml?

example of what i'm thinking about:

apiVersion: v1
kind: Namespace
metadata:
  name: $CI_COMMIT_BRANCH
Noraa
  • 35
  • 5

1 Answers1

1

So the best answer here would be to recommend Helm since you are effectively asking for dynamic yaml templates. Since version 3 of Helm it does not require any server-side components like Tiller so it is much easier to use.

There are however, two more pragmatic approaches if you don't want to convert all your files to be Helm templates


sed

By using sed you could find/replace the env variable in your (assumption) namespace.yml like this:

script:
  - sed -i "s/\$CI_COMMIT_BRANCH/$CI_COMMIT_BRANCH/g" namespace.yml
  - kubectl apply -f namespace.yml

The -i stands for 'in-place', leave it if you want to save to a new file or STDOUT.


envsubst

If you have multiple yaml files and need to mass find/replace, using envsubst (part of the gnu gettext utilities) is another option.

It finds all environment variables in a file and replaces them with their actual values as present in the current environment. This looks like this (original answer):

script:
  - envsubst < "namespace.yml" > "namespace-replaced.yml"
  - kubectl apply -f namespace-replaced.yml

Note, as stated in the related answer: If you want to use the same file for both, you'll have to use something like moreutil's sponge: envsubst < "namespace.yml" | sponge "namespace.yml" . (Because the shell redirect will otherwise empty the file before its read.


Final tips:

  • Please don't define namespaces in your yaml files (except for namespace.yml) as it is not a best-practice. Use kubectl to set the target namespace instead: kubectl apply -f deployment.yml --namespace=$CI_COMMIT_BRANCH
  • Don't use the $CI_COMMIT_BRANCH in relation to k8s. It's the full branch name and can contain special chars and spaces. Instead use $CI_COMMIT_REF_SLUG as predefined CI variable since this is the branch or tag name for which project is built, lowercased, shortened to 63 bytes, and with everything except 0-9 and a-z replaced with -. No leading / trailing -. Use in URLs, host names and domain names.
Stefan van Gastel
  • 4,330
  • 23
  • 25