[SOLVED] Ephemeral environments and environment variables

Hi team,

We’ve just released a sweet new Next.js site on Netlify, using Contentful CMS to provide us content. We have a great CI/CD Pipeline that will run when a new tag is pushed (e.g. prod/1.0.0), which creates a new Contentful environment/branch for us, and builds and deploys the site to Netlify via netlify-cli. Our Netlify site always knows which Contentful environment to use via a handy Contentful feature known as a branch alias, and a configured environment variable in Netlify, so we don’t have to update any environment variables in Netlify when we trigger a release.

However… now we want to set up ephemeral environments for testing when big new features are being developed or big content changes are happening. We don’t want a persistent test or staging environment, as they may be multiple users/teams working on new features at any given point so will need distinct Contentful environments. The dream is this:

  1. Developer creates a tag in Gitlab e.g. (release/sweet-new-feature)
  2. A Contentful environment is created (e.g. release-sweet-new-feature)
  3. Netlify branch environment variable created with the newly created Contentful environment as its value
  4. Netlify branch deployment created that uses our new environment variable
  5. Testers can access the new environment on a shareable URL and change/test content in our temp Contentful environment for testing purposes

Everything is working up until step 4. The created branch deployment (specifically the Netlify functions) don’t seem to be using the branch variables we’re setting dynamically in step 3, and instead just use the non-context environment variables.

Here’s the two commands we’re running in our pipeline:

yarn netlify env:set CONTENTFUL_ENVIRONMENT $CI_COMMIT_REF_SLUG --context branch:$CI_COMMIT_REF_SLUG
yarn netlify deploy --build --debug --context branch:$CI_COMMIT_REF_SLUG --alias $CI_ENVIRONMENT_SLUG --skip-functions-cache --site=$NETLIFY_SITE_ID --auth=$NETLIFY_AUTH_TOKEN --message "Deployed $CI_COMMIT_REF_SLUG"

I think the issue is this damning snippet from the docs:

“… alias doesn’t create a branch deploy and can’t be used in conjunction with the branch subdomain feature. Maximum 37 characters.”

Is there any way to create temporary branch or preview deployments with a unique set of environment variables?

Alright, this is a little embarrassing. But for the eagle-eyed among you you can probably see the typo.

You’ll note that the alias flag in the netlify deploy command is using $CI_ENVIRONMENT_SLUG instead of $CI_COMMIT_REF_SLUG which was causing the disconnect.

If anyone has any questions on our approach or need help to achieve similar, let me know! I’d be glad to try and help.

Hey there, @jdubz :wave:

Not embarrassing at all. Thank you so much for coming back and updating this thread with your solution. Glad everything is working now.

Happy building :rocket: