Help Center/ Config/ API Reference/ APIs/ Resource Tags/ Querying Resource Statistics
Updated on 2024-06-21 GMT+08:00

Querying Resource Statistics

Function

This API is used to query resource statistics. TMS allows you to filter resources by tag. Query results will be displayed in a list.Up to 20 tags can be specified in parameters: tags, tags_any, not_tags, and not_tags_any.

Calling Method

For details, see Calling APIs.

URI

POST /v1/resource-manager/{resource_type}/resource-instances/count

Table 1 Path Parameters

Parameter

Mandatory

Type

Description

resource_type

Yes

String

Resource type.

Request Parameters

Table 2 Request body parameters

Parameter

Mandatory

Type

Description

without_any_tag

No

Boolean

Tags to be excluded.If this parameter is set to true, all resources that do not have the specified tags will be returned. If this parameter is set to false or is not specified, it does not take effect.

Default: false

tags

No

Array of Tag objects

Specified tags. Up to 20 tag keys can be specified, and up to 20 values can be specified for each key. Each tag value can be an empty array, but the tag structure cannot be missing. Each tag key must be unique, and the values of the same key must be unique. Resources containing any of the specified tags will be returned. Keys in this list are in an AND relationship while values in each key-value structure is in an OR relationship.If no tag filtering condition is specified, full data is returned.

matches

No

Array of Match objects

Search field. A field contains a key (such as resource_name) and a value. Keys are predefined and must be unique and valid. Whether fuzzy or exact match is used is determined based on the filed key. For example, exact match is used for the field key resource_name. If the field value is an empty string, exact match is used. Since very few resources have an empty-string name, an empty list is returned. Exact match is used for the field key resource_id. Currently only resource_name is supported.

Table 3 Tag

Parameter

Mandatory

Type

Description

key

Yes

String

Tag key. A key can contain up to 128 Unicode characters and cannot be left blank. The system does not verify the character set of the key when searching for resources. The key element cannot be empty, an empty string, or spaces. Before using the key element, delete single-byte character (SBC) spaces before and after the value.

Minimum: 1

Maximum: 128

values

Yes

Array of strings

Tag values. A key can contain up to 255 Unicode characters. Before verifying or using the value element, delete single-byte character (SBC) spaces before and after the value. The value can be an empty array but cannot be left blank. If no value is specified, any values are supported. Values are in an Or relathionship. The system does not verify the character set of bvaluesb when searching for resources, but only verifies the length.

Maximum: 255

Array Length: 0 - 20

Table 4 Match

Parameter

Mandatory

Type

Description

key

Yes

String

Tag key. Currently, only the resource_name is supported.

value

Yes

String

Tag value. A tag value can contain up to 255 Unicode characters. The character set of a tag value will not be verified by the system.

Maximum: 255

Response Parameters

Status code: 200

Table 5 Response body parameters

Parameter

Type

Description

total_count

Integer

The total number of records.

Status code: 400

Table 6 Response body parameters

Parameter

Type

Description

error_code

String

Specifies the error code.

error_msg

String

Specifies the error message.

Status code: 401

Table 7 Response body parameters

Parameter

Type

Description

error_code

String

Specifies the error code.

error_msg

String

Specifies the error message.

Status code: 403

Table 8 Response body parameters

Parameter

Type

Description

error_code

String

Specifies the error code.

error_msg

String

Specifies the error message.

Status code: 404

Table 9 Response body parameters

Parameter

Type

Description

error_code

String

Specifies the error code.

error_msg

String

Specifies the error message.

Status code: 500

Table 10 Response body parameters

Parameter

Type

Description

error_code

String

Specifies the error code.

error_msg

String

Specifies the error message.

Example Requests

Querying the Number of Instances By Tags

POST https://{endpoint}/v1/resource-manager/{resource_type}/resource-instances/count

{
  "tags" : [ {
    "key" : "key1",
    "values" : [ "value1", "value2" ]
  }, {
    "key" : "key2",
    "values" : [ "value1", "value2" ]
  } ],
  "matches" : [ {
    "key" : "resource_name",
    "value" : "resource1"
  } ]
}

Example Responses

Status code: 200

Succeeded.

{
  "total_count" : 1000
}

SDK Sample Code

The SDK sample code is as follows.

Querying the Number of Instances By Tags

 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
package com.huaweicloud.sdk.test;

import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.auth.GlobalCredentials;
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.config.v1.region.ConfigRegion;
import com.huaweicloud.sdk.config.v1.*;
import com.huaweicloud.sdk.config.v1.model.*;

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

public class CountResourcesByTagSolution {

    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");

        ICredential auth = new GlobalCredentials()
                .withAk(ak)
                .withSk(sk);

        ConfigClient client = ConfigClient.newBuilder()
                .withCredential(auth)
                .withRegion(ConfigRegion.valueOf("<YOUR REGION>"))
                .build();
        CountResourcesByTagRequest request = new CountResourcesByTagRequest();
        ResourceInstancesReq body = new ResourceInstancesReq();
        List<Match> listbodyMatches = new ArrayList<>();
        listbodyMatches.add(
            new Match()
                .withKey(Match.KeyEnum.fromValue("resource_name"))
                .withValue("resource1")
        );
        List<String> listTagsValues = new ArrayList<>();
        listTagsValues.add("value1");
        listTagsValues.add("value2");
        List<String> listTagsValues1 = new ArrayList<>();
        listTagsValues1.add("value1");
        listTagsValues1.add("value2");
        List<Tag> listbodyTags = new ArrayList<>();
        listbodyTags.add(
            new Tag()
                .withKey("key1")
                .withValues(listTagsValues1)
        );
        listbodyTags.add(
            new Tag()
                .withKey("key2")
                .withValues(listTagsValues)
        );
        body.withMatches(listbodyMatches);
        body.withTags(listbodyTags);
        request.withBody(body);
        try {
            CountResourcesByTagResponse response = client.countResourcesByTag(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());
        }
    }
}

Querying the Number of Instances By Tags

 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
# coding: utf-8

import os
from huaweicloudsdkcore.auth.credentials import GlobalCredentials
from huaweicloudsdkconfig.v1.region.config_region import ConfigRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkconfig.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"]

    credentials = GlobalCredentials(ak, sk)

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

    try:
        request = CountResourcesByTagRequest()
        listMatchesbody = [
            Match(
                key="resource_name",
                value="resource1"
            )
        ]
        listValuesTags = [
            "value1",
            "value2"
        ]
        listValuesTags1 = [
            "value1",
            "value2"
        ]
        listTagsbody = [
            Tag(
                key="key1",
                values=listValuesTags1
            ),
            Tag(
                key="key2",
                values=listValuesTags
            )
        ]
        request.body = ResourceInstancesReq(
            matches=listMatchesbody,
            tags=listTagsbody
        )
        response = client.count_resources_by_tag(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

Querying the Number of Instances By Tags

 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
package main

import (
	"fmt"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/global"
    config "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/config/v1"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/config/v1/model"
    region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/config/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")

    auth := global.NewCredentialsBuilder().
        WithAk(ak).
        WithSk(sk).
        Build()

    client := config.NewConfigClient(
        config.ConfigClientBuilder().
            WithRegion(region.ValueOf("<YOUR REGION>")).
            WithCredential(auth).
            Build())

    request := &model.CountResourcesByTagRequest{}
	var listMatchesbody = []model.Match{
        {
            Key: model.GetMatchKeyEnum().RESOURCE_NAME,
            Value: "resource1",
        },
    }
	var listValuesTags = []string{
        "value1",
	    "value2",
    }
	var listValuesTags1 = []string{
        "value1",
	    "value2",
    }
	var listTagsbody = []model.Tag{
        {
            Key: "key1",
            Values: listValuesTags1,
        },
        {
            Key: "key2",
            Values: listValuesTags,
        },
    }
	request.Body = &model.ResourceInstancesReq{
		Matches: &listMatchesbody,
		Tags: &listTagsbody,
	}
	response, err := client.CountResourcesByTag(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

Status Code

Description

200

Succeeded.

400

Invalid parameter.

401

Unauthorized.

403

Forbidden.

404

Resources not found.

500

Internal server error.

Error Codes

See Error Codes.