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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
|
#!/usr/bin/python
#
# Copyright (c) 2018 Zim Kalinowski, <zikalino@microsoft.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: azure_rm_cosmosdbaccount
version_added: "0.1.2"
short_description: Manage Azure Database Account instance
description:
- Create, update and delete instance of Azure Database Account.
options:
resource_group:
description:
- Name of an Azure resource group.
required: True
type: str
name:
description:
- Cosmos DB database account name.
required: True
type: str
location:
description:
- The location of the resource group to which the resource belongs.
- Required when I(state=present).
type: str
kind:
description:
- Indicates the type of database account. This can only be set at database account creation.
type: str
choices:
- 'global_document_db'
- 'mongo_db'
- 'parse'
consistency_policy:
description:
- The consistency policy for the Cosmos DB account.
type: dict
suboptions:
default_consistency_level:
description:
- The default consistency level and configuration settings of the Cosmos DB account.
- Required when I(state=present).
type: str
choices:
- 'eventual'
- 'session'
- 'bounded_staleness'
- 'strong'
- 'consistent_prefix'
max_staleness_prefix:
description:
- When used with the Bounded Staleness consistency level, this value represents the number of stale requests tolerated.
- Accepted range for this value is 1 - 2,147,483,647. Required when I(default_consistency_policy=bounded_staleness).
type: int
max_interval_in_seconds:
description:
- When used with the Bounded Staleness consistency level, this value represents the time amount of staleness (in seconds) tolerated.
- Accepted range for this value is 5 - 86400. Required when I(default_consistency_policy=bounded_staleness).
type: int
geo_rep_locations:
description:
- An array that contains the georeplication locations enabled for the Cosmos DB account.
- Required when I(state=present).
type: list
elements: dict
suboptions:
name:
description:
- The name of the region.
type: str
required: true
failover_priority:
description:
- The failover priority of the region. A failover priority of 0 indicates a write region.
- The maximum value for a failover priority = (total number of regions - 1).
- Failover priority values must be unique for each of the regions in which the database account exists.
type: int
required: true
database_account_offer_type:
description:
- Database account offer type, for example I(Standard)
- Required when I(state=present).
type: str
enable_free_tier:
description:
- If enabled the account is free-tier.
type: bool
default: false
version_added: "1.10.0"
ip_range_filter:
description:
- (deprecated) Cosmos DB Firewall support. This value specifies the set of IP addresses or IP address ranges.
- In CIDR form to be included as the allowed list of client IPs for a given database account.
- IP addresses/ranges must be comma separated and must not contain any spaces.
- This value has been deprecated, and will be removed in a later version. Use I(ip_rules) instead.
type: str
ip_rules:
description:
- The IP addresses or IP address ranges in CIDR form to be included as the allowed list of client IPs.
type: list
elements: str
version_added: "1.10.0"
is_virtual_network_filter_enabled:
description:
- Flag to indicate whether to enable/disable Virtual Network ACL rules.
type: bool
enable_automatic_failover:
description:
- Enables automatic failover of the write region in the rare event that the region is unavailable due to an outage.
- Automatic failover will result in a new write region for the account and is chosen based on the failover priorities configured for the account.
type: bool
enable_cassandra:
description:
- Enable Cassandra.
type: bool
enable_table:
description:
- Enable Table.
type: bool
enable_gremlin:
description:
- Enable Gremlin.
type: bool
mongo_version:
description:
- Server version for the MongoDB account, such as c(3.2) or c(4.0).
- Only used when c(kind) = i(mongo_db).
type: str
version_added: "1.10.0"
public_network_access:
description:
- Enables or disables public network access to server.
type: str
default: Enabled
choices:
- Enabled
- Disabled
version_added: "1.10.0"
virtual_network_rules:
description:
- List of Virtual Network ACL rules configured for the Cosmos DB account.
type: list
elements: dict
suboptions:
subnet:
description:
- It can be a string containing resource id of a subnet.
- It can be a dictionary containing 'resource_group', 'virtual_network_name' and 'subnet_name'
type: raw
required: true
ignore_missing_v_net_service_endpoint:
description:
- Create Cosmos DB account without existing virtual network service endpoint.
type: bool
enable_multiple_write_locations:
description:
- Enables the account to write in multiple locations
type: bool
state:
description:
- Assert the state of the Database Account.
- Use C(present) to create or update an Database Account and C(absent) to delete it.
default: present
type: str
choices:
- absent
- present
extends_documentation_fragment:
- azure.azcollection.azure
- azure.azcollection.azure_tags
author:
- Zim Kalinowski (@zikalino)
'''
EXAMPLES = '''
- name: Create Cosmos DB Account - min
azure_rm_cosmosdbaccount:
resource_group: myResourceGroup
name: myDatabaseAccount
location: westus
geo_rep_locations:
- name: southcentralus
failover_priority: 0
database_account_offer_type: Standard
- name: Create Cosmos DB Account - max
azure_rm_cosmosdbaccount:
resource_group: myResourceGroup
name: myDatabaseAccount
location: westus
kind: mongo_db
geo_rep_locations:
- name: southcentralus
failover_priority: 0
database_account_offer_type: Standard
ip_rules:
- 10.10.10.10
enable_multiple_write_locations: true
virtual_network_rules:
- subnet: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVi
rtualNetwork/subnets/mySubnet"
consistency_policy:
default_consistency_level: bounded_staleness
max_staleness_prefix: 10
max_interval_in_seconds: 1000
'''
RETURN = '''
id:
description:
- The unique resource identifier of the database account.
returned: always
type: str
sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.DocumentDB/databaseAccounts/myData
baseAccount"
'''
from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
from ansible.module_utils.common.dict_transformations import _snake_to_camel
try:
from azure.core.polling import LROPoller
from azure.core.exceptions import ResourceNotFoundError
from azure.mgmt.cosmosdb import CosmosDBManagementClient
from ansible.module_utils.six import string_types
except ImportError:
# This is handled in azure_rm_common
pass
class Actions:
NoAction, Create, Update, Delete = range(4)
class AzureRMCosmosDBAccount(AzureRMModuleBase):
"""Configuration class for an Azure RM Database Account resource"""
def __init__(self):
self.module_arg_spec = dict(
resource_group=dict(
type='str',
required=True
),
name=dict(
type='str',
required=True
),
location=dict(
type='str'
),
kind=dict(
type='str',
choices=['global_document_db',
'mongo_db',
'parse']
),
consistency_policy=dict(
type='dict',
options=dict(
default_consistency_level=dict(
type='str',
choices=['eventual',
'session',
'bounded_staleness',
'strong',
'consistent_prefix']
),
max_staleness_prefix=dict(
type='int'
),
max_interval_in_seconds=dict(
type='int'
)
)
),
geo_rep_locations=dict(
type='list',
elements='dict',
options=dict(
name=dict(
type='str',
required=True
),
failover_priority=dict(
type='int',
required=True
)
)
),
database_account_offer_type=dict(
type='str'
),
enable_free_tier=dict(
type='bool',
default=False,
),
ip_range_filter=dict(
type='str'
),
ip_rules=dict(
type='list',
elements='str',
),
is_virtual_network_filter_enabled=dict(
type='bool'
),
enable_automatic_failover=dict(
type='bool'
),
enable_cassandra=dict(
type='bool'
),
enable_table=dict(
type='bool'
),
enable_gremlin=dict(
type='bool'
),
mongo_version=dict(
type='str'
),
public_network_access=dict(
type='str',
default='Enabled',
choices=['Enabled', 'Disabled']
),
virtual_network_rules=dict(
type='list',
elements='dict',
options=dict(
subnet=dict(
type='raw',
required=True
),
ignore_missing_v_net_service_endpoint=dict(
type='bool'
)
)
),
enable_multiple_write_locations=dict(
type='bool'
),
state=dict(
type='str',
default='present',
choices=['present', 'absent']
)
)
self.resource_group = None
self.name = None
self.parameters = dict()
self.results = dict(changed=False)
self.mgmt_client = None
self.state = None
self.to_do = Actions.NoAction
super(AzureRMCosmosDBAccount, self).__init__(derived_arg_spec=self.module_arg_spec,
supports_check_mode=True,
supports_tags=True)
def exec_module(self, **kwargs):
"""Main module execution method"""
for key in list(self.module_arg_spec.keys()) + ['tags']:
if hasattr(self, key):
setattr(self, key, kwargs[key])
elif kwargs[key] is not None:
self.parameters[key] = kwargs[key]
kind = self.parameters.get('kind')
if kind == 'global_document_db':
self.parameters['kind'] = 'GlobalDocumentDB'
elif kind == 'mongo_db':
self.parameters['kind'] = 'MongoDB'
elif kind == 'parse':
self.parameters['kind'] = 'Parse'
ip_range_filter = self.parameters.pop('ip_range_filter', None)
ip_rules = self.parameters.pop('ip_rules', [])
if ip_range_filter:
self.parameters['ip_rules'] = [{"ip_address_or_range": ip} for ip in ip_range_filter.split(",")]
if ip_rules:
# overrides deprecated 'ip_range_filter' parameter
self.parameters['ip_rules'] = [{"ip_address_or_range": ip} for ip in ip_rules]
dict_camelize(self.parameters, ['consistency_policy', 'default_consistency_level'], True)
dict_rename(self.parameters, ['geo_rep_locations', 'name'], 'location_name')
dict_rename(self.parameters, ['geo_rep_locations'], 'locations')
self.parameters['capabilities'] = []
if self.parameters.pop('enable_cassandra', False):
self.parameters['capabilities'].append({'name': 'EnableCassandra'})
if self.parameters.pop('enable_table', False):
self.parameters['capabilities'].append({'name': 'EnableTable'})
if self.parameters.pop('enable_gremlin', False):
self.parameters['capabilities'].append({'name': 'EnableGremlin'})
mongo_version = self.parameters.pop('mongo_version', None)
if kind == 'mongo_db' and mongo_version is not None:
self.parameters['api_properties'] = dict()
self.parameters['api_properties']['server_version'] = mongo_version
for rule in self.parameters.get('virtual_network_rules', []):
subnet = rule.pop('subnet')
if isinstance(subnet, dict):
virtual_network_name = subnet.get('virtual_network_name')
subnet_name = subnet.get('subnet_name')
resource_group_name = subnet.get('resource_group', self.resource_group)
template = "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/virtualNetworks/{2}/subnets/{3}"
subnet = template.format(self.subscription_id, resource_group_name, virtual_network_name, subnet_name)
rule['id'] = subnet
response = None
self.mgmt_client = self.get_mgmt_svc_client(CosmosDBManagementClient,
base_url=self._cloud_environment.endpoints.resource_manager)
resource_group = self.get_resource_group(self.resource_group)
if "location" not in self.parameters:
self.parameters["location"] = resource_group.location
old_response = self.get_databaseaccount()
if not old_response:
self.log("Database Account instance doesn't exist")
if self.state == 'absent':
self.log("Old instance didn't exist")
else:
self.to_do = Actions.Create
else:
self.log("Database Account instance already exists")
if self.state == 'absent':
self.to_do = Actions.Delete
elif self.state == 'present':
old_response['locations'] = old_response['failover_policies']
if not default_compare(self.parameters, old_response, '', self.results):
self.to_do = Actions.Update
if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
self.log("Need to Create / Update the Database Account instance")
if self.check_mode:
self.results['changed'] = True
return self.results
response = self.create_update_databaseaccount()
self.results['changed'] = True
self.log("Creation / Update done")
elif self.to_do == Actions.Delete:
self.log("Database Account instance deleted")
self.results['changed'] = True
if self.check_mode:
return self.results
self.delete_databaseaccount()
else:
self.log("Database Account instance unchanged")
self.results['changed'] = False
response = old_response
if self.state == 'present':
self.results.update({'id': response.get('id', None)})
return self.results
def create_update_databaseaccount(self):
'''
Creates or updates Database Account with the specified configuration.
:return: deserialized Database Account instance state dictionary
'''
self.log("Creating / Updating the Database Account instance {0}".format(self.name))
try:
response = self.mgmt_client.database_accounts.begin_create_or_update(resource_group_name=self.resource_group,
account_name=self.name,
create_update_parameters=self.parameters)
if isinstance(response, LROPoller):
response = self.get_poller_result(response)
except Exception as exc:
self.log('Error attempting to create the Database Account instance.')
self.fail("Error creating the Database Account instance: {0}".format(str(exc)))
return response.as_dict()
def delete_databaseaccount(self):
'''
Deletes specified Database Account instance in the specified subscription and resource group.
:return: True
'''
self.log("Deleting the Database Account instance {0}".format(self.name))
try:
response = self.mgmt_client.database_accounts.begin_delete(resource_group_name=self.resource_group,
account_name=self.name)
if isinstance(response, LROPoller):
response = self.get_poller_result(response)
except Exception as e:
self.log('Error attempting to delete the Database Account instance.')
self.fail("Error deleting the Database Account instance: {0}".format(str(e)))
return True
def get_databaseaccount(self):
'''
Gets the properties of the specified Database Account.
:return: deserialized Database Account instance state dictionary
'''
self.log("Checking if the Database Account instance {0} is present".format(self.name))
found = False
try:
response = self.mgmt_client.database_accounts.get(resource_group_name=self.resource_group,
account_name=self.name)
if not response:
return False
found = True
self.log("Response : {0}".format(response))
self.log("Database Account instance : {0} found".format(response.name))
except ResourceNotFoundError as e:
self.log('Did not find the Database Account instance.')
if found is True:
return response.as_dict()
return False
def default_compare(new, old, path, result):
'''
:return: false if differences are found between old and new.
'''
if new is None:
return True
elif isinstance(new, dict):
if not isinstance(old, dict):
result['compare'] = 'changed [' + path + '] old dict is null'
return False
for k in new.keys():
if not default_compare(new.get(k), old.get(k, None), path + '/' + k, result):
return False
return True
elif isinstance(new, list):
if not isinstance(old, list) or len(new) != len(old):
result['compare'] = 'changed [' + path + '] length is different or null'
return False
elif len(old) == 0:
return True
elif isinstance(old[0], dict):
key = None
if 'id' in old[0] and 'id' in new[0]:
key = 'id'
elif 'name' in old[0] and 'name' in new[0]:
key = 'name'
else:
key = list(old[0])[0]
new = sorted(new, key=lambda x: x.get(key, ''))
old = sorted(old, key=lambda x: x.get(key, ''))
else:
new = sorted(new)
old = sorted(old)
for i in range(len(new)):
if not default_compare(new[i], old[i], path + '/*', result):
return False
return True
else:
if path == '/location' or path.endswith('location_name'):
new = new.replace(' ', '').lower()
old = new.replace(' ', '').lower()
if isinstance(old, string_types) and isinstance(new, string_types):
new = new.lower()
old = old.lower()
if new == old:
return True
else:
result['compare'] = 'changed [' + path + '] ' + str(new) + ' != ' + str(old)
return False
def dict_camelize(d, path, camelize_first):
if isinstance(d, list):
for i in range(len(d)):
dict_camelize(d[i], path, camelize_first)
elif isinstance(d, dict):
if len(path) == 1:
old_value = d.get(path[0], None)
if old_value is not None:
d[path[0]] = _snake_to_camel(old_value, camelize_first)
else:
sd = d.get(path[0], None)
if sd is not None:
dict_camelize(sd, path[1:], camelize_first)
def dict_upper(d, path):
if isinstance(d, list):
for i in range(len(d)):
dict_upper(d[i], path)
elif isinstance(d, dict):
if len(path) == 1:
old_value = d.get(path[0], None)
if old_value is not None:
d[path[0]] = old_value.upper()
else:
sd = d.get(path[0], None)
if sd is not None:
dict_upper(sd, path[1:])
def dict_rename(d, path, new_name):
if isinstance(d, list):
for i in range(len(d)):
dict_rename(d[i], path, new_name)
elif isinstance(d, dict):
if len(path) == 1:
old_value = d.pop(path[0], None)
if old_value is not None:
d[new_name] = old_value
else:
sd = d.get(path[0], None)
if sd is not None:
dict_rename(sd, path[1:], new_name)
def dict_expand(d, path, outer_dict_name):
if isinstance(d, list):
for i in range(len(d)):
dict_expand(d[i], path, outer_dict_name)
elif isinstance(d, dict):
if len(path) == 1:
old_value = d.pop(path[0], None)
if old_value is not None:
d[outer_dict_name] = d.get(outer_dict_name, {})
d[outer_dict_name] = old_value
else:
sd = d.get(path[0], None)
if sd is not None:
dict_expand(sd, path[1:], outer_dict_name)
def main():
"""Main execution"""
AzureRMCosmosDBAccount()
if __name__ == '__main__':
main()
|