Help Center/ Database Security Service/ API Reference/ API/ TMS Tags/ Querying the Number of Resource Instances by Tag
Updated on 2024-11-01 GMT+08:00

Querying the Number of Resource Instances by Tag

Function

Querying the Number of Resource Instances by Tag

Calling Method

For details, see Calling APIs.

URI

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

Table 1 URI parameter

Parameter

Mandatory

Parameter Type

Description

project_id

Yes

String

Project ID.

resource_type

Yes

String

Resource type.

  • auditInstance

Request Parameter

Table 2 Request header parameter

Parameter

Mandatory

Parameter Type

Description

X-Auth-Token

Yes

String

User token. The token can be queried by calling the IAM API. (The token is the value of X-Subject-Token in the response header.)

Table 3 Request body parameter

Parameter

Mandatory

Parameter Type

Description

matches

No

Array of matches objects

Specifies the search criteria. The tag key is the parameter to match, for example, resource_name. The tag value indicates the value to be matched. The key is a fixed dictionary value and cannot contain duplicate keys or unsupported keys. Check whether fuzzy match is required based on the key value. For example, if key is set to resource_name, fuzzy search (case-insensitive) is performed by default. If value is empty, exact match is performed. Most services do not have resources without names. In this case, an empty list is returned. If key is resource_id, exact match is performed. Only resource_name for key is supported. Other key values will be available later.

not_tags

No

Array of TagKeyValuesBean objects

The resources to be queried do not contain tags listed in not_tags. Each resource to be queried contains a maximum of 50 keys. Each tag key can have a maximum of 10 tag values. The tag value corresponding to each tag key can be an empty array but the structure cannot be missing. Keys must be unique and values of a key must be unique. The response returns resources containing no tags in this list. Keys in this list are in an AND relationship while values in each key-value structure are in an OR relationship. If no tag filtering condition is specified, full data is returned.

tags

No

Array of TagKeyValuesBean objects

The resources to be queried contain tags listed in tags. Each instance to be queried contains a maximum of 50 keys. Each tag key has a maximum of 10 tag values. The tag value corresponding to each tag key can be an empty array but the structure cannot be missing. Keys must be unique and values of a key must be unique. The response returns instances containing all tags in this list. Keys in this list are in the AND relationship and values in each key-value structure are in the OR relationship. If no tag filtering condition is specified, full data is returned.

tags_any

No

Array of TagKeyValuesBean objects

The resources to be queried contain any tags listed in tags_any. Each resource to be queried contains a maximum of 50 keys. Each tag key can have a maximum of 10 tag values. The tag value corresponding to each tag key can be an empty array but the structure cannot be missing. Keys must be unique and values of a key must be unique. The response returns instances containing any tag in this list. Keys in this list are in the OR relationship and values in each key-value structure are also in the OR relationship. If no tag filtering condition is specified, full data is returned.

not_tags_any

No

Array of TagKeyValuesBean objects

The resources to be queried do not contain any tags listed in not_tags_any. Each resource to be queried contains a maximum of 50 keys. Each tag key can have a maximum of 10 tag values. The tag value corresponding to each tag key can be an empty array but the structure cannot be missing. Keys must be unique and values of a key must be unique. The response returns resources containing no tag in this list. Keys in this list are in the OR relationship and values in each key-value structure are also in the OR relationship. If no tag filtering condition is specified, full data is returned.

sys_tags

No

TagKeyValuesBean object

Only users with the op_service permission can use this parameter to filter resources. Only one tag structure is contained when this API is called by Tag Management Service (TMS). The key is _sys_enterprise_project_idvalue, and the value is an enterprise project ID. Currently, each key can contain only one value. 0 indicates the default enterprise project. sys_tags cannot be used together with tenant tag filtering criteria (without_any_tag, tags, tags_any, not_tags, and not_tags_any). If sys_tags is not specified, resources with all the tags specified in tags will be returned. If tags is not specified, all resources will be returned.

without_any_tag

No

Boolean

If this parameter is set to true, all resources without tags are queried. In this case, the tags, tags_any, not_tags, and not_tags_any fields are ignored.

Table 4 matches

Parameter

Mandatory

Parameter Type

Description

key

Yes

String

Key. Only resource_name is supported.

value

Yes

String

Value, which is the name of the resource to be matched.

Table 5 TagKeyValuesBean

Parameter

Mandatory

Parameter Type

Description

key

Yes

String

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

values

Yes

Array of strings

List of tag values. Each value contains a maximum of 255 Unicode characters. Before verifying and using values, delete SBC spaces before and after the value.

The value can be an empty array but cannot be left blank.

If the values are null, it indicates any_value (querying any value). The values are in the OR relationship.

Response Parameters

Status code: 200

Table 6 Response body parameter

Parameter

Parameter Type

Description

resources

Array of resources objects

Resource instance list.

total_count

Integer

Total number of records.

Table 7 resources

Parameter

Parameter Type

Description

resource_id

String

Resource ID.

resource_name

String

Resource name. If the resource does not have a name, the ID is returned.

resource_detail

Object

Specifies the share details. This field is reserved for subsequent extension, and its value defaults to an empty string.

tags

Array of tags objects

A list of tags for queried resources to match against. This parameter is an empty array by default if there is no tag.

sys_tags

Array of sys_tags objects

Only the op_service permission can obtain this field.

Only one **resource_tag** structure is included currently.

The key is _sys_enterprise_project_id.

value: enterprise project ID. The value 0 indicates the default enterprise project.

This field is not returned for the non-op_service permission.

Table 8 Tag

Parameter

Parameter Type

Description

key

String

Tag key.

value

String

Value

Table 9 sys_tags

Parameter

Parameter Type

Description

key

String

Tag key.

value

String

Value

Status code: 400

Table 10 Response body parameter

Parameter

Parameter Type

Description

error

Object

Error message.

Table 11 ErrorDetail

Parameter

Parameter Type

Description

error_code

String

Error code

error_msg

String

Error message

Status code: 403

Table 12 Response body parameter

Parameter

Parameter Type

Description

error

Object

Error message.

Table 13 ErrorDetail

Parameter

Parameter Type

Description

error_code

String

Error code

error_msg

String

Error message

Status code: 500

Table 14 Response body parameters

Parameter

Parameter Type

Description

error

Object

Error message.

Table 15 ErrorDetail

Parameter

Parameter Type

Description

error_code

String

Error code

error_msg

String

Error message

Example Request

/v1/{project_id}/{resource_type}/resource-instances/count

{
  "matches" : [ {
    "key" : "resource_name",
    "value" : "resource1"
  } ],
  "not_tags" : [ {
    "key" : "key1",
    "values" : [ "*value1", "value2" ]
  } ],
  "tags" : [ {
    "key" : "key1",
    "values" : [ "*value1", "value2" ]
  } ],
  "tags_any" : [ {
    "key" : "key1",
    "values" : [ "value1", "value2" ]
  } ],
  "not_tags_any" : [ {
    "key" : "key1",
    "values" : [ "value1", "value2" ]
  } ],
  "sys_tags" : [ {
    "key" : "_sys_enterprise_project_id",
    "values" : [ "5aa119a8-d25b-45a7-8d1b-88e127885635" ]
  } ]
}

Response Examples

Status code: 200

Execution succeeded.

{
  "total_count" : 1000
}

Status code: 400

Failed

{
  "error" : {
    "error_code" : "DBSS.XXXX",
    "error_msg" : "XXX"
  }
}

Example SDK Code

The sample code is as follows.

Java

  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
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.dbss.v1.region.DbssRegion;
import com.huaweicloud.sdk.dbss.v1.*;
import com.huaweicloud.sdk.dbss.v1.model.*;

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

public class CountResourceInstanceByTagSolution {

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

        DbssClient client = DbssClient.newBuilder()
                .withCredential(auth)
                .withRegion(DbssRegion.valueOf("<YOUR REGION>"))
                .build();
        CountResourceInstanceByTagRequest request = new CountResourceInstanceByTagRequest();
        request.withResourceType("{resource_type}");
        ResourceInstanceTagRequest body = new ResourceInstanceTagRequest();
        List<String> listNotTagsAnyValues = new ArrayList<>();
        listNotTagsAnyValues.add("value1");
        listNotTagsAnyValues.add("value2");
        List<TagKeyValuesBean> listbodyNotTagsAny = new ArrayList<>();
        listbodyNotTagsAny.add(
            new TagKeyValuesBean()
                .withKey("key1")
                .withValues(listNotTagsAnyValues)
        );
        List<String> listTagsAnyValues = new ArrayList<>();
        listTagsAnyValues.add("value1");
        listTagsAnyValues.add("value2");
        List<TagKeyValuesBean> listbodyTagsAny = new ArrayList<>();
        listbodyTagsAny.add(
            new TagKeyValuesBean()
                .withKey("key1")
                .withValues(listTagsAnyValues)
        );
        List<String> listTagsValues = new ArrayList<>();
        listTagsValues.add("*value1");
        listTagsValues.add("value2");
        List<TagKeyValuesBean> listbodyTags = new ArrayList<>();
        listbodyTags.add(
            new TagKeyValuesBean()
                .withKey("key1")
                .withValues(listTagsValues)
        );
        List<String> listNotTagsValues = new ArrayList<>();
        listNotTagsValues.add("*value1");
        listNotTagsValues.add("value2");
        List<TagKeyValuesBean> listbodyNotTags = new ArrayList<>();
        listbodyNotTags.add(
            new TagKeyValuesBean()
                .withKey("key1")
                .withValues(listNotTagsValues)
        );
        List<ResourceInstanceTagRequestMatches> listbodyMatches = new ArrayList<>();
        listbodyMatches.add(
            new ResourceInstanceTagRequestMatches()
                .withKey("resource_name")
                .withValue("resource1")
        );
        body.withSysTags("[{\"values\":[\"5aa119a8-d25b-45a7-8d1b-88e127885635\"],\"key\":\"_sys_enterprise_project_id\"}]");
        body.withNotTagsAny(listbodyNotTagsAny);
        body.withTagsAny(listbodyTagsAny);
        body.withTags(listbodyTags);
        body.withNotTags(listbodyNotTags);
        body.withMatches(listbodyMatches);
        request.withBody(body);
        try {
            CountResourceInstanceByTagResponse response = client.countResourceInstanceByTag(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());
        }
    }
}

Python

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

import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkdbss.v1.region.dbss_region import DbssRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkdbss.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 = DbssClient.new_builder() \
        .with_credentials(credentials) \
        .with_region(DbssRegion.value_of("<YOUR REGION>")) \
        .build()

    try:
        request = CountResourceInstanceByTagRequest()
        request.resource_type = "{resource_type}"
        listValuesNotTagsAny = [
            "value1",
            "value2"
        ]
        listNotTagsAnybody = [
            TagKeyValuesBean(
                key="key1",
                values=listValuesNotTagsAny
            )
        ]
        listValuesTagsAny = [
            "value1",
            "value2"
        ]
        listTagsAnybody = [
            TagKeyValuesBean(
                key="key1",
                values=listValuesTagsAny
            )
        ]
        listValuesTags = [
            "*value1",
            "value2"
        ]
        listTagsbody = [
            TagKeyValuesBean(
                key="key1",
                values=listValuesTags
            )
        ]
        listValuesNotTags = [
            "*value1",
            "value2"
        ]
        listNotTagsbody = [
            TagKeyValuesBean(
                key="key1",
                values=listValuesNotTags
            )
        ]
        listMatchesbody = [
            ResourceInstanceTagRequestMatches(
                key="resource_name",
                value="resource1"
            )
        ]
        request.body = ResourceInstanceTagRequest(
            sys_tags="[{\"values\":[\"5aa119a8-d25b-45a7-8d1b-88e127885635\"],\"key\":\"_sys_enterprise_project_id\"}]",
            not_tags_any=listNotTagsAnybody,
            tags_any=listTagsAnybody,
            tags=listTagsbody,
            not_tags=listNotTagsbody,
            matches=listMatchesbody
        )
        response = client.count_resource_instance_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)

Go

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

import (
	"fmt"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
    dbss "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dbss/v1"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dbss/v1/model"
    region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dbss/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 := dbss.NewDbssClient(
        dbss.DbssClientBuilder().
            WithRegion(region.ValueOf("<YOUR REGION>")).
            WithCredential(auth).
            Build())

    request := &model.CountResourceInstanceByTagRequest{}
	request.ResourceType = "{resource_type}"
	var listValuesNotTagsAny = []string{
        "value1",
	    "value2",
    }
	var listNotTagsAnybody = []model.TagKeyValuesBean{
        {
            Key: "key1",
            Values: listValuesNotTagsAny,
        },
    }
	var listValuesTagsAny = []string{
        "value1",
	    "value2",
    }
	var listTagsAnybody = []model.TagKeyValuesBean{
        {
            Key: "key1",
            Values: listValuesTagsAny,
        },
    }
	var listValuesTags = []string{
        "*value1",
	    "value2",
    }
	var listTagsbody = []model.TagKeyValuesBean{
        {
            Key: "key1",
            Values: listValuesTags,
        },
    }
	var listValuesNotTags = []string{
        "*value1",
	    "value2",
    }
	var listNotTagsbody = []model.TagKeyValuesBean{
        {
            Key: "key1",
            Values: listValuesNotTags,
        },
    }
	keyMatches:= "resource_name"
	valueMatches:= "resource1"
	var listMatchesbody = []model.ResourceInstanceTagRequestMatches{
        {
            Key: &keyMatches,
            Value: &valueMatches,
        },
    }
	var sysTagsSysTags interface{} = "[{\"values\":[\"5aa119a8-d25b-45a7-8d1b-88e127885635\"],\"key\":\"_sys_enterprise_project_id\"}]"
	request.Body = &model.ResourceInstanceTagRequest{
		SysTags: &sysTagsSysTags,
		NotTagsAny: &listNotTagsAnybody,
		TagsAny: &listTagsAnybody,
		Tags: &listTagsbody,
		NotTags: &listNotTagsbody,
		Matches: &listMatchesbody,
	}
	response, err := client.CountResourceInstanceByTag(request)
	if err == nil {
        fmt.Printf("%+v\n", response)
    } else {
        fmt.Println(err)
    }
}

More

For more SDK code examples in various programming languages, see the Sample Code tab on the right of the API Explorer page, which can automatically generate the corresponding SDK code examples.

Status Code

Status Code

Description

200

Request succeeded.

400

Failed

403

Authentication failed.

500

Server error.

Error Codes

For details, see Error Codes.