Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interpolate environment variables within netlify.toml config

Tags:

netlify

I want to proxy to a different api depending on the environment - I've tried a few variations on the following theme without any luck. What's the correct way of doing this, if its even possible?

[build.environment]
  API_URI="https://dev-api.foo.com/:splat"

[context.production.environment]
  API_URI="https://prod-api.foo.com/:splat"

[[redirects]]
  from = "/api/*"
  to = "$API_URI"
  status = 200
  force = true

This does not work.

Although the above config works when I hardcode a URI into the to field, it just fails when I try to interpolate an env var.

like image 700
Jed Richards Avatar asked Jun 11 '18 12:06

Jed Richards


2 Answers

It's not supported, but Netlify suggest a work-around in their documentation (https://www.netlify.com/docs/netlify-toml-reference):

Using Environment Variables directly as values ($VARIABLENAME) in your netlify.toml file is not supported. However, the following workflow can be used to substitute values based on environment variables in the file, assuming you are only trying to change headers or redirects. The rest of the file is read BEFORE your build - but those sections are read AFTER the build process.

  1. Add a placeholder like API_KEY_PLACEHOLDER somewhere in the netlify.toml redirects or headers sections.
  2. Create an Build Environment Variable, for example API_KEY, with the desired value. You can do this in the toml file or in our UI in the Build and Deploy Settings section of your configuration. You might use the latter to keep sensitive values out of your repository.
  3. Add a command like this one to your build command: sed -i s/API_KEY_PLACEHOLDER/$API_KEY/g netlify.toml && normal build command.
like image 150
oligopol Avatar answered Oct 14 '22 12:10

oligopol


Answering my own question - it's not supported, you have to manually interpolate env vars yourself as part of the build on Netlify.

like image 44
Jed Richards Avatar answered Oct 14 '22 13:10

Jed Richards