33
44import logging
55
6- from c7n_huaweicloud .actions .base import HuaweiCloudBaseAction
7- from c7n_huaweicloud .filters .tms import register_tms_filters
86from c7n_huaweicloud .provider import resources
97from c7n_huaweicloud .query import QueryResourceManager , TypeInfo
10- from huaweicloudsdkcore .exceptions import exceptions
11- from huaweicloudsdkdc .v3 import (
12- ShowDirectConnectRequest ,
13- CreateResourceTagRequest ,
14- DeleteResourceTagRequest
15- )
168
179from c7n .filters .core import AgeFilter
1810from c7n .utils import type_schema
@@ -39,37 +31,10 @@ class DC(QueryResourceManager):
3931
4032 class resource_type (TypeInfo ):
4133 service = 'dc'
42- enum_spec = ('list_direct_connects' , 'direct_connects' , None )
34+ enum_spec = ('list_direct_connects' , 'direct_connects' , 'marker' )
4335 id = 'id'
4436 name = 'name'
45- tag_resource_type = 'direct-connect'
46-
47- def augment (self , resources ):
48- """Enhance resource information
49-
50- Get more detailed information for each direct connect resource and process tag formats
51- """
52- client = self .get_client ()
53- for r in resources :
54- try :
55- request = ShowDirectConnectRequest (direct_connect_id = r ['id' ])
56- response = client .show_direct_connect (request )
57- detail = response .to_dict ()
58- if 'direct_connect' in detail :
59- r .update (detail ['direct_connect' ])
60-
61- # Process tag format, convert to AWS compatible format
62- if 'tags' in r and isinstance (r ['tags' ], list ):
63- tags = []
64- for tag in r ['tags' ]:
65- if isinstance (tag , dict ) and 'key' in tag and 'value' in tag :
66- tags .append ({'Key' : tag ['key' ], 'Value' : tag ['value' ]})
67- r ['Tags' ] = tags
68- except exceptions .ClientRequestException as e :
69- log .warning (
70- f"Unable to get details for direct connect { r ['id' ]} : { e .error_msg } "
71- )
72- return resources
37+ tag_resource_type = 'dc-directconnect'
7338
7439
7540@DC .filter_registry .register ('age' )
@@ -106,218 +71,3 @@ class DCAgeFilter(AgeFilter):
10671
10772 # Specify the field name representing creation time in the resource dictionary
10873 date_attribute = "create_time"
109-
110-
111- @DC .action_registry .register ('tag' )
112- class DCTag (HuaweiCloudBaseAction ):
113- """
114- Add or update tags for direct connect resources
115-
116- This operation allows users to add specified tags to direct connect resources.
117- If the tag already exists, it will update the tag value.
118-
119- :example:
120- Add 'Environment=Production' tag to all direct connect resources:
121-
122- .. code-block:: yaml
123-
124- policies:
125- - name: tag-dc-production
126- resource: huaweicloud.dc
127- actions:
128- - type: tag # Action type
129- key: Environment # Tag key to add/update
130- value: Production # Tag value to set
131- """
132- # Define the input schema for this operation
133- schema = type_schema (
134- 'tag' , # Action type name
135- key = {'type' : 'string' }, # Tag key
136- value = {'type' : 'string' }, # Tag value
137- # Declare 'key' and 'value' parameters are required
138- required = ['key' , 'value' ]
139- )
140-
141- def perform_action (self , resource ):
142- """
143- Perform add/update tag operation on a single resource
144-
145- :param resource: Direct connect resource dictionary to add tags to
146- :return: None
147- """
148- key = self .data .get ('key' )
149- value = self .data .get ('value' )
150-
151- # Get resource ID and name
152- resource_id = resource .get ('id' )
153- resource_name = resource .get ('name' , 'Unknown name' )
154-
155- if not resource_id :
156- log .error (
157- f"Cannot add tag to direct connect resource missing 'id': { resource_name } "
158- )
159- return None
160-
161- # Get Huawei Cloud DC service client
162- client = self .manager .get_client ()
163- project_id = client ._credentials .project_id
164-
165- try :
166- # Build create tag request
167- request = CreateResourceTagRequest ()
168- request .direct_connect_id = resource_id
169- request .project_id = project_id
170- # Direct connect physical connection resource type
171- request .resource_type = "dc-directconnect"
172- request .resource_id = resource_id
173- # Set request body, including tag key-value pair
174- request .body = {"tag" : {"key" : key , "value" : value }}
175-
176- # Call API to execute operation
177- client .create_resource_tag (request )
178- log .info (
179- f"Added/updated tag for direct connect "
180- f"{ resource_name } ({ resource_id } ): { key } ={ value } "
181- )
182- except exceptions .ClientRequestException as e :
183- # Handle API request exceptions
184- log .error (
185- f"Unable to add/update tag { key } for direct connect "
186- f"{ resource_name } ({ resource_id } ): "
187- f"{ e .error_msg } (status code: { e .status_code } )"
188- )
189- except Exception as e :
190- # Handle other potential exceptions
191- log .error (
192- f"Unable to add/update tag { key } for direct connect "
193- f"{ resource_name } ({ resource_id } ): { str (e )} "
194- )
195-
196- return None
197-
198-
199- @DC .action_registry .register ('remove-tag' )
200- class DCRemoveTag (HuaweiCloudBaseAction ):
201- """
202- Remove one or more specified tags from direct connect resources
203-
204- Allows users to remove tags from direct connect resources based on tag keys
205-
206- :example:
207- Remove 'Temporary' tag from all direct connect resources:
208-
209- .. code-block:: yaml
210-
211- policies:
212- - name: remove-temp-dc-tags
213- resource: huaweicloud.dc
214- # Can add filters to ensure only resources with this tag are processed
215- filters:
216- - "tag:Temporary": present
217- actions:
218- - type: remove-tag # Action type
219- key: Temporary # Tag key to remove (required)
220- # Can specify multiple keys to remove multiple tags at once
221- # - type: remove-tag
222- # keys: ["Temp1", "Temp2"]
223- """
224- # Define the input schema for this operation
225- schema = type_schema (
226- 'remove-tag' , # Action type name
227- # Can specify either a single key or a list of keys
228- key = {'type' : 'string' }, # Single tag key to remove
229- keys = {'type' : 'array' , 'items' : {'type' : 'string' }}, # List of tag keys to remove
230- )
231-
232- def perform_action (self , resource ):
233- """
234- Perform remove tag operation on a single resource
235-
236- :param resource: Direct connect resource dictionary to remove tags from
237- :return: None
238- """
239- # Get the list of tag keys to remove
240- tags_to_remove = self .data .get ('keys' , [])
241- single_key = self .data .get ('key' )
242- if single_key and single_key not in tags_to_remove :
243- tags_to_remove .append (single_key )
244-
245- if not tags_to_remove :
246- log .warning ("Remove tag operation did not specify tag keys (key or keys)" )
247- return None
248-
249- # Get resource ID and name
250- resource_id = resource .get ('id' )
251- resource_name = resource .get ('name' , 'Unknown name' )
252-
253- if not resource_id :
254- log .error (
255- f"Cannot remove tags from direct connect resource missing 'id': { resource_name } "
256- )
257- return None
258-
259- # Check tags that actually exist on the resource, avoid trying to delete non-existent tags
260- current_tags = set ()
261-
262- # Process normalized AWS format tags
263- if 'Tags' in resource :
264- current_tags = {t .get ('Key' ) for t in resource .get ('Tags' , [])}
265- # Process original format tags
266- elif 'tags' in resource :
267- tags = resource .get ('tags' , [])
268- if isinstance (tags , list ):
269- for tag in tags :
270- if isinstance (tag , dict ) and 'key' in tag :
271- current_tags .add (tag .get ('key' ))
272-
273- keys_that_exist = [k for k in tags_to_remove if k in current_tags ]
274-
275- if not keys_that_exist :
276- log .debug (
277- f"Direct connect { resource_name } ({ resource_id } ) "
278- f"does not have tags to remove: { tags_to_remove } "
279- )
280- return None
281-
282- # Get Huawei Cloud DC service client
283- client = self .manager .get_client ()
284- # Get project ID
285- project_id = client ._credentials .project_id
286-
287- # Call API for each tag key to delete
288- for key in keys_that_exist :
289- try :
290- # Build delete tag request
291- request = DeleteResourceTagRequest ()
292- # Set path parameters according to API documentation
293- request .project_id = project_id
294- # Direct connect physical connection resource type
295- request .resource_type = "dc-directconnect"
296- request .resource_id = resource_id
297- request .key = key
298-
299- # Call API to execute deletion
300- client .delete_resource_tag (request )
301- log .info (
302- f"Removed tag from direct connect { resource_name } "
303- f"({ resource_id } ): { key } "
304- )
305- except exceptions .ClientRequestException as e :
306- # Handle API request exceptions
307- log .error (
308- f"Unable to remove tag { key } from direct connect "
309- f"{ resource_name } ({ resource_id } ): "
310- f"{ e .error_msg } (status code: { e .status_code } )"
311- )
312- except Exception as e :
313- # Handle other potential exceptions
314- log .error (
315- f"Unable to remove tag { key } from direct connect "
316- f"{ resource_name } ({ resource_id } ): { str (e )} "
317- )
318-
319- return None
320-
321-
322- # Register TMS tag related filters
323- register_tms_filters (DC .filter_registry )
0 commit comments