Help Center/ MapReduce Service/ API Reference/ API V1.1/ Auto Scaling APIs/ Configuring an Auto Scaling Rule - CreateAutoScalingPolicy
Updated on 2026-09-15 GMT+08:00

Configuring an Auto Scaling Rule - CreateAutoScalingPolicy

Function

This API is used to edit and configure the autoscaling rules of an MRS cluster, setting the trigger conditions and adjustment rules for autoscaling. Autoscaling rules can also be created simultaneously in the API for creating a cluster and executing a job. It can be used together with the API for viewing an autoscaling policy to verify the configuration result.

Constraints

None

Debugging

You can debug this API in API Explorer. Automatic authentication is supported. API Explorer can automatically generate sample SDK code and supports sample SDK code debugging.

Authorization Information

Each account has all the permissions required to call all APIs, but IAM users must be assigned the required permissions.

  • If you are using role/policy-based authorization, see Permissions Policies and Supported Actions for details on the required permissions.
  • If you are using identity policy-based authorization, no identity policy-based permissions are required for calling this API.

URI

POST /v1.1/{project_id}/autoscaling-policy/{cluster_id}
Table 1 URI parameters

Parameter

Mandatory

Type

Description

project_id

Yes

String

Definition

Project ID. For details about how to obtain the project ID, see Obtaining a Project ID.

Constraints

N/A

Range

The value must consist of 1 to 64 characters. Only letters and digits are allowed.

Default Value

N/A

cluster_id

Yes

String

Definition

Cluster ID. For details about how to obtain the cluster ID, see Obtaining the MRS Cluster Information.

Constraints

N/A

Range

The value can contain 1 to 64 characters, including only letters, digits, underscores (_), and hyphens (-).

Default Value

N/A

Request Parameters

Table 2 Request body parameters

Parameter

Mandatory

Type

Description

node_group

Yes

String

Definition

Type of the node to which an auto scaling rule applies. Currently, only task nodes support auto scaling rules.

Constraints

N/A

Range

  • task_node_default_group: Task node

Default Value

N/A

auto_scaling_policy

Yes

AutoScalingPolicy object

Definition

The auto scaling policy.

Constraints

N/A

Range

N/A

Default Value

N/A

Table 3 AutoScalingPolicy

Parameter

Mandatory

Type

Description

auto_scaling_enable

Yes

Boolean

Definition

Whether to enable the auto scaling rule.

Constraints

N/A

Range

  • true: Enable the auto scaling rule.
  • false: Disable the autoscaling rule.

Default Value

N/A

min_capacity

Yes

Integer

Definition

Minimum number of nodes left in the node group.

Constraints

N/A

Range

0-500

Default Value

N/A

max_capacity

Yes

Integer

Definition

Maximum number of nodes in the node group.

Constraints

N/A

Range

0-500

Default Value

N/A

resources_plans

No

Array of ResourcesPlan objects

Definition

Resource plan list. If this parameter is left blank, resource plans are disabled.

Constraints

When auto scaling is enabled, either a resource plan or an auto scaling rule must be configured. A maximum of five resource plans are allowed.

Range

N/A

Default Value

N/A

rules

No

Array of Rule objects

Definition

Autoscaling rule list.

Constraints

When auto scaling is enabled, either a resource plan or an auto scaling rule must be configured. The number of records cannot exceed 10.

Range

N/A

Default Value

N/A

exec_scripts

No

Array of ScaleScript objects

Definition

List of custom scaling automation scripts. If this parameter is left blank, automation scripts are disabled.

Constraints

The number of records cannot exceed 10.

Range

N/A

Default Value

N/A

Table 4 ResourcesPlan

Parameter

Mandatory

Type

Description

period_type

Yes

String

Definition

Cycle type of a resource plan. This parameter can be set to daily only.

Constraints

N/A

Range

  • daily: Charges are calculated by day.

Default Value

N/A

start_time

Yes

String

Definition

Start time of a resource plan. The value is in the format of hour:minute.

Constraints

N/A

Range

N/A

Default Value

N/A

end_time

Yes

String

Definition

End time of a resource plan. The format is the same as that of start_time.

Constraints

The value cannot be earlier than the start_time, and the interval between start_time and start_time cannot be less than 30 minutes.

Range

N/A

Default Value

N/A

min_capacity

Yes

Integer

Definition

Minimum number of the preserved nodes in a node group in a resource plan.

Constraints

N/A

Range

0-500

Default Value

N/A

max_capacity

Yes

Integer

Definition

Maximum number of the preserved nodes in a node group in a resource plan.

Constraints

N/A

Range

0-500

Default Value

N/A

Table 5 ScaleScript

Parameter

Mandatory

Type

Description

name

Yes

String

Definition

Names of custom scaling automation scripts.

Constraints

N/A

Range

The names of custom automation scripts within the same cluster must be unique. The value can contain 1 to 64 characters. Only letters, digits, underscores (_), and hyphens (-) are allowed.

Default Value

N/A

uri

Yes

String

Definition

Path of a custom automation script. Set this parameter to an OBS bucket path or a local VM path.

  • OBS bucket path: Enter a script path manually, for example, s3a://XXX/scale.sh.
  • Local VM path: Enter a script path. The script path must start with a slash (/) and end with .sh.

Constraints

N/A

Range

N/A

Default Value

N/A

parameters

No

String

Definition

Parameters of a custom automation script. Multiple parameters are separated by spaces. The following system predefined parameters can be passed in:
  • ${mrs_scale_node_num}: Number of the nodes to be added or removed
  • ${mrs_scale_type}: Scaling type. The value can be scale_out or scale_in.
  • ${mrs_scale_node_hostnames}: Host names of the nodes to be added or removed
  • ${mrs_scale_node_ips}: IP addresses of the nodes to be added or removed
  • ${mrs_scale_rule_name}: Name of the rule that triggers auto scaling

Other user-defined parameters are used in the same way as in a normal shell script, with multiple parameters separated by spaces.

Constraints

N/A

Range

N/A

Default Value

N/A

nodes

Yes

Array of strings

Definition

Name of the node group where the custom automation script is executed (for non-custom clusters, node types can also be used, including Master, Core, and Task).

Constraints

N/A

Range

N/A

Default Value

N/A

active_master

No

Boolean

Definition

Whether the custom automation script runs only on the active Master node.

Constraints

N/A

Range

  • true: The custom automation script runs only on the active Master nodes.
  • false: The custom automation script can run on all Master nodes.

Default Value

false

action_stage

Yes

String

Definition

Time when a script is executed.

Constraints

N/A

Range

  • before_scale_out: before scale-out
  • before_scale_in: before scale-in
  • after_scale_out: after scale-out
  • after_scale_in: after scale-in

Default Value

N/A

fail_action

Yes

String

Definition

Whether to continue executing subsequent scripts and creating the cluster if the custom automation script fails. You are advised to set this parameter to continue during the debugging phase, so that regardless of whether the custom automation script executes successfully, the cluster can continue with installation and startup. Since scaling in cannot be rolled back, the fail_action of scripts executed after scaling in must be set to continue.

Constraints

N/A

Range

  • continue: Continue to execute subsequent scripts.
  • errorout: Stop the action.

Default Value

continue

Table 6 Rule

Parameter

Mandatory

Type

Description

name

Yes

String

Definition

Name of an auto scaling rule.

Constraints

N/A

Range

The value can contain 1 to 64 characters. Only letters, digits, underscores (_), and hyphens (-) are allowed. Rule names must be unique in a node group.

Default Value

N/A

description

No

String

Definition

Description about an auto scaling rule.

Constraints

N/A

Range

A string of 1 to 1024 characters

Default Value

N/A

adjustment_type

Yes

String

Definition

Adjustment type of an auto scaling rule.

Constraints

N/A

Range

  • scale_out: cluster scale-out
  • scale_in: cluster scale-in

Default Value

N/A

cool_down_minutes

Yes

Integer

Definition

Cluster cooling time after an auto scaling rule is triggered, when no auto scaling operation is performed. The unit is minute.

Constraints

N/A

Range

0 to 10080. 10080 indicates the number of minutes in a week.

Default Value

N/A

scaling_adjustment

Yes

Integer

Definition

Number of nodes that can be adjusted once.

Constraints

N/A

Range

1-100

Default Value

N/A

trigger

Yes

Trigger object

Definition

Trigger condition for this rule.

Constraints

N/A

Range

N/A

Default Value

N/A

Table 7 Trigger

Parameter

Mandatory

Type

Description

metric_name

Yes

String

Definition

Metric name. This trigger condition evaluates based on the value of the metric corresponding to this name.

Constraints

N/A

Range

For the value range, see Autoscaling metrics.

Default Value

N/A

metric_value

Yes

String

Definition

Metric threshold to trigger a rule Threshold that triggers this condition. Only integers or numbers with up to two decimal places are allowed.

Constraints

N/A

Range

Only integers or numbers with two decimal places are allowed.

Default Value

N/A

comparison_operator

No

String

Definition

Metric judgment logic operator.

Constraints

N/A

Range

  • LT: less than
  • GT: greater than
  • LTOE: less than or equal to
  • GTOE: greater than or equal to

Default Value

N/A

evaluation_periods

Yes

Integer

Definition

Number of consecutive five-minute periods, during which a metric threshold is reached

Constraints

N/A

Range

1-200

Default Value

N/A

Response Parameters

Status code: 200

Table 8 Response body parameter

Parameter

Type

Description

result

String

Definition

Operation result

Range

  • succeeded: The operation is successful.
  • Error Codes describes the error codes returned upon operation failures.

Example Request

Configure autoscaling rules for the cluster.

POST https://{endpoint}/v1.1/{project_id}/autoscaling-policy/{cluster_id}

{
  "node_group" : "task_node_analysis_group",
  "auto_scaling_policy" : {
    "auto_scaling_enable" : "true",
    "min_capacity" : "1",
    "max_capacity" : "3",
    "resources_plans" : [ {
      "period_type" : "daily",
      "start_time" : "9:50",
      "end_time" : "10:20",
      "min_capacity" : "2",
      "max_capacity" : "3"
    }, {
      "period_type" : "daily",
      "start_time" : "10:20",
      "end_time" : "12:30",
      "min_capacity" : "0",
      "max_capacity" : "2"
    } ],
    "exec_scripts" : [ {
      "name" : "before_scale_out",
      "uri" : "s3a://XXX/zeppelin_install.sh",
      "parameters" : "${mrs_scale_node_num} ${mrs_scale_type} xxx",
      "nodes" : [ "master_node_default_group", "core_node_analysis_group", "task_node_analysis_group" ],
      "active_master" : "true",
      "action_stage" : "before_scale_out",
      "fail_action" : "continue"
    }, {
      "name" : "after_scale_out",
      "uri" : "s3a://XXX/storm_rebalance.sh",
      "parameters" : "${mrs_scale_node_hostnames} ${mrs_scale_node_ips}",
      "nodes" : [ "master_node_default_group", "core_node_analysis_group", "task_node_analysis_group" ],
      "active_master" : "true",
      "action_stage" : "after_scale_out",
      "fail_action" : "continue"
    } ],
    "rules" : [ {
      "name" : "default-expand-1",
      "adjustment_type" : "scale_out",
      "cool_down_minutes" : "5",
      "scaling_adjustment" : "1",
      "trigger" : {
        "metric_name" : "YARNMemoryAvailablePercentage",
        "metric_value" : "25",
        "comparison_operator" : "LT",
        "evaluation_periods" : "10"
      }
    }, {
      "name" : "default-shrink-1",
      "adjustment_type" : "scale_in",
      "cool_down_minutes" : "5",
      "scaling_adjustment" : "1",
      "trigger" : {
        "metric_name" : "YARNMemoryAvailablePercentage",
        "metric_value" : "70",
        "comparison_operator" : "GT",
        "evaluation_periods" : "10"
      }
    } ]
  }
}

Example Response

Status code: 200

The operation is successful.

{
  "result" : "succeeded"
}

SDK Sample Code

The SDK sample code is as follows.

Configure autoscaling rules for the cluster.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package com.huaweicloud.sdk.test;

import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.mrs.v1.region.MrsRegion;
import com.huaweicloud.sdk.mrs.v1.*;
import com.huaweicloud.sdk.mrs.v1.model.*;

import java.util.List;
import java.util.ArrayList;

public class CreateScalingPolicySolution {

    public static void main(String[] args) {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        String ak = System.getenv("CLOUD_SDK_AK");
        String sk = System.getenv("CLOUD_SDK_SK");
        String projectId = "{project_id}";

        ICredential auth = new BasicCredentials()
                .withProjectId(projectId)
                .withAk(ak)
                .withSk(sk);

        MrsClient client = MrsClient.newBuilder()
                .withCredential(auth)
                .withRegion(MrsRegion.valueOf("<YOUR REGION>"))
                .build();
        CreateScalingPolicyRequest request = new CreateScalingPolicyRequest();
        request.withClusterId("{cluster_id}");
        AutoScalingPolicyReqV11 body = new AutoScalingPolicyReqV11();
        List<String> listExecScriptsNodes = new ArrayList<>();
        listExecScriptsNodes.add("master_node_default_group");
        listExecScriptsNodes.add("core_node_analysis_group");
        listExecScriptsNodes.add("task_node_analysis_group");
        List<String> listExecScriptsNodes1 = new ArrayList<>();
        listExecScriptsNodes1.add("master_node_default_group");
        listExecScriptsNodes1.add("core_node_analysis_group");
        listExecScriptsNodes1.add("task_node_analysis_group");
        List<ScaleScript> listAutoScalingPolicyExecScripts = new ArrayList<>();
        listAutoScalingPolicyExecScripts.add(
            new ScaleScript()
                .withName("before_scale_out")
                .withUri("s3a://XXX/zeppelin_install.sh")
                .withParameters("${mrs_scale_node_num} ${mrs_scale_type} xxx")
                .withNodes(listExecScriptsNodes1)
                .withActiveMaster(true)
                .withFailAction(ScaleScript.FailActionEnum.fromValue("continue"))
                .withActionStage(ScaleScript.ActionStageEnum.fromValue("before_scale_out"))
        );
        listAutoScalingPolicyExecScripts.add(
            new ScaleScript()
                .withName("after_scale_out")
                .withUri("s3a://XXX/storm_rebalance.sh")
                .withParameters("${mrs_scale_node_hostnames} ${mrs_scale_node_ips}")
                .withNodes(listExecScriptsNodes)
                .withActiveMaster(true)
                .withFailAction(ScaleScript.FailActionEnum.fromValue("continue"))
                .withActionStage(ScaleScript.ActionStageEnum.fromValue("after_scale_out"))
        );
        Trigger triggerRules = new Trigger();
        triggerRules.withMetricName("YARNMemoryAvailablePercentage")
            .withMetricValue("70")
            .withComparisonOperator("GT")
            .withEvaluationPeriods(10);
        Trigger triggerRules1 = new Trigger();
        triggerRules1.withMetricName("YARNMemoryAvailablePercentage")
            .withMetricValue("25")
            .withComparisonOperator("LT")
            .withEvaluationPeriods(10);
        List<Rule> listAutoScalingPolicyRules = new ArrayList<>();
        listAutoScalingPolicyRules.add(
            new Rule()
                .withName("default-expand-1")
                .withAdjustmentType(Rule.AdjustmentTypeEnum.fromValue("scale_out"))
                .withCoolDownMinutes(5)
                .withScalingAdjustment(1)
                .withTrigger(triggerRules1)
        );
        listAutoScalingPolicyRules.add(
            new Rule()
                .withName("default-shrink-1")
                .withAdjustmentType(Rule.AdjustmentTypeEnum.fromValue("scale_in"))
                .withCoolDownMinutes(5)
                .withScalingAdjustment(1)
                .withTrigger(triggerRules)
        );
        List<ResourcesPlan> listAutoScalingPolicyResourcesPlans = new ArrayList<>();
        listAutoScalingPolicyResourcesPlans.add(
            new ResourcesPlan()
                .withPeriodType("daily")
                .withStartTime("9:50")
                .withEndTime("10:20")
                .withMinCapacity(2)
                .withMaxCapacity(3)
        );
        listAutoScalingPolicyResourcesPlans.add(
            new ResourcesPlan()
                .withPeriodType("daily")
                .withStartTime("10:20")
                .withEndTime("12:30")
                .withMinCapacity(0)
                .withMaxCapacity(2)
        );
        AutoScalingPolicy autoScalingPolicybody = new AutoScalingPolicy();
        autoScalingPolicybody.withAutoScalingEnable(true)
            .withMinCapacity(1)
            .withMaxCapacity(3)
            .withResourcesPlans(listAutoScalingPolicyResourcesPlans)
            .withRules(listAutoScalingPolicyRules)
            .withExecScripts(listAutoScalingPolicyExecScripts);
        body.withAutoScalingPolicy(autoScalingPolicybody);
        body.withNodeGroup(AutoScalingPolicyReqV11.NodeGroupEnum.fromValue("task_node_analysis_group"));
        request.withBody(body);
        try {
            CreateScalingPolicyResponse response = client.createScalingPolicy(request);
            System.out.println(response.toString());
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getRequestId());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }
    }
}

Configure autoscaling rules for the cluster.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# coding: utf-8

import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkmrs.v1.region.mrs_region import MrsRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkmrs.v1 import *

if __name__ == "__main__":
    # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
    # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
    ak = os.environ["CLOUD_SDK_AK"]
    sk = os.environ["CLOUD_SDK_SK"]
    projectId = "{project_id}"

    credentials = BasicCredentials(ak, sk, projectId)

    client = MrsClient.new_builder() \
        .with_credentials(credentials) \
        .with_region(MrsRegion.value_of("<YOUR REGION>")) \
        .build()

    try:
        request = CreateScalingPolicyRequest()
        request.cluster_id = "{cluster_id}"
        listNodesExecScripts = [
            "master_node_default_group",
            "core_node_analysis_group",
            "task_node_analysis_group"
        ]
        listNodesExecScripts1 = [
            "master_node_default_group",
            "core_node_analysis_group",
            "task_node_analysis_group"
        ]
        listExecScriptsAutoScalingPolicy = [
            ScaleScript(
                name="before_scale_out",
                uri="s3a://XXX/zeppelin_install.sh",
                parameters="${mrs_scale_node_num} ${mrs_scale_type} xxx",
                nodes=listNodesExecScripts1,
                active_master=True,
                fail_action="continue",
                action_stage="before_scale_out"
            ),
            ScaleScript(
                name="after_scale_out",
                uri="s3a://XXX/storm_rebalance.sh",
                parameters="${mrs_scale_node_hostnames} ${mrs_scale_node_ips}",
                nodes=listNodesExecScripts,
                active_master=True,
                fail_action="continue",
                action_stage="after_scale_out"
            )
        ]
        triggerRules = Trigger(
            metric_name="YARNMemoryAvailablePercentage",
            metric_value="70",
            comparison_operator="GT",
            evaluation_periods=10
        )
        triggerRules1 = Trigger(
            metric_name="YARNMemoryAvailablePercentage",
            metric_value="25",
            comparison_operator="LT",
            evaluation_periods=10
        )
        listRulesAutoScalingPolicy = [
            Rule(
                name="default-expand-1",
                adjustment_type="scale_out",
                cool_down_minutes=5,
                scaling_adjustment=1,
                trigger=triggerRules1
            ),
            Rule(
                name="default-shrink-1",
                adjustment_type="scale_in",
                cool_down_minutes=5,
                scaling_adjustment=1,
                trigger=triggerRules
            )
        ]
        listResourcesPlansAutoScalingPolicy = [
            ResourcesPlan(
                period_type="daily",
                start_time="9:50",
                end_time="10:20",
                min_capacity=2,
                max_capacity=3
            ),
            ResourcesPlan(
                period_type="daily",
                start_time="10:20",
                end_time="12:30",
                min_capacity=0,
                max_capacity=2
            )
        ]
        autoScalingPolicybody = AutoScalingPolicy(
            auto_scaling_enable=True,
            min_capacity=1,
            max_capacity=3,
            resources_plans=listResourcesPlansAutoScalingPolicy,
            rules=listRulesAutoScalingPolicy,
            exec_scripts=listExecScriptsAutoScalingPolicy
        )
        request.body = AutoScalingPolicyReqV11(
            auto_scaling_policy=autoScalingPolicybody,
            node_group="task_node_default_group"
        )
        response = client.create_scaling_policy(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

Configure autoscaling rules for the cluster.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package main

import (
	"fmt"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
    mrs "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/mrs/v1"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/mrs/v1/model"
    region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/mrs/v1/region"
)

func main() {
    // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
    // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
    ak := os.Getenv("CLOUD_SDK_AK")
    sk := os.Getenv("CLOUD_SDK_SK")
    projectId := "{project_id}"

    auth := basic.NewCredentialsBuilder().
        WithAk(ak).
        WithSk(sk).
        WithProjectId(projectId).
        Build()

    client := mrs.NewMrsClient(
        mrs.MrsClientBuilder().
            WithRegion(region.ValueOf("<YOUR REGION>")).
            WithCredential(auth).
            Build())

    request := &model.CreateScalingPolicyRequest{}
	request.ClusterId = "{cluster_id}"
	var listNodesExecScripts = []string{
        "master_node_default_group",
	    "core_node_analysis_group",
	    "task_node_analysis_group",
    }
	var listNodesExecScripts1 = []string{
        "master_node_default_group",
	    "core_node_analysis_group",
	    "task_node_analysis_group",
    }
	parametersExecScripts:= "${mrs_scale_node_num} ${mrs_scale_type} xxx"
	activeMasterExecScripts:= true
	parametersExecScripts1:= "${mrs_scale_node_hostnames} ${mrs_scale_node_ips}"
	activeMasterExecScripts1:= true
	var listExecScriptsAutoScalingPolicy = []model.ScaleScript{
        {
            Name: "before_scale_out",
            Uri: "s3a://XXX/zeppelin_install.sh",
            Parameters: &parametersExecScripts,
            Nodes: listNodesExecScripts1,
            ActiveMaster: &activeMasterExecScripts,
            FailAction: model.GetScaleScriptFailActionEnum().CONTINUE,
            ActionStage: model.GetScaleScriptActionStageEnum().BEFORE_SCALE_OUT,
        },
        {
            Name: "after_scale_out",
            Uri: "s3a://XXX/storm_rebalance.sh",
            Parameters: &parametersExecScripts1,
            Nodes: listNodesExecScripts,
            ActiveMaster: &activeMasterExecScripts1,
            FailAction: model.GetScaleScriptFailActionEnum().CONTINUE,
            ActionStage: model.GetScaleScriptActionStageEnum().AFTER_SCALE_OUT,
        },
    }
	comparisonOperatorTrigger:= "GT"
	triggerRules := &model.Trigger{
		MetricName: "YARNMemoryAvailablePercentage",
		MetricValue: "70",
		ComparisonOperator: &comparisonOperatorTrigger,
		EvaluationPeriods: int32(10),
	}
	comparisonOperatorTrigger1:= "LT"
	triggerRules1 := &model.Trigger{
		MetricName: "YARNMemoryAvailablePercentage",
		MetricValue: "25",
		ComparisonOperator: &comparisonOperatorTrigger1,
		EvaluationPeriods: int32(10),
	}
	var listRulesAutoScalingPolicy = []model.Rule{
        {
            Name: "default-expand-1",
            AdjustmentType: model.GetRuleAdjustmentTypeEnum().SCALE_OUT,
            CoolDownMinutes: int32(5),
            ScalingAdjustment: int32(1),
            Trigger: triggerRules1,
        },
        {
            Name: "default-shrink-1",
            AdjustmentType: model.GetRuleAdjustmentTypeEnum().SCALE_IN,
            CoolDownMinutes: int32(5),
            ScalingAdjustment: int32(1),
            Trigger: triggerRules,
        },
    }
	var listResourcesPlansAutoScalingPolicy = []model.ResourcesPlan{
        {
            PeriodType: "daily",
            StartTime: "9:50",
            EndTime: "10:20",
            MinCapacity: int32(2),
            MaxCapacity: int32(3),
        },
        {
            PeriodType: "daily",
            StartTime: "10:20",
            EndTime: "12:30",
            MinCapacity: int32(0),
            MaxCapacity: int32(2),
        },
    }
	autoScalingPolicybody := &model.AutoScalingPolicy{
		AutoScalingEnable: true,
		MinCapacity: int32(1),
		MaxCapacity: int32(3),
		ResourcesPlans: &listResourcesPlansAutoScalingPolicy,
		Rules: &listRulesAutoScalingPolicy,
		ExecScripts: &listExecScriptsAutoScalingPolicy,
	}
	request.Body = &model.AutoScalingPolicyReqV11{
		AutoScalingPolicy: autoScalingPolicybody,
		NodeGroup: model.GetAutoScalingPolicyReqV11NodeGroupEnum().TASK_NODE_ANALYSIS_GROUP,
	}
	response, err := client.CreateScalingPolicy(request)
	if err == nil {
        fmt.Printf("%+v\n", response)
    } else {
        fmt.Println(err)
    }
}

For SDK sample code of more programming languages, see the Sample Code tab in API Explorer. SDK sample code can be automatically generated.

Status Codes

Table 9 describes the status code.

Table 9 Status code

Status Code

Description

200

Operation succeeded.

Error Codes

See Error Codes.