このページは、お客様の言語ではご利用いただけません。Huawei Cloudは、より多くの言語バージョンを追加するために懸命に取り組んでいます。ご協力ありがとうございました。

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

deploy.sh Description

Updated on 2025-01-17 GMT+08:00

Scenarios

  • Scenario 1: If a software package is generated using Jenkins, for example, a JAR package, use the software package deployment scenario in the script. During deployment, the built software package is uploaded to the OBS bucket and the CAE component is upgraded using the new JAR package.
  • Scenario 2: If an image is generated using Jenkins, use the image deployment scenario in the script. During deployment, the built image is uploaded to the SWR image repository and the CAE component is upgraded using the new image.

Script Content

#!/bin/bash

#------------Mandatory parameters------------------
# Region name
region=''
# Project ID
project_id=''
# Environment name
environment_name=''
# Application name
application_name=''
# Component name
component_name=''
# Deployment type. 1. software; 2. image.
deploy_type=''

#------------Mandatory parameters in the software package deployment scenario---------------
# Absolute path of the executable file for installing obsutil
obsutil=''
# Name of the OBS bucket that stores the software package
bucket_name=''
# Directory for storing the software package in the OBS bucket. The default directory is the root directory. The directory must end with a slash (/). If the directory does not exist in the OBS bucket, it will be automatically created.
bucket_dir='/'

#------------Mandatory parameters in the image deployment scenario------------------
# SWR organization name
swr_organization=''
# AK, which is used to log in to the SWR image repository
AK=''
# SWR login secret, which is used to log in to the SWR image repository.
login_secret=''

#------------External input parameters, which do not need to be set. For details, see the pipeline script parameter build_target_name in the pipeline build task------------------
# Software package deployment scenario: name of the built software package, which is transferred from the external build_target_name parameter.
software_package=''
# Image deployment scenario: image generated after build: image name:version name, which is transferred from the external build_target_name parameter.
machine_image_name=''

# Either the software package name or image name must be input.
# If the parameter count is 1, set the software package name or image name.
if [ $# == 1 ]; then
    if [[ "$deploy_type" == "software" ]]; then
        software_package=$1
    elif [[ "$deploy_type" == "image" ]]; then
        machine_image_name=$1
    fi
else
    echo "The number of external input parameters is not 1. Configure the pipeline script parameter build_target_name in the pipeline build task."
fi

# ----------------Retain the settings of the following code-------------------
enterprise_project_id='0'
environment_id=''
application_id=''
component_id=''

function splitVersion() {
    str=$1
    right=${str##*.}
    left=${str%.*}
    if [ ${#str} -eq ${#left} ]; then
        left=""
    fi
}

function addVersion() {
    v1=$1
    res=`echo $v1|awk '{print int($0)}'`
    if [ $res -gt 9998 ]; then
        res=0
    else
        res=$(($res+1))
    fi
}

# Upgrade the version number.
# The version number format is A.B.C or A.B.C.D. A, B, C, and D are integers, and each integer cannot be greater than 9999.
# Example: 1.0.0 -> 1.0.1; 1.0.9999 -> 1.1.0
function upgradeVersion() {
    left=$1
    start=0
    end=''
    res=0
    while ( [[ $res = 0 ]] && [ $start -lt 4 ] )
    do
        start=$(($start+1))
        splitVersion $left
        addVersion $right
        if [ $start -gt 1 ]; then
            end=`echo "$res.$end"`
        else
            end=`echo "$res$end"`
        fi
    done
    if [ ${#left} -ne 0 ]; then
        version="$left.$end"
    else
        version="$end"
    fi
}

# Obtain the version number of the component to be upgraded.
function upgradeComponentVersion() {
    #Query component information.
    component_detials=`/usr/local/bin/hcloud CAE ShowComponent --cli-region="$region" --project_id="$project_id" --X-Enterprise-Project-ID="$enterprise_project_id" --X-Environment-ID="$environment_id" --application_id="$application_id" --component_id="$component_id"`

    # Obtain the current version number of the component.
    version=`getJsonValuesByAwk  "$component_detials" "version" "defaultValue"`
    version=`echo "$version"  | cut -d  '"' -f  2`
    echo "current version: $version"
    if [[ "$version" == "defaultValue" ]]; then
        echo "get component detials and get component version error"
        echo "$component_detials"
        exit 126
    fi
    upgradeVersion $version
    echo "upgrade version: $version"
}

# JAR package deployment scenario
function obs_software_upgrade() {
    echo "upload jar to obs"
    # OBS address to which the software package is uploaded. The format is obs://{Bucket name}{Directory for storing the JAR package in the OBS bucket}.
    bucket_address="obs://$bucket_name$bucket_dir"
    # Link of the JAR package uploaded to OBS. The format is https://{Bucket name}.obs.{region}.myhuaweicloud.com/{Directory for storing the JAR package in the OBS bucket}/
    obs_jar_url="https://$bucket_name.obs.$region.myhuaweicloud.com$bucket_dir$software_package"
    echo "software_package url: $obs_jar_url"
    #Upload the JAR package generated in the project to OBS.
    obs_result=`"$obsutil" cp ./target/*.jar "$bucket_address"`
    if [ $? -ne 0 ]; then
        echo "obsutil upload software package error"
        echo "$obs_result"
        exit 126
    fi
    #Print the upload result.
    echo "$obs_result"
    
    # Upgrade the component.
    echo "upgrade component"
    action_result=`/usr/local/bin/hcloud CAE ExecuteAction --cli-region="$region" --project_id="$project_id" --X-Enterprise-Project-ID="$enterprise_project_id" --X-Environment-ID="$environment_id" --application_id="$application_id" --component_id="$component_id" --api_version='v1' --kind='Action' --metadata.name='upgrade' --metadata.annotations.version="$version" --spec.source.type='softwarePackage' --spec.source.sub_type='BinObs' --spec.source.url="$obs_jar_url"`
}

# Generate a string in the second-level time format, which is used to add the time format suffix to the version when the SWR image is uploaded.
function generateTimeFormatString() {
    ms=$(date +%s)
    time=$(date -d @$ms "+%Y%m%d%H%M%S")
    echo $time
}

# Image deployment scenario
function swr_image_upgrade() {

    # Path of the SWR image repository to which the image is uploaded. The format is [Image repository address]/[Organization name]/[Image name:Version name].
    swr_image_url="swr.$region.myhuaweicloud.com/$swr_organization/$machine_image_name"
    #SWR image repository address
    swr_url="swr.$region.myhuaweicloud.com"

    # SWR image version and time format string
    time_format_string=`generateTimeFormatString`
    swr_image_url="$swr_image_url.$time_format_string"

    echo "upload image to swr"
    docker tag "$machine_image_name" "$swr_image_url"
    login_result=`docker login -u "$region"@"$AK" -p "$login_secret" "$swr_url"`
    # Print the result of logging in to the SWR image repository.
    #echo "$login_result"
    push_result=`docker push "$swr_image_url"`
    if [ $? -ne 0 ]; then
        echo "docker push error"
        echo "$push_result"
        exit 126
    fi
    #Print the image push result.
    #echo "$push_result"
    logout_result=`docker logout "$swr_url"`
    #Print the result of logging out of the SWR image repository.
    #echo "$logout_result"
    #Clear all historical records. They may contain SWR login secret information.
    #history -c
    echo "upgrade component"
    # Upgrade the image component.
    action_result=`/usr/local/bin/hcloud CAE ExecuteAction --cli-region="$region" --project_id="$project_id" --X-Enterprise-Project-ID="$enterprise_project_id" --X-Environment-ID="$environment_id" --application_id="$application_id" --component_id="$component_id" --api_version='v1' --kind='Action' --metadata.name='upgrade' --metadata.annotations.version="$version" --spec.source.type='image' --spec.source.url="$swr_image_url" `
}

### Description:
### 1. Search for a string: key with double quotation marks. If no value is found, defaultValue is returned.
### 2. Search for the nearest colon (:). The content following the colon is the value.
### 3. If there are multiple keys with the same name, only the first value is printed.
### 4. params: json, key, defaultValue
function getJsonValuesByAwk() {
    awk -v json="$1" -v key="$2" -v defaultValue="$3" 'BEGIN{
        foundKeyCount = 0
        pos = match(json, "\""key"\"[ \\t]*?:[ \\t]*");
        if (pos == 0) {if (foundKeyCount == 0) {print defaultValue;} exit 0;}
        ++foundKeyCount;
        start = 0; stop = 0; layer = 0;
        for (i = pos + length(key) + 1; i <= length(json); ++i) {
            lastChar = substr(json, i - 1, 1)
            currChar = substr(json, i, 1)
            if (start <= 0) {
                if (lastChar == ":") {
                    start = currChar == " " ? i + 1: i;
                    if (currChar == "{" || currChar == "[") {
                        layer = 1;
                    }
                }
            } else {
                if (currChar == "{" || currChar == "[") {
                    ++layer;
                }
                if (currChar == "}" || currChar == "]") {
                    --layer;
                }
                if ((currChar == "," || currChar == "}" || currChar == "]") && layer <= 0) {
                    stop = currChar == "," ? i : i + 1 + layer;
                    break;
                }
            }
        }
        if (start <= 0 || stop <= 0 || start > length(json) || stop > length(json) || start >= stop) {
            if (foundKeyCount == 0) {print defaultValue;} exit 0;
        } else {
            print substr(json, start, stop-start);
        }
    }'
}

### Description:
### Find tagKey when key equals to value from the result returned by the list.
### Search for the JSON string '"key":"value"'. After the string is found, end it with this position.
### Search for lastIndex, and then search for tagKey with lastIndex as the start point to obtain the value of tagKey.
### 
### params: json, key, value, tagKey, defaultValue
function getJsonValuesByAwkWithConditions() {
    awk -v json="$1" -v key="$2" -v value="$3" -v tagKey="$4" -v defaultValue="$5" 'BEGIN{
        foundKeyCount = 0
        pos = match(json, "\""key"\"[ \\t]*?:[ \\t]*\""value"\"");
        if (pos == 0) {print defaultValue; exit 0;}
        str1 = substr(json, 0, pos)
        lastIndex = 0
        while (match(str1, "{")) {
            lastIndex = lastIndex + RSTART
            str1 = substr(str1, RSTART + RLENGTH)
        }
        if (lastIndex == 0) {print defaultValue; exit 0;}
        newStr = substr(json, lastIndex)
        pos1 = match(newStr, "\""tagKey"\"[ \\t]*?:[ \\t]*");
        if (pos1 == 0) {print defaultValue; exit 0;}
        ++foundKeyCount;
        start = 0; stop = 0; layer = 0;
        for (i = pos1 + length(tagKey) + 1; i <= length(newStr); ++i) {
            lastChar = substr(newStr, i - 1, 1)
            currChar = substr(newStr, i, 1)
            if (start <= 0) {
                if (lastChar == ":") {
                    start = currChar == " " ? i + 1: i;
                    if (currChar == "{" || currChar == "[") {
                        layer = 1;
                    }
                }
            } else {
                if (currChar == "{" || currChar == "[") {
                    ++layer;
                }
                if (currChar == "}" || currChar == "]") {
                    --layer;
                }
                if ((currChar == "," || currChar == "}" || currChar == "]") && layer <= 0) {
                    stop = currChar == "," ? i : i + 1 + layer;
                    break;
                }
            }
        }
        if (start <= 0 || stop <= 0 || start > length(newStr) || stop > length(newStr) || start >= stop) {
            if (foundKeyCount == 0) {print defaultValue;} exit 0;
        } else {
            print substr(newStr, start, stop-start);
        }
    }'
}

# Obtain enterprise_project_id, environment_id, application_id, and component_id.
function initParpare() {
    # Obtain environment_id.
    listEnvsResult=`/usr/local/bin/hcloud CAE ListEnvironments --cli-region="$region" --project_id="$project_id"`
    environment_id=`getJsonValuesByAwkWithConditions  "$listEnvsResult" "name" "$environment_name" "id" "defaultValue"`
    environment_id=`echo "$environment_id"  | cut -d  '"' -f  2`
    echo "environment_id: $environment_id"
    if [[ "$environment_id" == "defaultValue" ]]; then
        echo "list environments and get environment_id error"
        echo "$listEnvsResult"
        exit 126
    fi

    # Obtain enterprise_project_id.
    enterprise_project_id=`getJsonValuesByAwk  "$listEnvsResult" "enterprise_project_id" "defaultValue"`
    enterprise_project_id=`echo "$enterprise_project_id"  | cut -d  '"' -f  2`
    echo "enterprise_project_id: $enterprise_project_id"
    if [[ "$enterprise_project_id" == "defaultValue" ]]; then
        echo "get enterprise_project_id error"
        echo "$listEnvsResult"
        exit 126
    fi

    # Obtain application_id.
    listAppsResult=`/usr/local/bin/hcloud CAE ListApplications  --cli-region="$region" --project_id="$project_id" --X-Environment-ID="$environment_id"`
    application_id=`getJsonValuesByAwkWithConditions  "$listAppsResult" "name" "$application_name" "id" "defaultValue"`
    application_id=`echo "$application_id"  | cut -d  '"' -f  2`
    echo "application_id: $application_id"
    if [[ "$application_id" == "defaultValue" ]]; then
        echo "list applications and get application_id error"
        echo "$listAppsResult"
        exit 126
    fi

    # Obtain component_id.
    listComponentsResult=`/usr/local/bin/hcloud CAE ListComponents  --cli-region="$region" --project_id="$project_id" --X-Environment-ID="$environment_id" --application_id="$application_id"`
    component_id=`getJsonValuesByAwkWithConditions  "$listComponentsResult" "name" "$component_name" "id" "defaultValue"`
    component_id=`echo "$component_id"  | cut -d  '"' -f  2`
    echo "component_id: $component_id"
    if [[ "$component_id" == "defaultValue" ]]; then
        echo "list components and get component_id error"
        echo "$listComponentsResult"
        exit 126
    fi
}

# Query the job status every 15 seconds until the job is complete.
function waitDeployFinish() {
    sleep 10s
    id="$1"
    leni=${#id}
    id=${id:1:leni-2}
    echo "job_id= $id"
    job_status=""
    while [[ "$job_status" != "success" ]]; do
        job_status_result=`/usr/local/bin/hcloud CAE ShowJob --cli-region="$region" --project_id="$project_id" --job_id="$id" --X-Environment-ID="$environment_id"`
        job_status=`getJsonValuesByAwk  "$job_status_result" "status" "defaultValue"`
        if [[ "$job_status" == "defaultValue" ]]; then
            echo "ShowJob failed"
            echo "$job_status_result"
            return
        fi
        job_status=`echo "$job_status"  | cut -d  '"' -f  2`
        if [[ "$job_status" != "running" && "$job_status" != "success" ]]; then
            echo 'upgrade failed'
            echo "$job_status_result"
            return
        fi
        sleep 15s
    done
    echo 'upgrade success'
}

function deploy() {
    if [[ "$deploy_type" == "software" ]]; then
        obs_software_upgrade
    elif [[ "$deploy_type" == "image" ]]; then
        swr_image_upgrade
    else
        return
    fi
    
    # Print the component upgrade result.
    echo "upgrade result: $action_result"
    # Obtain the job_id in the result.
    job_id=`getJsonValuesByAwk  "$action_result" "job_id" "defaultValue"`
    if [[ "$job_id" == "defaultValue" ]]; then
        echo "upgrade failed"
        exit 126
    fi
    # Wait until the upgrade is complete.
    waitDeployFinish "$job_id"
}

function main() {
    initParpare
    upgradeComponentVersion
    deploy
}
main

Script Parameters

Table 1 Script parameters

Parameter

Mandatory

Type

Description

region

Yes

String

Project name.

project_id

Yes

String

Project ID.

environment_name

Yes

String

Environment name of a component.

application_name

Yes

String

Application name of a component.

component_name

Yes

String

Component name.

deploy_type

Yes

String

Deployment type.

  • software
  • image

obsutil

No

String

This parameter is mandatory when a software package, such as a JAR package, is used for deployment. Absolute installation path of the OBS tool to which the JAR package is uploaded.

Example: /root/tools/obsutil/obsutil_linux_amd64_5.4.6/obsutil

bucket_name

No

String

This parameter is mandatory when software packages are used for deployment. Name of the OBS bucket that stores the software package.

bucket_dir

No

String

This parameter is mandatory when software packages are used for deployment.

Directory for storing the software package in the OBS bucket. The default directory is the root directory. The directory must end with a slash (/). If the directory does not exist in the OBS bucket, it will be automatically created. For example, the root directory is /, and the test directory in the root directory is /test/.

swr_organization

No

String

This parameter is mandatory when images are used for deployment. Name of the SWR organization to which the image is uploaded.

AK

No

String

This parameter is mandatory when images are used for deployment. Used to log in to the SWR image repository.

login_secret

No

String

This parameter is mandatory when images are used for deployment. SWR login secret, which is used to log in to the SWR image repository. Run the following command using the created AK and SK. The returned result is the login secret.

printf "$AK" | openssl dgst -binary -sha256 -hmac "$SK" | od -An -vtx1 | sed 's/[ \n]//g' | sed 'N;s/\n//'

Obtaining Values

  • Obtain region and project_id.
    Log in to CAE, click the personal account in the upper right corner, and click My Credentials to view the project name and ID of the region.
    Figure 1 My Credentials
    Figure 2 Projects
  • Obtain environment_name, application_name, and component_name.

    Log in to CAE, click Components, and find the target component, for example, image, as shown in Figure 3.

    Figure 3 Viewing component information

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback