Skip to content

Commit fdb733b

Browse files
committed
Refactor the module creation and clean up
1 parent fc3efcc commit fdb733b

File tree

2 files changed

+156
-130
lines changed

2 files changed

+156
-130
lines changed

securitycenter/snippets_management_api/security_health_analytics_custom_modules.py

Lines changed: 57 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,14 @@
1414
# See the License for the specific language governing permissions and
1515
# limitations under the License.
1616

17-
import random
18-
import time
19-
from typing import Dict
17+
import uuid
2018

21-
from google.api_core.exceptions import NotFound
19+
from google.api_core.exceptions import GoogleAPICallError, NotFound
2220
from google.cloud import securitycentermanagement_v1
2321

2422

2523
# [START securitycenter_create_security_health_analytics_custom_module]
26-
def create_security_health_analytics_custom_module(parent: str) -> Dict:
24+
def create_security_health_analytics_custom_module(parent: str) -> securitycentermanagement_v1.SecurityHealthAnalyticsCustomModule:
2725
"""
2826
Creates a Security Health Analytics custom module.
2927
@@ -40,57 +38,63 @@ def create_security_health_analytics_custom_module(parent: str) -> Dict:
4038
"""
4139
client = securitycentermanagement_v1.SecurityCenterManagementClient()
4240

43-
# Generate a unique display name
44-
unique_suffix = f"{int(time.time())}_{random.randint(0, 999)}"
45-
display_name = f"python_sample_sha_custom_module_{unique_suffix}"
46-
47-
# Define the custom module configuration
48-
custom_module = {
49-
"display_name": display_name,
50-
"enablement_state": "ENABLED",
51-
"custom_config": {
52-
"description": (
53-
"Sample custom module for testing purposes. This custom module evaluates "
54-
"Cloud KMS CryptoKeys to ensure their rotation period exceeds 30 days (2592000 seconds)."
55-
),
56-
"predicate": {
57-
"expression": "has(resource.rotationPeriod) && (resource.rotationPeriod > duration('2592000s'))",
58-
"title": "Cloud KMS CryptoKey Rotation Period",
41+
try:
42+
# Generate a unique suffix
43+
unique_suffix = str(uuid.uuid4()).replace("-", "_")
44+
# Generate a unique display name
45+
display_name = f"python_sample_sha_custom_module_{unique_suffix}"
46+
47+
# Define the custom module configuration
48+
custom_module = {
49+
"display_name": display_name,
50+
"enablement_state": "ENABLED",
51+
"custom_config": {
5952
"description": (
60-
"Evaluates whether the rotation period of a Cloud KMS CryptoKey exceeds 30 days. "
61-
"A longer rotation period might increase the risk of exposure."
53+
"Sample custom module for testing purposes. This custom module evaluates "
54+
"Cloud KMS CryptoKeys to ensure their rotation period exceeds 30 days (2592000 seconds)."
6255
),
56+
"predicate": {
57+
"expression": "has(resource.rotationPeriod) && (resource.rotationPeriod > duration('2592000s'))",
58+
"title": "Cloud KMS CryptoKey Rotation Period",
59+
"description": (
60+
"Evaluates whether the rotation period of a Cloud KMS CryptoKey exceeds 30 days. "
61+
"A longer rotation period might increase the risk of exposure."
62+
),
63+
},
64+
"recommendation": (
65+
"Review and adjust the rotation period for Cloud KMS CryptoKeys to align with your security policies. "
66+
"Consider setting a shorter rotation period if possible."
67+
),
68+
"resource_selector": {"resource_types": ["cloudkms.googleapis.com/CryptoKey"]},
69+
"severity": "CRITICAL",
70+
"custom_output": {
71+
"properties": [
72+
{
73+
"name": "example_property",
74+
"value_expression": {
75+
"description": "The resource name of the CryptoKey being evaluated.",
76+
"expression": "resource.name",
77+
"location": "global",
78+
"title": "CryptoKey Resource Name",
79+
},
80+
}
81+
]
82+
},
6383
},
64-
"recommendation": (
65-
"Review and adjust the rotation period for Cloud KMS CryptoKeys to align with your security policies. "
66-
"Consider setting a shorter rotation period if possible."
67-
),
68-
"resource_selector": {"resource_types": ["cloudkms.googleapis.com/CryptoKey"]},
69-
"severity": "CRITICAL",
70-
"custom_output": {
71-
"properties": [
72-
{
73-
"name": "example_property",
74-
"value_expression": {
75-
"description": "The resource name of the CryptoKey being evaluated.",
76-
"expression": "resource.name",
77-
"location": "global",
78-
"title": "CryptoKey Resource Name",
79-
},
80-
}
81-
]
82-
},
83-
},
84-
}
84+
}
85+
86+
request = securitycentermanagement_v1.CreateSecurityHealthAnalyticsCustomModuleRequest(
87+
parent=parent,
88+
security_health_analytics_custom_module=custom_module,
89+
)
8590

86-
request = securitycentermanagement_v1.CreateSecurityHealthAnalyticsCustomModuleRequest(
87-
parent=parent,
88-
security_health_analytics_custom_module=custom_module,
89-
)
91+
response = client.create_security_health_analytics_custom_module(request=request)
92+
print(f"Created SecurityHealthAnalytics Custom Module: {response.name}")
93+
return response
9094

91-
response = client.create_security_health_analytics_custom_module(request=request)
92-
print(f"Created Security Health Analytics Custom Module: {response.name}")
93-
return response
95+
except GoogleAPICallError as e:
96+
print(f"Failed to create EventThreatDetectionCustomModule: {e}")
97+
raise
9498
# [END securitycenter_create_security_health_analytics_custom_module]
9599

96100

@@ -210,9 +214,8 @@ def update_security_health_analytics_custom_module(parent: str, module_id: str):
210214
client = securitycentermanagement_v1.SecurityCenterManagementClient()
211215
try:
212216
# Define the custom module configuration
213-
custom_module_name = f"{parent}/securityHealthAnalyticsCustomModules/{module_id}"
214217
custom_module = securitycentermanagement_v1.SecurityHealthAnalyticsCustomModule(
215-
name=custom_module_name,
218+
name=f"{parent}/securityHealthAnalyticsCustomModules/{module_id}",
216219
enablement_state=securitycentermanagement_v1.SecurityHealthAnalyticsCustomModule.EnablementState.DISABLED,
217220
)
218221

@@ -228,7 +231,7 @@ def update_security_health_analytics_custom_module(parent: str, module_id: str):
228231
print(f"Updated Security Health Analytics Custom Module: {response.name}")
229232
return response
230233
except NotFound:
231-
print(f"Custom Module not found: {custom_module_name}")
234+
print(f"Custom Module not found: {custom_module.name}")
232235
raise
233236
except Exception as e:
234237
print(f"An error occurred while updating the custom module: {e}")

0 commit comments

Comments
 (0)