Cloudinary Blog

Commanding Cloudinary Through the CLI

By
Using the Cloudinary CLI (Command Line Interface)

“Anything you can do, I can do better,
I can do anything better than you…”
(Irving Berlin)

If the Cloudinary CLI could sing, this could well be its song. Virtually anything you can do with the Cloudinary upload and admin APIs, you can do with the CLI (Command Line Interface), and much of the functionality that’s available through your account console is also accessible through the CLI. As to being ‘better’, it probably depends on the context, but in many situations it’s certainly quicker and easier, and it provides some bonus functionality that isn’t available through the APIs or console.

Initiation

All you need to get started with the Cloudinary CLI is your own Cloudinary account (sign up for free if you don’t have one) and Python 3.6 or later. You can install the Cloudinary CLI using the Python Package installer (PIP), as follows:

Copy to clipboard
pip3 install cloudinary-cli

To make all your cld commands point to your Cloudinary account, set up your CLOUDINARY_URL environment variable. For example, to set a temporary environment variable:

  • On Mac or Linux:

    Copy to clipboard
    export CLOUDINARY_URL=cloudinary://123456789012345:abcdefghijklmnopqrstuvwxyzA@cloud_name

  • On Windows:

    Copy to clipboard
    set CLOUDINARY_URL=cloudinary://123456789012345:abcdefghijklmnopqrstuvwxyzA@cloud_name

Tip
You can copy and paste your account environment variable from the Account Details section of the Dashboard page in the Cloudinary console.

You may prefer to set up a persistent environment variable so that you don't have to add it every time you open a new terminal, but be aware that you could put your API secret at risk if you're storing it in your shell's startup script.

Check your configuration by entering the following CLI command:

Copy to clipboard
cld config

Here's the type of response to expect:

Copy to clipboard
cloud_name:     <CLOUD_NAME>
api_key:        <API_KEY>
api_secret:     ***************<LAST_4_DIGITS>
private_cdn:    <True|False>

Before we jump into the fun stuff, take a look at this video to see how easy it is to get the CLI up and running, plus a few basic commands in action:

Now you know the basics, keep reading for some examples of what you can do with the CLI.

Uploading Assets

Let's start with an upload example. When uploading assets to Cloudinary there are many options that you can specify. To make uploading easier you can save a set of options in an upload preset. Want to know what upload presets you have configured in your account? No need to log in to your console, just enter:

Copy to clipboard
cld admin upload_presets

You'll get back a listing of all the account upload presets including the upload options defined for each one.

Can’t find one that meets your needs? No worries - just create a new one with cld admin create_upload_preset together with any of the upload parameters documented in the API reference:

Copy to clipboard
cld admin create_upload_preset name=new_preset use_filename=true unique_filename=false

Next, use the upload command to upload a single file using the upload preset (this example assumes you're running the command from the same folder as video.mp4, otherwise you'd need to specify the file path):

Copy to clipboard
cld uploader upload video.mp4 upload_preset=new_preset folder=cld_folder

Or, if you have a whole directory (folder) to upload, you can use the upload_dir command. This command is unique to the CLI - it's not part of the upload API - so has different syntax. Notice that the upload preset is specified with the -p option this time, and the Cloudinary folder with -f:

Copy to clipboard
cld upload_dir -f cld_folder -p new_preset local_folder

The following video shows some of these commands in action. A folder of images is uploaded to Cloudinary using an upload preset that removes the backgrounds of the images by activating the Cloudinary AI Background Removal add-on:


  • Here's the create_upload_preset command from the video:

    Copy to clipboard
    cld admin create_upload_preset name=remove_background overwrite=false use_filename=true unique_filename=false type=upload access_mode=public background_removal=cloudinary_ai

    The optional parameter, background_removal=cloudinary_ai, tells it to use the Cloudinary AI Background Removal add-on.

  • The details of the ‘remove_background’ upload preset are shown using the command:

    Copy to clipboard
    cld admin upload_preset remove_background

  • The upload_dir command is used to upload the ‘soft_toys’ folder together with its contents and sub-folder to the ‘new_toys’ folder in the Cloudinary account. Because the 'remove_background' upload preset is specified, the image backgrounds are removed on upload. Here's the command:

    Copy to clipboard
    cld upload_dir -f new_toys -p remove_background soft_toys

Another way to upload assets to your Cloudinary account is to migrate them from an external site using the migrate command. If this is something you're interested in, be sure to check out the migrate example in the docs.

Prompt Me!

The make command is very nifty if you want to embed one of Cloudinary’s front-end tools into your app. It returns template code for implementing one of Cloudinary's widgets or players. For example, you can get the HTML you need to embed the upload widget into your web page by entering:

Copy to clipboard
cld make upload_widget

Here’s the sample output:

Copy to clipboard
<button id="upload_widget" class="cloudinary-button">Upload files</button>

<script src="https://widget.cloudinary.com/v2.0/global/all.js" type="text/javascript"></script>  

<script type="text/javascript">  

    var myWidget = cloudinary.createUploadWidget({
        cloudName: 'cloud_name',
        upload_preset: 'preset1',
        }, (error, result) => { if (result.event == "success") {
            console.log(result.info) // result.info contains data from upload
        } })

        document.getElementById("upload_widget").addEventListener("click", function(){
            myWidget.open();
        }, false);

</script>

In Search of Answers

The search command can be incredibly useful for running queries on your assets. Want to know which assets have been rejected by one of our moderation services? Just enter:

Copy to clipboard
cld search -s public_id asc moderation_status=rejected

Or, perhaps you want to know which files are eating up your storage space…

Copy to clipboard
cld search -s public_id asc "bytes>10m"

The double quotes prevent the > character redirecting to a file called 10m!

Anything you can do with the Search API, you can do with the search command, so be sure to take a look at the expressions and fields that we support, if you're not already familiar with them.

Trying Out Transformations

Had your eye on a particular transformation but not set up a coding environment yet? If all you want to do is try out some transformation parameters, then you can of course enter a URL into a browser. But that means remembering the structure of the URL. If you know the public ID of your asset and which transformations you want to try, then the url command can be very handy. For example, say you have a picture of a bear (bear.jpg) in the top level of your Cloudinary account, and you want to try the cartoonify effect on it, enter the following command:

Copy to clipboard
cld url -o bear.jpg e_cartoonify

The URL is returned, and also opened in a browser because the -o option was given:

Copy to clipboard
http://res.cloudinary.com/demo/image/upload/e_cartoonify/bear.jpg

Cartoonified bear

Sign Here

Even if you have a great memory, and could rattle off a URL in a browser in no time, when it comes to signed URLs it’s not that easy. With the CLI it’s as simple as adding the -s option to the url command.

For example, you may want to try out the Cloudinary Object-Aware Cropping add-on, to crop your bear image keeping only the bear. The add-on requires the URL to be signed by default, so this command does the job:

Copy to clipboard
cld url -o -s bear.jpg w_300,g_bear,c_thumb

The returned URL includes the required signature (s--dbEUpIJT--):

Copy to clipboard
http://res.cloudinary.com/demo/image/upload/s--dbEUpIJT--/w_300,g_bear,c_thumb/bear.jpg

Cropped bear

Scripted Solutions

The beauty of working with any CLI is that you can call commands from a script, making repetitive or periodic tasks a breeze.

The multi method in the upload API can be used to create an animation from images that have the same tag. The following video shows how you can use a script to upload the same image multiple times with the same tag but different public IDs, adjusting the color saturation each time. The multi method is used at the end to create the animation.

Take a look:

Here’s the script that's used in the video (note that you'd need to specify the file path to umbrellas.jpg if you didn't run the script from the same folder):

Copy to clipboard
#!/bin/bash

inc=10

# Increase the color saturation by 10 for each image
for ((sat = -100; sat <= 100; sat += 10))
do
      trans="transformation='{\"effect\": \"saturation:$sat\"}'"

      echo $trans

      # Upload the image with the applied transformation
      eval cld uploader upload umbrellas.jpg public_id="umbrellas_$inc" folder="color" overwrite=true tags="umbrella" $trans

      ((inc++))
done

cld uploader multi umbrella delay=100

The last command in the script creates the animated GIF with a delay of 100 milliseconds between frames.

If you’re a fan of scripts, I’m sure you can think of plenty more uses for the CLI, perhaps within a Jenkins or cron job. For example, you could set up a cron job to run the sync command periodically to keep a Cloudinary folder in sync with a local folder, or vice versa (see the sync documentation for details). Or, you could automatically check your credit usage each day using cld admin usage to warn you if you’re approaching your limit.

Explode and Regenerate

Here’s an example of some more creative commands in action.

Image sprites incorporate multiple images into one and therefore reduce the number of server requests required to download the images, saving bandwidth and reducing page load times. The following video shows images being extracted from a PDF, then re-combined as an image sprite, so that they can be displayed on a website:

First, the PDF is uploaded to Cloudinary, with a public ID of ‘blue_signs’:

Copy to clipboard
cld uploader upload blue_signs.pdf public_id=blue_signs

The explode method is called to pre-generate images from each page of the PDF. Although not strictly necessary in this context, it does help to speed up the subsequent commands that need the derived images.

Copy to clipboard
cld uploader explode blue_signs page=all

The derived images are then uploaded to Cloudinary as new original images and assigned the same tag, blue_signs:

Copy to clipboard
cld uploader upload http://res.cloudinary.com/carl/image/upload/pg_1/blue_signs.png tags=blue_signs

cld uploader upload http://res.cloudinary.com/carl/image/upload/pg_2/blue_signs.png tags=blue_signs

cld uploader upload http://res.cloudinary.com/carl/image/upload/pg_3/blue_signs.png tags=blue_signs

You’ll see in the video that each of the new images has a random public ID, as no public IDs are specified on upload. This has implications when the sprite is generated as the images are added in alphabetical order, so if you want to keep them in a specific order, be sure to upload them with appropriate public IDs.

Finally, the generate_sprite method is used to create the image sprite along with the CSS required to use each of its images on a website. Notice that a transformation is applied to each of the images added to the sprite to crop them to a square:

Copy to clipboard
cld uploader generate_sprite blue_signs transformation=’{“width”: 200, “height”: 200, “crop”: “fill”, “gravity”: auto}’

You’re in Command

Of course, the CLI is no substitute for real SDK or REST API code when you’re creating your app or website, but it does add another dimension to the way you can interact with Cloudinary. In addition to giving you access to Cloudinary’s APIs outside of a formal coding environment, it can ease the administrative side of managing your Cloudinary account, provide some extra functionality and give you an efficient way to try out all the great features that Cloudinary has to offer.

For more information and examples, check out the Cloudinary CLI documentation.

Go on, give it a go! That’s a command!

Recent Blog Posts

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more