The Salesforce Command Line Interface (CLI) is a powerful, free, open-source tool from Salesforce, intended to help simplify and potentially automate tasks across the platform. Ultimately, the Salesforce CLI supports and speeds up the development process for both developers and admins.
That’s right – the Salesforce CLI is very powerful for admins; it’s not just a fancy tool for developers! In this guide, you’ll learn how to get started, from downloading to installing, as well as the different ways you could use the Salesforce CLI.
What Is a CLI?
You may be thinking: This sounds great – another tool for my belt, but what is a CLI? This is a very good question as most non-developers are unlikely to encounter CLIs in their day-to-day lives.
A Command Line Interface is a text-based interface for a program, as opposed to the more common graphical-based interfaces (like the one you’re using to read this blog post!).
As you might expect, interacting with a text-based interface is very different from a graphical one; instead of clicking on buttons and inputs, you type out the commands for what you wish to achieve, which are then processed and run by the program. These achievements are quicker compared to a graphical interface, and allow for the easy automation of any repetitive tasks. However, there is a much steeper learning curve when you don’t have the visual prompts!
How Do I Download and Install the Salesforce CLI?
Getting hold of the CLI is simple – just head over to this website and select the appropriate version for your operating system. Once the file has been downloaded and installed, all you need to do is open up a terminal and enter the following command:
If everything was installed correctly, the above command should output the current version of the CLI that’s installed.
Alternatively, the CLI can be installed via npm, however, this is more useful for continuous integrations or situations where you don’t have admin/root access to the machine (and can’t install the CLI through the more standard methods).
How to Use the Salesforce CLI
Now that we’ve installed the Salesforce CLI, it’s time to use it. However, as I mentioned earlier, we need to provide text commands to do anything, so how do we find these commands? The quickest way is to use a simple command instructing the CLI to give us the information about what it does. Try running the following command:
This command outputs all of the commands the CLI accepts. The keen eyed amongst you will have noticed that almost all of these commands start with one of four words: alias, auth, config, or force. These are logical groupings for our commands, which we call “namespaces”, and each fulfills its own set of functionality:
- alias: Manages our login aliases. These are login credentials that we’ve authorized for use with the CLI. We can provide a user-friendly name such as “UAT” or “Prod”.
- auth: Authorize Salesforce orgs for use with the CLI. This namespace is further broken down into different sub categories, depending on how we want to authorize the org, which can be anything from logging in via our web browser, to using a JSON Web Token.
sfdx auth:web:login -a DeveloperSandbox
- config: Allows us to set and edit configuration variables for other commands to consume. This could be anything from the API version to use, or the default username for our commands.
sfdx config:get defaultusername
- force: This is where most of the CLI magic happens, and as such, it’s the largest and most frequently used namespace. It contains commands for interacting with an org including (but not limited to):
- Deploying and retrieving metadata.
- Generating scratch orgs or sandboxes.
- Building first and second generation packages.
- Running anonymous apex.
- Importing and exporting data.
sfdx force:source:deploy -m CustomObjects
If you were to try and run one of the commands outputted by sfdx commands, you’d probably be left scratching your head and wondering how to actually do what you want to do.
As an example, how can we deploy this Apex class? To do so, we provide each command with parameters to show our intent. These are provided after the name of the command and are prefixed with a single hyphen (when we’re using the shortened parameter name), or a double hyphen (when using the full name), for example, -w or –wait. These parameters are either standalone to indicate a boolean value of true, or we provide additional information on what that parameter value should resolve to.
For example, the following code block contains the command for deploying a specific Apex class by name, using the shortened form –metadata parameter flag.
sfdx force:source:deploy -m ApexClass:MyApexClass
3 Ways to Use the Salesforce CLI
Now that we know the basic structure of a command, let’s look into some real-life use cases and scenarios where we could use the CLI to help increase our efficiency.
1. Retrieve and Deploy Metadata
Imagine you’re a Salesforce Consultant and you’ve just completed a project involving the creation of a flow embedded in the utility bar – the intention was to allow end users to quickly raise cases and requests for help. The user testing was a great success and it was deployed from the testing environment to production using changesets – nothing out of the ordinary so far.
A few weeks later, a similar user story comes up in another project with a few subtle differences. Rather than redevelop the same feature twice, you decide to use the Salesforce CLI to kickstart this feature by deploying the known tried-and-tested solution from the previous org, before amending it to meet the client’s specific needs.
What next? Firstly, we create a new project for our metadata by running the following command – this will create the boilerplate files and folders for our metadata to live in and be deployed from. The -n parameter is the name of the folder which will be created to store our metadata, which will be created in our current working directory in the command line.
sfdx force:project:create -n CaseFlow
We need to change our terminal’s working directory to the newly created folder once that command finishes with the cd command (change directory).
Next we need to authorize the org for this project with the following command, which will use our web browser for easier login. The -a parameter is the friendly name we’re giving to this org. The -s parameter sets it as our default org for future commands in this project.
sfdx auth:web:login -a CaseFlowSourceOrg -s
Now that we’re authorized, we’re good to go! Our next step is retrieving the pieces of metadata we want to deploy. Our source org has a lot of metadata other than the flow we wish to retrieve, so we must ensure our command only retrieves what we want. We can do this using the -m parameter, which accepts a comma separated list of metadata types. In this case, we’ve specified the flow by developer name and a custom field on the case object, which is required for the flow to work.
sfdx force:source:retrieve -m Flow:Case_Creation_Flow,CustomField:Case.Is_Internal__c
Great! Now we have our metadata in our project, the next step is to authorize our target org and deploy the metadata. We can use the same command we used to authorize our source org, but with a different alias. We can also chain that command with another to immediately deploy our source afterwards – this is done via the semicolon (;) which means it will run the second command after the first one has finished (but not only on success!).
The second part of this command is the deploy command, which has a parameter of -p. This parameter tells it to deploy all the source files in a specific directory, and since we’re using a standard SFDX project, it all resides within the force-app folder.
sfdx auth:web:login -a CaseFlowSourceOrg -s; sfdx force:source:deploy -p force-app
Once we’ve authorized our org, the second command will immediately execute – within moments, we’ve deployed our flow from one environment to a completely separate environment without having to use changesets or any third-party tools. This can be great for finding reusable or flexible solutions and deploying them into different environments, essentially kickstarting a project and increasing confidence in the work.
2. Import and Export Data
In this scenario, we have a UAT environment running on a partial copy sandbox. We’ve built a great set of test accounts and contacts that we wish to move from our partial copy into several new development sandboxes. However, as the sandbox types don’t match, we can’t just create a new sandbox using the UAT environment as our source.
We could export the data out and import it to our development sandboxes, but then we either need to work with external Ids or do VLOOKUPS (or similar) within Excel every time – not fun and not scalable! Instead we’re going to use the Salesforce CLI to make things super speedy (and scalable!).
For the following commands, we’re going to skip the authentication and project setup. Instead, we’ll assume we are authenticated and have a fresh SFDX project (which is our terminal’s working directory).
Firstly, we want to extract the data from our UAT environment – we can use the force:data:tree:export command to do this. This command expects several parameters:
- -q: Either an inline SOQL query (in double quotes, to account for the spaces), or a file path pointing to a query file.
- -p: This tells the command to generate a query plan for a multi-level query (in our case account and contacts), and to save it to a file.
- -d: A file path prefix if we wish to store the output in a specific folder (e.g. “queries”).
With these parameters in place, we can write our command.
sfdx force:data:tree:export -q "SELECT Name, (SELECT FirstName, LastName FROM Contacts) FROM Account" -p -d queries
Once the query has completed, three new JSON files will have been created:
- Accounts.json: The exported accounts
- Contacts.json: The exported contacts
- Account-Contact-plan.json: Our query plan, containing the details the CLI will need to import our records
Now we have our query plan and data, we can switch our org to our target sandbox and import it using the force:data:tree:import command. For this command, we will only need to use a single parameter, -p which should be the file path to the query plan we exported.
sfdx force:data:tree:import -p queries/Account-Contact-plan.json
Running this command will first import our accounts and keep track of their imported Ids. It will then import the contacts, and by using the stored references, will automatically reestablish the relationships. Very cool!
3. Sandbox Creation
Following on from the previous scenario, we have only populated a single sandbox, when in fact we want several. Logging into our production environment and creating half a dozen sandboxes seems like such a tedious task now that we’ve unlocked the power of the CLI. Instead, we’re going to get the CLI to create them for us while we make a well-deserved cup of tea for our efforts!
The CLI contains the force:org:create command which is usually used to create scratch orgs, but we can also use it to create sandboxes for us. For this, we need to use many parameters (lots of which could be stored in a definition file if we want to store our config), which are mostly defined as key value pairs within our command.
- -t: The type of org to be created (in this instance, we specify “sandbox”)
- sandboxName: The name of the sandbox
- licenseType: The type of sandbox to create
- -a: Our ‘friendly’ name for this org
- -w: How long the command should wait before exiting (but not canceling) in minutes, up to 120 minutes
We can use the following command (and potentially run it several times at once in different terminals) to generate our sandbox.
sfdx force:org:create -t sandbox sandboxName=Dev1 licenseType=Developer -a “Dev 1 Sandbox” -w 120
This will create the sandbox, and report its creation status for a full 120 minutes (or until it’s created). We could potentially even chain this command with our data deployment example from earlier to super streamline the process.
The examples above are just a drop in the ocean when it comes to potential use cases for the Salesforce CLI. Part of its power is the ability to chain commands to automate tedious or time consuming processes.
Hopefully, now that the Salesforce CLI is no longer a magic box, you can think of ways to streamline your own processes. My favorite is the force:source:push command! Feel free to share your own encounters with the CLI in the comment section below.