Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2017 Zim Kalinowski, <[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_containerregistryreplication
14 version_added: "0.1.2"
15 short_description: Manage Replication instance.
16 description:
17 - Create, update and delete instance of Replication.
18
19 options:
20 resource_group:
21 description:
22 - The name of the resource group to which the container registry belongs.
23 required: True
24 type: str
25 registry_name:
26 description:
27 - The name of the container registry.
28 required: True
29 type: str
30 replication_name:
31 description:
32 - The name of the I(replication).
33 required: True
34 type: str
35 replication:
36 description:
37 - The parameters for creating a replication.
38 type: dict
39 location:
40 description:
41 - Resource location. If not set, location from the resource group will be used as default.
42 type: str
43 state:
44 description:
45 - Assert the state of the Container registery replication.
46 - Use C(present) to create or update Container registery replication and C(absent) to delete it.
47 default: present
48 type: str
49 choices:
50 - absent
51 - present
52
53 extends_documentation_fragment:
54 - azure.azcollection.azure
55
56 author:
57 - "Zim Kalinowski (@zikalino)"
58
59 '''
60
61 EXAMPLES = '''
62 - name: Create (or update) Replication
63 azure_rm_containerregistryreplication:
64 resource_group: myResourceGroup
65 registry_name: myRegistry
66 replication_name: myReplication
67 replication:
68 Key: value
69 location: eastus
70 '''
71
72 RETURN = '''
73 id:
74 description:
75 - The resource ID.
76 returned: always
77 type: str
78 sample: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.ContainerRegistry/registries/myRegistry/r
79 eplications/myReplication"
80 status:
81 description:
82 - The status of the replication at the time the operation was called.
83 returned: always
84 type: str
85 sample: Ready
86 '''
87
88 import time
89 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
90
91 try:
92 from azure.core.exceptions import ResourceNotFoundError
93 from azure.core.polling import LROPoller
94 from azure.mgmt.containerregistry.models import Replication, ReplicationUpdateParameters
95 except ImportError:
96 # This is handled in azure_rm_common
97 pass
98
99
100 def create_replication_dict(replication):
101 if replication is None:
102 return None
103 results = dict(
104 id=replication.id,
105 name=replication.name,
106 location=replication.location,
107 provisioning_state=replication.provisioning_state,
108 tags=replication.tags,
109 status=replication.status.display_status
110 )
111 return results
112
113
114 class Actions:
115 NoAction, Create, Update, Delete = range(4)
116
117
118 class AzureRMReplications(AzureRMModuleBase):
119 """Configuration class for an Azure RM Replication resource"""
120
121 def __init__(self):
122 self.module_arg_spec = dict(
123 resource_group=dict(
124 type='str',
125 required=True
126 ),
127 registry_name=dict(
128 type='str',
129 required=True
130 ),
131 replication_name=dict(
132 type='str',
133 required=True
134 ),
135 replication=dict(
136 type='dict'
137 ),
138 location=dict(
139 type='str'
140 ),
141 state=dict(
142 type='str',
143 default='present',
144 choices=['present', 'absent']
145 )
146 )
147
148 self.resource_group = None
149 self.registry_name = None
150 self.replication_name = None
151 self.location = None
152
153 self.results = dict(changed=False)
154 self.state = None
155 self.to_do = Actions.NoAction
156
157 super(AzureRMReplications, self).__init__(derived_arg_spec=self.module_arg_spec,
158 supports_check_mode=True,
159 supports_tags=False)
160
161 def exec_module(self, **kwargs):
162 """Main module execution method"""
163
164 for key in list(self.module_arg_spec.keys()):
165 if hasattr(self, key):
166 setattr(self, key, kwargs[key])
167
168 old_response = None
169 response = None
170
171 resource_group = self.get_resource_group(self.resource_group)
172
173 if self.location is None:
174 self.location = resource_group.location
175
176 old_response = self.get_replication()
177
178 if not old_response:
179 self.log("Replication instance doesn't exist")
180 if self.state == 'absent':
181 self.log("Old instance didn't exist")
182 else:
183 self.to_do = Actions.Create
184 else:
185 self.log("Replication instance already exists")
186 if self.state == 'absent':
187 self.to_do = Actions.Delete
188 elif self.state == 'present':
189 self.log("Need to check if Replication instance has to be deleted or may be updated")
190 self.to_do = Actions.Update
191
192 if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
193 self.log("Need to Create / Update the Replication instance")
194
195 if self.check_mode:
196 self.results['changed'] = True
197 return self.results
198
199 response = self.create_update_replication()
200
201 if not old_response:
202 self.results['changed'] = True
203 else:
204 self.results['changed'] = old_response.__ne__(response)
205 self.log("Creation / Update done")
206 elif self.to_do == Actions.Delete:
207 self.log("Replication instance deleted")
208 self.results['changed'] = True
209
210 if self.check_mode:
211 return self.results
212
213 self.delete_replication()
214 # make sure instance is actually deleted, for some Azure resources, instance is hanging around
215 # for some time after deletion -- this should be really fixed in Azure
216 while self.get_replication():
217 time.sleep(20)
218 else:
219 self.log("Replication instance unchanged")
220 self.results['changed'] = False
221 response = old_response
222
223 if response:
224 self.results["id"] = response["id"]
225 self.results["status"] = response["status"]
226
227 return self.results
228
229 def create_update_replication(self):
230 '''
231 Creates or updates Replication with the specified configuration.
232
233 :return: deserialized Replication instance state dictionary
234 '''
235 self.log("Creating / Updating the Replication instance {0}".format(self.replication_name))
236
237 try:
238 if self.to_do == Actions.Create:
239 replication = Replication(
240 location=self.location,
241 )
242 response = self.containerregistry_client.replications.begin_create(resource_group_name=self.resource_group,
243 registry_name=self.registry_name,
244 replication_name=self.replication_name,
245 replication=replication)
246 else:
247 update_params = ReplicationUpdateParameters()
248 response = self.containerregistry_client.replications.begin_update(resource_group_name=self.resource_group,
249 registry_name=self.registry_name,
250 replication_name=self.replication_name,
251 replication_update_parameters=update_params)
252 if isinstance(response, LROPoller):
253 response = self.get_poller_result(response)
254
255 except Exception as exc:
256 self.log('Error attempting to create the Replication instance.')
257 self.fail("Error creating the Replication instance: {0}".format(str(exc)))
258 return create_replication_dict(response)
259
260 def delete_replication(self):
261 '''
262 Deletes specified Replication instance in the specified subscription and resource group.
263
264 :return: True
265 '''
266 self.log("Deleting the Replication instance {0}".format(self.replication_name))
267 try:
268 response = self.containerregistry_client.replications.begin_delete(resource_group_name=self.resource_group,
269 registry_name=self.registry_name,
270 replication_name=self.replication_name)
271 self.get_poller_result(response)
272 except Exception as e:
273 self.log('Error attempting to delete the Replication instance.')
274 self.fail("Error deleting the Replication instance: {0}".format(str(e)))
275
276 return True
277
278 def get_replication(self):
279 '''
280 Gets the properties of the specified Replication.
281
282 :return: deserialized Replication instance state dictionary
283 '''
284 self.log("Checking if the Replication instance {0} is present".format(self.replication_name))
285 found = False
286 try:
287 response = self.containerregistry_client.replications.get(resource_group_name=self.resource_group,
288 registry_name=self.registry_name,
289 replication_name=self.replication_name)
290 found = True
291 self.log("Response : {0}".format(response))
292 self.log("Replication instance : {0} found".format(response.name))
293 except ResourceNotFoundError as e:
294 self.log('Did not find the Replication instance: {0}'.format(str(e)))
295 if found is True:
296 return response.as_dict()
297
298 return False
299
300
301 def main():
302 """Main execution"""
303 AzureRMReplications()
304
305
306 if __name__ == '__main__':
307 main()