2

in others language like PHP or NodeJs. I can use .env file to store enviroment variables. For example, I need to use one enviroment variable is API_URL

  • Then in local:
API_URL will have a value of 'http:localhost:3000'
  • In DEV:
API_URL will have a value of 'http:url_dev.com'
  • In Production:
API_URL will have a value of 'http:url_production.com'

So I want to ask that in salesforce, is it possible to use enviroment variable like above example? If it can do, please let me know how to do it?

1
  • Which metadata do you want this capability to work with? Nov 13, 2022 at 12:26

1 Answer 1

3

There is a new feature in the Salesforce CLI version 7.176.1 documented in the release notes.

Replace snippets of your metadata source files with specific values right before you deploy the files to an org with the force:source:deploy|push commands! Note works with only the force:source:deploy or push commands of the CLI

To create a replacement you will need a section named replacements in your sfdx-project.json

"replacements": [
 {
  "filename": "force-app/main/default/classes/myClass.cls",
  "stringToReplace": "replaceMe",
  "replaceWithEnv": "THE_REPLACEMENT"
  "replaceWhenEnv": [{
     "env": "DEPLOY_DESTINATION",
     "value": "PROD"
     }]  
 }
]

The above implied Replace THE_REPLACEMENT in the Apex class myClass with the string replaceMe when there is an environment variable named DEPLOY_DESTINATION with value PROD.

You can specify these keys in the replacements property:

filename: Single file that contains the string to be replaced.

glob: Collection of files that contain the string to be replaced. Example: **/classes/*.cls.

stringToReplace: The string to be replaced.

regexToReplace: Regular expression that specifies a string pattern to be replaced.

replaceWithEnv: Specifies that the string be replaced with the value of the environment variable.

replaceWithFile: Specifies that the string be replaced with the contents of a file.

replaceWhenEnv: Specifies a condition, using environment variables, for when a string replacement occurs.

Currently it does not support a file format of .env so you would need a true environment variable in your operating system.

1
  • Mohit, why i would do like this and not use Custom labels ? Becaz, In later case i will have to update labels for each environment ? Nov 14, 2022 at 13:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .