Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_autoscale_info.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2017 Yuwei Zhou, <[email protected]>
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_autoscale_info
14 version_added: "0.1.2"
15 short_description: Get Azure Auto Scale Setting facts
16 description:
17 - Get facts of Auto Scale Setting.
18
19 options:
20 resource_group:
21 description:
22 - The name of the resource group.
23 required: True
24 type: str
25 name:
26 description:
27 - The name of the Auto Scale Setting.
28 type: str
29 tags:
30 description:
31 - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'.
32 type: list
33 elements: str
34
35 extends_documentation_fragment:
36 - azure.azcollection.azure
37
38 author:
39 - Yuwei Zhou (@yuwzho)
40
41 '''
42
43 EXAMPLES = '''
44 - name: Get instance of Auto Scale Setting
45 azure_rm_autoscale_info:
46 resource_group: myResourceGroup
47 name: auto_scale_name
48
49 - name: List instances of Auto Scale Setting
50 azure_rm_autoscale_info:
51 resource_group: myResourceGroup
52 tags:
53 - key
54 - key:value
55 '''
56
57 RETURN = '''
58 autoscales:
59 description: List of Azure Scale Settings dicts.
60 returned: always
61 type: list
62 sample: [{
63 "enabled": true,
64 "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/microsoft.insights/autoscalesettings/scale",
65 "location": "eastus",
66 "name": "scale",
67 "notifications": [
68 {
69 "custom_emails": [
70 "[email protected]"
71 ],
72 "send_to_subscription_administrator": true,
73 "send_to_subscription_co_administrators": false,
74 "webhooks": []
75 }
76 ],
77 "profiles": [
78 {
79 "count": "1",
80 "max_count": "1",
81 "min_count": "1",
82 "name": "Auto created scale condition 0",
83 "recurrence_days": [
84 "Monday"
85 ],
86 "recurrence_frequency": "Week",
87 "recurrence_hours": [
88 "6"
89 ],
90 "recurrence_mins": [
91 "0"
92 ],
93 "recurrence_timezone": "China Standard Time",
94 "rules": [
95 {
96 "cooldown": 5.0,
97 "dimensions": [
98 {
99 "dimension_name": "AppName",
100 "operator": "Equals",
101 "values": [
102 "App1",
103 "App2"
104 ]
105 }
106 ],
107 "divide_per_instance": true,
108 "metric_namespace": "Fredtest",
109 "direction": "Increase",
110 "metric_name": "Percentage CPU",
111 "metric_resource_uri": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsof
112 t.Compute/virtualMachineScaleSets/myVmss",
113 "operator": "GreaterThan",
114 "statistic": "Average",
115 "threshold": 70.0,
116 "time_aggregation": "Average",
117 "time_grain": 1.0,
118 "time_window": 10.0,
119 "type": "ChangeCount",
120 "value": "1"
121 }
122 ]
123 }
124 ],
125 "target": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachineScale
126 Sets/myVmss"
127 }]
128
129 '''
130
131 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
132 from ansible.module_utils._text import to_native
133
134
135 # duplicated in azure_rm_autoscale
136 def timedelta_to_minutes(time):
137 if not time:
138 return 0
139 return time.days * 1440 + time.seconds / 60.0 + time.microseconds / 60000000.0
140
141
142 def get_enum_value(item):
143 if hasattr(item, 'value'):
144 return to_native(item.value)
145 return to_native(item)
146
147
148 def auto_scale_to_dict(instance):
149 if not instance:
150 return dict()
151 return dict(
152 id=to_native(instance.id or ''),
153 name=to_native(instance.name),
154 location=to_native(instance.location),
155 profiles=[profile_to_dict(p) for p in instance.profiles or []],
156 notifications=[notification_to_dict(n) for n in instance.notifications or []],
157 enabled=instance.enabled,
158 target=to_native(instance.target_resource_uri),
159 tags=instance.tags
160 )
161
162
163 def rule_to_dict(rule):
164 if not rule:
165 return dict()
166 result = dict(metric_name=to_native(rule.metric_trigger.metric_name),
167 metric_resource_uri=to_native(rule.metric_trigger.metric_resource_uri),
168 time_grain=timedelta_to_minutes(rule.metric_trigger.time_grain),
169 statistic=get_enum_value(rule.metric_trigger.statistic),
170 time_window=timedelta_to_minutes(rule.metric_trigger.time_window),
171 time_aggregation=get_enum_value(rule.metric_trigger.time_aggregation),
172 operator=get_enum_value(rule.metric_trigger.operator),
173 threshold=float(rule.metric_trigger.threshold),
174 metric_namespace=rule.metric_trigger.metric_namespace,
175 dimensions=[],
176 divide_per_instance=rule.metric_trigger.divide_per_instance)
177 if rule.metric_trigger.dimensions:
178 for item in rule.metric_trigger.dimensions:
179 result['dimensions'].append(dict(dimension_name=item.dimension_name, operator=item.operator, values=item.values))
180 if rule.scale_action and to_native(rule.scale_action.direction) != 'None':
181 result['direction'] = get_enum_value(rule.scale_action.direction)
182 result['type'] = get_enum_value(rule.scale_action.type)
183 result['value'] = to_native(rule.scale_action.value)
184 result['cooldown'] = timedelta_to_minutes(rule.scale_action.cooldown)
185 return result
186
187
188 def profile_to_dict(profile):
189 if not profile:
190 return dict()
191 result = dict(name=to_native(profile.name),
192 count=to_native(profile.capacity.default),
193 max_count=to_native(profile.capacity.maximum),
194 min_count=to_native(profile.capacity.minimum))
195
196 if profile.rules:
197 result['rules'] = [rule_to_dict(r) for r in profile.rules]
198 if profile.fixed_date:
199 result['fixed_date_timezone'] = profile.fixed_date.time_zone
200 result['fixed_date_start'] = profile.fixed_date.start
201 result['fixed_date_end'] = profile.fixed_date.end
202 if profile.recurrence:
203 if get_enum_value(profile.recurrence.frequency) != 'None':
204 result['recurrence_frequency'] = get_enum_value(profile.recurrence.frequency)
205 if profile.recurrence.schedule:
206 result['recurrence_timezone'] = to_native(str(profile.recurrence.schedule.time_zone))
207 result['recurrence_days'] = [to_native(r) for r in profile.recurrence.schedule.days]
208 result['recurrence_hours'] = [to_native(r) for r in profile.recurrence.schedule.hours]
209 result['recurrence_mins'] = [to_native(r) for r in profile.recurrence.schedule.minutes]
210 return result
211
212
213 def notification_to_dict(notification):
214 if not notification:
215 return dict()
216 return dict(send_to_subscription_administrator=notification.email.send_to_subscription_administrator if notification.email else False,
217 send_to_subscription_co_administrators=notification.email.send_to_subscription_co_administrators if notification.email else False,
218 custom_emails=[to_native(e) for e in notification.email.custom_emails or []],
219 webhooks=[to_native(w.service_url) for w in notification.webhooks or []])
220
221
222 class AzureRMAutoScaleInfo(AzureRMModuleBase):
223 def __init__(self):
224 # define user inputs into argument
225 self.module_arg_spec = dict(
226 resource_group=dict(
227 type='str',
228 required=True
229 ),
230 name=dict(
231 type='str'
232 ),
233 tags=dict(
234 type='list',
235 elements='str'
236 )
237 )
238 # store the results of the module operation
239 self.results = dict()
240 self.resource_group = None
241 self.name = None
242 self.tags = None
243
244 super(AzureRMAutoScaleInfo, self).__init__(self.module_arg_spec, supports_check_mode=True, supports_tags=False, facts_module=True)
245
246 def exec_module(self, **kwargs):
247
248 for key in list(self.module_arg_spec):
249 setattr(self, key, kwargs[key])
250
251 if self.resource_group and self.name:
252 self.results['autoscales'] = self.get()
253 elif self.resource_group:
254 self.results['autoscales'] = self.list_by_resource_group()
255 return self.results
256
257 def get(self):
258 result = []
259 try:
260 instance = self.monitor_autoscale_settings_client.autoscale_settings.get(self.resource_group, self.name)
261 result = [auto_scale_to_dict(instance) if self.has_tags(instance.tags, self.tags) else None]
262 except Exception as ex:
263 self.log('Could not get facts for autoscale {0} - {1}.'.format(self.name, str(ex)))
264 return result
265
266 def list_by_resource_group(self):
267 results = []
268 try:
269 response = self.monitor_autoscale_settings_client.autoscale_settings.list_by_resource_group(self.resource_group)
270 results = [auto_scale_to_dict(item) for item in response if self.has_tags(item.tags, self.tags)]
271 except Exception as ex:
272 self.log('Could not get facts for autoscale {0} - {1}.'.format(self.name, str(ex)))
273 return results
274
275
276 def main():
277 AzureRMAutoScaleInfo()
278
279
280 if __name__ == '__main__':
281 main()