How to replace hardcoded Ids in Metadata during a deployment using SFDX
Having hardcoded Ids in Salesforce metadata makes it very hard for CI/CD automations, in many cases, a post deploy step is required to change the ids in the target org, as a good practice, any hardcoded ids in metadata should be avoided in the first place, but in reality, we still face this problem with many legacy orgs on a daily basis. a clean-up project sometimes is just too expensive and not practical due to a very tight project schedule and budget.
Writing custom scripts or some third party tools could be the solution to this issue, but recently we have got a good news, a new feature just came out from the SFDX release on 7.176.1 (Nov 10, 2022) that “You can now automatically 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.“, and the string replacement is "ephemeral", which does not change the metadata locally.
Let’s use a process builder with a hardcoded id as an example:
As you can see in the the process builder metadata snippet below, the id is hardcoded in the xml file
<processMetadataValues> <name>operatorDataType</name> <value> <stringValue>String</stringValue> </value> </processMetadataValues> <processMetadataValues> <name>rightHandSideType</name> <value> <stringValue>ID</stringValue> </value> </processMetadataValues> <leftValueReference>myVariable_current.Id</leftValueReference> <operator>EqualTo</operator> <rightValue> <stringValue>0011y00000Y2e6AAAR</stringValue> </rightValue> </conditions> <connector> <targetReference>myAssignment_myRule_1_A1</targetRefere
Here are the steps to replace this account id with the account id in your target org during a deploument:
Step 1: Add the following snippet into your project sfdx-project.json file, here is an example, the “filename” is the metadata file with the id that needs to be replaced, and “replaceWithEnv” is the environment variable you can define in your pipelines to replace the hardcodedid in this case.
"replacements": [ { "filename": "force-app/main/default/flows/a_hardcoded_id_process_example.flow-meta.xml", "stringToReplace": "0011y00000Y2e6AAAR", "replaceWithEnv": "TARGET_ORG_ACCOUNTID" } ]
Step 2: Assign an account id value from the target org to the environment variable TARGET_ORG_ACCOUNTID (defined in step 1), for example:
export TARGET_ORG_ACCOUNTID = {account id in the target org}
Step 3: Run sfdx commands to replace the ids during the deployment
sfdx force:source:push or sfdx force:source:deploy
You can find the full example in https://github.com/junliu724515/ReplaceHardcodedIds, this is a very nice feature to make it much easier to change values in your XML during a deployment.
If you have any questions or suggestions, please feel free to contact me.