Automating ZDK CLI commands using shell scripting

Automating ZDK CLI commands using shell scripting


Hello everyone,
Welcome back to Kaizen.  ZDK CLI's command-line nature allows you to easily incorporate it within a shell script, to achieve any custom action that you want to execute.  It allows you to execute multiple ZDK CLI commands seamlessly, enhancing productivity.

In this week's Kaizen post, we will discuss a shell script designed to automate the process of pushing locally modified metadata to our CRM environment. Before executing the push operation, ensure that the local metadata is up-to-date and conflicts (same file has been modified in both the local ZDK environment and the remote UI environment) are resolved. To achieve this, we will perform the following steps for files in conflict where manual intervention is required:
  • Retrieve the latest metadata from Zoho CRM to our local environment using zdk org:pull command
  • Address conflicts that may arise during the pull operation using zdk org:pull:resolve command 
  • Update our local directory with the newly pulled file using zdk org:pull:update command
  • Push changes from your local environment to the CRM using zdk org:push command
  • Update local directory and check status of push command using zdk org:push:result command
This script automates the sequential execution of these commands.

Prerequisites
  • ZDK CLI Version 1.0.2-beta
To update ZDK CLI, execute the following command in your terminal


  npm install -g @zohocrm/zdk-cli


This will initiate the installation process for the latest version.

Crafting the Shell Script

 
1.Create a new shell script file zdk_automation.sh in your ZDK project's root directory.
#!/bin/bash
touch stdout.txt
#This script is used to automate ZDK CLI conflict resolve flow
conflict_flag=false
# Clear stdout.txt at the start
> stdout.txt
#Step 1: Initial Push Command
echo "====Start of the script ====" >> stdout.txt
echo "**Executing the initial zdk org:push -j" >> stdout.txt
json_content=$(zdk org:push -j)
echo "Output  $json_content" >> stdout.txt
next_command=$(echo "$json_content" | jq -r '.next_command_sequence // empty')
echo "next_command after initial push  is $next_command">> stdout.txt
# Check if the JSON is valid
if echo "$json_content" | jq empty 2>/dev/null; then
#Step 2: Conflict Detection
    message=$(echo "$json_content" | jq -r '.message')
    echo "message: $message" >>stdout.txt
    if [[ "$message" == *"Merge Conflicts!"* ]]; then
        #Step 3: Resolving Conflicts
        conflict_flag=true
        # Pull changes to the local repository and store the output in a variable
        echo "**Executing zdk org:pull -j" >> stdout.txt
        json_content=$(zdk org:pull -j)
        echo "Output  $json_content" >> stdout.txt
        if echo "$json_content" | jq empty 2>/dev/null; then
            message=$(echo "$json_content" | jq -r '.result')
            echo "message $message" >>stdout.txt
            IFS=$'\n' read -r -d '' -a filenames <<< "$message"
            # Iterate over each filename and execute the resolve command
            for filename in "${filenames[@]}"; do
                echo "**Executing zdk org:pull:resolve for $filename" >> stdout.txt
                # Executing zdk org:pull:resolve 
                json_content=$(zdk org:pull:resolve -f "$filename" -j)
                echo "Output  $json_content" >> stdout.txt
            done
            echo "***Executing zdk org:pull:update" >> stdout.txt
            json_content=$(zdk org:pull:update -j)
            echo "Output  $json_content" >> stdout.txt
        fi
    fi
fi
#Step 4: Second Push Attempt after conflict
if [ "$conflict_flag" = true ]; then
# Push changes to the org and store the output in a variable again
echo "***Executing: zdk org:push -j after conflict resolution" >> stdout.txt
json_content=$(zdk org:push -j)
echo "Output  $json_content" >> stdout.txt
# Extract the line containing "next_command_sequence" from the push output
next_command=$(echo "$json_content" | jq -r '.next_command_sequence')
echo "Next command $next_command " >> stdout.txt
fi
#Step 5: Push result command
# Execute the next command if it exists
counter=0  # Initialize a counter
if [ -n "$next_command" ]; then
    while true; do
    # Execute the command stored in next_command and capture the output
    echo "***Executing: $next_command -j"  >> stdout.txt
    output=$(eval "$next_command -j")
    echo "Output $output" >>stdout.txt
    # Check if the output contains "Process in progress"
    if echo "$output" | grep -q "Process in progress"; then
        echo "Push process in progress. Waiting for 5 seconds..."  >> stdout.txt
        sleep 5  # Wait for 5 seconds
    else
        # If not found, break the loop and handle the output
        echo "Command executed successfully or completed."  >> stdout.txt
        break
    fi
     # Increment the counter
    counter=$((counter + 1))

    # Break the loop after 10 iterations
    if [ "$counter" -ge 10 ]; then
        echo "Maximum number of attempts(10) reached. Exiting the loop." >> stdout.txt
        echo "Try executing $next_command after some time" >> stdout.txt
        break
    fi
done
fi

Explanation of the script

Step 1: Initial Push Command
  • The script starts by executing the zdk org:push -j command. 
  • The commands executed using -j option ensures that the output is in a machine-readable JSON format, which facilitates easier parsing and processing.
  • The conflict_flag is set to false.
Step 2: Conflict Detection
  • The script checks the output for any merge conflicts. 
  • If conflicts are detected, it executes the zdk org:pull -j  command to retrieve the latest changes from the organization. The conflict_flag is set to true.
  • If conflicts are not present, the script proceeds to Step 5: Executing the push:result command.
Step 3: Resolving Conflicts
  • If conflicts are present, the script extracts a list of filenames associated with these conflicts. 
  • It iterates through this list and executes the zdk org:pull:resolve -j command for each filename, allowing for manual resolution of conflicts as needed. 
  • This opens a three-way editor in the browser where the conflicts can be resolved.
Step 4: Second Push Attempt after conflict
  • Once all conflicts are resolved, the script attempts to push any changes back to Zoho CRM by executing the zdk org:push -j command. 
Step 5: Executing push:result command 
  • This command should be followed by zdk org:push:result --jobid {id} command (indicated by a next_command_sequence) which displays the result of the push process with the mentioned job id and updates the local directory. 
  • During this process, if the result is shown as "Process in progress", a subsequent push:result command is required. In this case, the script waits for five seconds before trying again to ensure that operations complete successfully. 

2.Make the script executable
chmod +x zdk_automation.sh

3.Run your script
./zdk_automation.sh & tail -f stdout.txt

Logging ActionsAll actions taken by the script are logged in stdout.txt. This serves as a record for later reference and troubleshooting.







Using ZDK CLI with shell script ensures that your ZDK CLI operations are automated daily, minimizing manual intervention while effectively managing conflicts. 
Notes
For the current beta release, ZDK CLI is exclusively available for Sandbox environment and is not operational in Production environments. 

We hope you found this post useful. We will meet you next week with another interesting topic!
If you have any questions, let us know in the comment section.

Happy Exploring!


    Access your files securely from anywhere



                      Zoho Developer Community




                                              • Desk Community Learning Series


                                              • Digest


                                              • Functions


                                              • Meetups


                                              • Kbase


                                              • Resources


                                              • Glossary


                                              • Desk Marketplace


                                              • MVP Corner


                                              • Word of the Day


                                              • Ask the Experts





                                                        Manage your brands on social media



                                                              Zoho TeamInbox Resources



                                                                  Zoho CRM Plus Resources

                                                                    Zoho Books Resources


                                                                      Zoho Subscriptions Resources

                                                                        Zoho Projects Resources


                                                                          Zoho Sprints Resources


                                                                            Qntrl Resources


                                                                              Zoho Creator Resources



                                                                                  Zoho CRM Resources

                                                                                  • CRM Community Learning Series

                                                                                    CRM Community Learning Series


                                                                                  • Kaizen

                                                                                    Kaizen

                                                                                  • Functions

                                                                                    Functions

                                                                                  • Meetups

                                                                                    Meetups

                                                                                  • Kbase

                                                                                    Kbase

                                                                                  • Resources

                                                                                    Resources

                                                                                  • Digest

                                                                                    Digest

                                                                                  • CRM Marketplace

                                                                                    CRM Marketplace

                                                                                  • MVP Corner

                                                                                    MVP Corner





                                                                                      Design. Discuss. Deliver.

                                                                                      Create visually engaging stories with Zoho Show.

                                                                                      Get Started Now


                                                                                        Zoho Show Resources


                                                                                          Zoho Writer Writer

                                                                                          Get Started. Write Away!

                                                                                          Writer is a powerful online word processor, designed for collaborative work.

                                                                                            Zoho CRM コンテンツ








                                                                                              Nederlandse Hulpbronnen


                                                                                                  ご検討中の方




                                                                                                        • Recent Topics

                                                                                                        • old invoices (Exchange rate)

                                                                                                          We have been facing an issue and searching for a solution for over a month. Issue: Previously, the exchange rate in Zoho Books and Zoho CRM was incorrect, and invoices were being recorded in Zoho CRM with the wrong exchange rate. After adjusting the exchange
                                                                                                        • How to download Renamed File that already updated to Zoho Creator.

                                                                                                          Hi members, I construct a button with report workflow. link = "https://creatorexport.zoho.com" + zoho.appuri + "report_link_name/File_upload/image-download/" + input.File_upload; openUrl(link,"new window"); This script able to download the file. But I
                                                                                                        • Email signature duplicate

                                                                                                          Hi, For a few weeks, opening the email writer would show an error. After clicking ok, the signature would change slighty (font size, I believe). After that it worked fine, so we thought nothing of it. However, now it no longer shows the error puts the
                                                                                                        • Set a global default filter to All Candidates view

                                                                                                          Hi, Is it possible to set a global filter to the All Candidates view? As a use case would be for off-limit candidates. These are those who are off limits due to previous bad client feedback on performance/behaviour. Ideal use case would be to set these
                                                                                                        • Highlight a candidate who is "off limits"

                                                                                                          Hello: Is there a way to highlight a candidate who is "off limits"?  I would like to have the ability to make certain candidate and / or Client records highlighted in RED or something like that.   This would be used for example when we may have placed a candidate somewhere and we want everyone in our company to quickly and easily see that they are off limits.  The same would apply when we want to put a client or former client off limits so no one recruits out of there. How can this be done? Cheers,
                                                                                                        • Merge Join PDFs Zoho Creator

                                                                                                          Hi all, I have a field where users upload PDF, is it possible to join those pdfs into one with a function or something? Regards.
                                                                                                        • Custom Sign-in and Sign-out

                                                                                                          I've had a number of users ask me "how do I sign-out" when the sign-out link is clearly on the upper right of the page. To make it more obvious, you can use this bit of code to make a sign-out button on the top of any HTML view. You can customize the serviceurl as needed. <a class="zc-formbutton" style="padding: 5px;font-size:12px;" href="https://accounts.zoho.com/logout?serviceurl=https://creator.zoho.com/<%=zoho.adminuser%>/<%=zoho.appname%>/">Sign-Out</a> And since we're on this topic, you can
                                                                                                        • Tip 26: How to hide the "Submit" button from a form

                                                                                                          Hi everyone, Hope you're staying safe and working from home. We are, too. By now, we at Zoho are all very much accustomed to the new normal—working remotely. Today, we're back with yet another simple but interesting tip--how to hide the Submit button from your forms. In certain scenarios, you may want to hide the submit button from a form until all the fields are filled in.  Use case In this tip, we'll show you how to hide the Submit button while the user is entering data into the form, and then
                                                                                                        • Disappearing Mouse cursor in Zoho Mail / Windows 11 (Chrome + Edge)

                                                                                                          I'm seeing an issue when writing mails with the light theme with the mouse cursor being white and the document area also being white - making it nearly impossible to see the mouse cursor. I see the problem on Windows 11 under Chrome and Edge. (Yet to
                                                                                                        • Introducing Dark Mode / Light Mode : A New Look For Your CRM

                                                                                                          Hello Users, We are excited to announce a highly anticipated feature - the launch of Day, Night and Auto Mode implementation in Zoho CRM's NextGen user interface! This feature is designed to provide a visually appealing and comfortable experience for
                                                                                                        • People 5.0 widget and API questions

                                                                                                          While creating Widget for People 5 I found couple issues that I can’t find answer on my own: 1) How to get leave requests according to this API https://www.zoho.com/people/api/get-records-v2.html. I tried: requestData = { "url": "https://people.zoho.eu/api/v2/leavetracker/leaves/records",
                                                                                                        • Enhancements for Creator in Mobile Browsers and PWAs

                                                                                                          ZC Team, Lady & Gentlemen! This enhancement has been awaited for a thousand years, and it has made my day! It now appears more "enterprise" and no longer a jerk.
                                                                                                        • Zoho CRM Functions 53: Automatically name your Deals during lead conversion.

                                                                                                          Welcome back everyone! Last week's function was about automatically updating the recent Event date in the Accounts module. This week, it's going to be about automatically giving a custom Deal name whenever a lead is converted. Business scenario Deals are the most important records in CRM. After successful prospecting, the sales cycle is followed by deal creation, follow-up, and its subsequent closure. Being a critical function of your sales cycle, it's good to follow certain best practices. One such
                                                                                                        • Perfomance Management - Zoho People

                                                                                                          Hi team, I am looking for performance management data such as KRA, goals, feedback, appraisals, etc., in Zoho Analytics. However, I am unable to find these metrics while editing the setup. Could you please confirm whether these fields are available in
                                                                                                        • Client Script - Updating Field Value in Detail Page of a Lead

                                                                                                          Hello, I'm trying to use Client Script To enrich some data of the Lead when one of my User fill the "City" field in the detail page of the Lead. This is my Script: log (value); var response = ZDK.Apps.CRM.Functions.execute("getInfoCitta", { "nomeCitta":
                                                                                                        • Sales Returns - Repairand Return

                                                                                                          Hi Inventory Team, I'm working with a client on an Inventory implementation project and they have shared this use case with me. Some items may be returned by the customer, then returned to the vendor for repairs, received from the vendor and shipped back
                                                                                                        • Zoho One and Zoho Learn

                                                                                                          Is Zoho Learn going to become part of Zoho One? If not, why not? Also, if not, what is the closest product offered in the One bundle which is comparable to Zoho Learn? Please help me understand the overall relationship between Zoho Learn and Zoho One.
                                                                                                        • Creating task at someones date of birth

                                                                                                          Hi, I want to create a workflow which creates a task at someones date of birth. How can I do this?
                                                                                                        • Client scripts for Zoho Books ?

                                                                                                          Good day everyone, I am looking for a way to be able to interact with the Quotes and Invoices as they are being created. Think of it like Zoho client script in Zoho CRM. But for the life of me I dont see a way to do this. The issue with having function
                                                                                                        • Hourly Permission not getting Calculated

                                                                                                          That is our settings The total calculation should be from 9:37 AM to 3:37 PM, but the hourly permission isn't getting calculated The last entry is hourly permission, it's not
                                                                                                        • Zoho Flow Doesn't Detect Desk Ticket Custom Field Change

                                                                                                          I have a Flow that is configured to be triggered when a custom field on a ticket changes. I also have a Schedule in Desk that runs a script that changes the custom field. When I change the custom field manually in the Desk interface, the Flow runs as
                                                                                                        • Desk Contact Name > split to First and Last name

                                                                                                          I am new to Zoho and while setting up the Desk and Help Center, I saw that new tickets created or submitted from the Help Center used the Contact Name field. This would create a new Contact but put the person's name in the Last Name field only. The First
                                                                                                        • Display name in Zoho Desk Ticketing system

                                                                                                          We are in the trial phase to implement a Ticketing system. As our company uses several generic emails, such as service@abc.com and service@xyz.com across different branches, the uniqueness of usernames (full names) becomes crucial for our business. Without
                                                                                                        • 請求書に添付されているファイルをAPI経由で取得する際の問題について

                                                                                                          Books APIリファレンス 現在、Books APIを利用して請求書内の添付ファイルを取得するメソッドを構築しています。以下のコードを参考にしているのですが、添付ファイルが複数アップロードされている場合、responseにおいて2つ目のファイルの情報しか取得できない現象が発生しています。 headers_data = Map(); headers_data.put("Authorization", "Zoho-oauthtoken 1000.41d9xxxxxxxxxxxxxxxxxxxxxxxxc2d1.8fccxxxxxxxxxxxxxxxxxxxxxxxx125f");
                                                                                                        • Feature request - pin or flag note

                                                                                                          Hi, It would be great if you could either pin or flag one or more notes so that they remain visible when there are a bunch of notes and some get hidden in the list. Sometimes you are looking for a particular name that gets lost in a bunch of less important
                                                                                                        • Differentiating between invoice templates when adding custom fields

                                                                                                          We are adding HS codes to the items which we would like published on our international customers invoices plus other export data required. We don't need this data on our domestic customer invoices. We have setup an invoice template for them but it if
                                                                                                        • LMS icon missing in zoho people account

                                                                                                          How to create zoho people LMS. I tried to find the LMS icon in zoho people. But I didn't  find that icon. Kindly give solution. how to start LMS in zoho people account?
                                                                                                        • Have an input card for zobot that could collect Name, Email, and Phone or a message all at once

                                                                                                          It would be great to have an input card for the codeless bot in a form style that allows it to ask all relevant questions at once. at any point in the chat flow or conversation, This approach would simplify the interaction, making it easier and more straightforward
                                                                                                        • CRM Quotes- Delete tasks when status is changed

                                                                                                          Hello. We have our quotes setup for approval process. We would like however to delete the tasks that are made when a different quote stage is selected. So when a quote stage is setup for "sent for review" we have the automation process to send out an
                                                                                                        • Power of Automation::Streamline Associated Teams during Blueprint transition.

                                                                                                          Hello Everyone, A Custom Function is a user-written set of code to achieve a specific requirement. Set the required conditions needed as to when to trigger using the Workflow rules (be it Tasks / Project) and associate the custom function to it. Requirement:-
                                                                                                        • web page becomes flickering after being made into WebTab

                                                                                                          I create a webtab in Zoho CRM like this it uses this URL below: https://blueraycargo.id/kalkulator-berat-volume/ as you can see, if you open the bare URL then it will have no problem, but after it becomes a WebTab then it is flickering constatly. what
                                                                                                        • NOW Zoho Creator still cannot bulk download Image or File Upload Field

                                                                                                          The filedownloader has been deprecated for 5 years. Until now, we still cannot have a replacement tool. How can we bulk download the file that we uploaded to Zoho Creator. Previously, it was so simple to bulk download all those files. But now failed to
                                                                                                        • Transferring Attachments from Lead to Account

                                                                                                          Hi All, I'm trying to create a function that will transfer attachments in leads to the newly created account. I know there's an option to choose where the attachments go when you click the standard convert button but we have a high volume of conversions
                                                                                                        • Product/Quotes with a Setup AND a Recurring (monthly) Fee.

                                                                                                          Good day. We sell software in different modules. These modules have a Setup Fee AND a Monthly fee. It is possible to add a Custom Field to a product with the Monthly Fee (next to the Setup Fee or Unit Price), but it's not possible to make this visible in the Quotes Module. What we need, which is essential for SAAS business with a subscriptions and a setup model: - We want to add products to our quotes with two prices (setup AND month fee) - These should be visible and editable in the product details
                                                                                                        • How to save email as PDF?

                                                                                                          I saw 2 previous threads about this. One is from 14 years ago. The other was closed as "answered" a year ago but the feature was never implemented: https://help.zoho.com/portal/en/community/topic/how-to-download-save-emails-as-pdf Is the "save as PDF"
                                                                                                        • how to have incline alert on subrow's column or subform or other workaround that at least can let the user know this subform currently has some validation checking.

                                                                                                          I have a subform and each row that are some columns that are compulsory to fill up. If user did not fill up, how to show incline alert on those columns or incline alert on the subform. Or any workaround that at least can bring the user to that fields
                                                                                                        • The ability to show fields from subforms when viewing from related list

                                                                                                          Hi there, Currently im only able to display default columns , however when im unable to add the columns/fields from the subform Ive created. below is a field called quantity from the subform. Im not able to search up this field from the manage column
                                                                                                        • Tip 31: How to make a field in a Zoho Creator form mandatory based on criteria

                                                                                                          Hi folks,   I'm sure most of you are familiar with the Mandatory property available in our form builder. It enables you to ensure that your users enter an input in a required field. If they don't enter an input in that field, they'll be unable to submit
                                                                                                        • Create a new module with first name & last name, and join the two when viewing records

                                                                                                          I've created a new module, and I have first name / last name fields (I've renamed the record name field as last name). When I'm viewing a record, I'd like to see "Bob Smith" at the top of the page and in lists, not just "Smith" as I have today - basically the same experience you get when editing / viewing leads in the leads module.
                                                                                                        • Time Entry warning

                                                                                                          Is it possible to configure a warning/alert when a ticket exceeds a set amount of Time?
                                                                                                        • Next Page