Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_containerinstance_info.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_containerinstance_info
14 version_added: "0.1.2"
15 short_description: Get Azure Container Instance facts
16 description:
17 - Get facts of Container Instance.
18
19 options:
20 resource_group:
21 description:
22 - The name of the resource group.
23 type: str
24 required: True
25 name:
26 description:
27 - The name of the container instance.
28 type: str
29 tags:
30 description:
31 - Limit results by providing of tags. Format tags 'key:value'.
32 type: list
33 elements: str
34
35 extends_documentation_fragment:
36 - azure.azcollection.azure
37
38 author:
39 - Zim Kalinowski (@zikalino)
40
41 '''
42
43 EXAMPLES = '''
44 - name: Get specific Container Instance facts
45 azure_rm_containerinstance_info:
46 resource_group: myResourceGroup
47 name: myContainer
48
49 - name: List Container Instances in a specified resource group name
50 azure_rm_containerinstance_info:
51 resource_group: myResourceGroup
52 tags:
53 - key
54 - key:value
55 '''
56
57 RETURN = '''
58 container_groups:
59 description: A list of Container Instance dictionaries.
60 returned: always
61 type: complex
62 contains:
63 id:
64 description:
65 - The resource id.
66 returned: always
67 type: str
68 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.ContainerInstance/contain
69 erGroups/myContainer"
70 resource_group:
71 description:
72 - Resource group where the container exists.
73 returned: always
74 type: str
75 sample: testrg
76 name:
77 description:
78 - The resource name.
79 returned: always
80 type: str
81 sample: mycontainers
82 location:
83 description:
84 - The resource location.
85 returned: always
86 type: str
87 sample: westus
88 os_type:
89 description:
90 - The OS type of containers.
91 returned: always
92 type: str
93 sample: linux
94 ip_address:
95 description:
96 - IP address of the container instance.
97 returned: always
98 type: str
99 sample: 173.15.18.1
100 dns_name_label:
101 description:
102 - The Dns name label for the IP.
103 returned: always
104 type: str
105 sample: mydomain
106 ports:
107 description:
108 - List of ports exposed by the container instance.
109 returned: always
110 type: list
111 sample: [ 80, 81 ]
112 containers:
113 description:
114 - The containers within the container group.
115 returned: always
116 type: complex
117 sample: containers
118 contains:
119 name:
120 description:
121 - The name of the container instance.
122 returned: always
123 type: str
124 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.ContainerInstance
125 /containerGroups/myContainer"
126 image:
127 description:
128 - The container image name.
129 returned: always
130 type: str
131 sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.ContainerInstance
132 /containerGroups/myContainer"
133 memory:
134 description:
135 - The required memory of the containers in GB.
136 returned: always
137 type: float
138 sample: 1.5
139 cpu:
140 description:
141 - The required number of CPU cores of the containers.
142 returned: always
143 type: int
144 sample: 1
145 ports:
146 description:
147 - List of ports exposed within the container group.
148 returned: always
149 type: list
150 sample: [ 80, 81 ]
151 commands:
152 description:
153 - List of commands to execute within the container instance in exec form.
154 returned: always
155 type: list
156 sample: [ "pip install abc" ]
157 volume_mounts:
158 description:
159 - The list of volumes mounted in container instance
160 returned: If volumes mounted in container instance
161 type: list
162 sample: [
163 {
164 "mount_path": "/mnt/repo",
165 "name": "myvolume1"
166 }
167 ]
168 environment_variables:
169 description:
170 - List of container environment variables.
171 type: complex
172 contains:
173 name:
174 description:
175 - Environment variable name.
176 type: str
177 value:
178 description:
179 - Environment variable value.
180 type: str
181 subnet_ids:
182 description:
183 - The subnet resource IDs for a container group.
184 type: list
185 returned: always
186 sample: [{'id': "/subscriptions/xxx-xxx/resourceGroups/myRG/providers/Microsoft.Network/virtualNetworks/vnetrpfx/subnets/subrpfx"}]
187 volumes:
188 description: The list of Volumes that can be mounted by container instances
189 returned: If container group has volumes
190 type: list
191 sample: [
192 {
193 "git_repo": {
194 "repository": "https://github.com/Azure-Samples/aci-helloworld.git"
195 },
196 "name": "myvolume1"
197 }
198 ]
199 identity:
200 description:
201 - Identity for the Server.
202 type: complex
203 returned: when available
204 contains:
205 type:
206 description:
207 - Type of the managed identity
208 returned: always
209 sample: UserAssigned
210 type: str
211 user_assigned_identities:
212 description:
213 - User Assigned Managed Identities and its options
214 returned: always
215 type: complex
216 contains:
217 id:
218 description:
219 - Dict of the user assigned identities IDs associated to the Resource
220 returned: always
221 type: dict
222 elements: dict
223 tags:
224 description: Tags assigned to the resource. Dictionary of string:string pairs.
225 type: dict
226 sample: { "tag1": "abc" }
227 '''
228
229 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
230 from ansible.module_utils.common.dict_transformations import _camel_to_snake
231
232 try:
233 from azure.core.exceptions import ResourceNotFoundError
234 except ImportError:
235 # This is handled in azure_rm_common
236 pass
237
238
239 class AzureRMContainerInstanceInfo(AzureRMModuleBase):
240 def __init__(self):
241 # define user inputs into argument
242 self.module_arg_spec = dict(
243 resource_group=dict(
244 type='str',
245 required=True
246 ),
247 name=dict(
248 type='str'
249 ),
250 tags=dict(
251 type='list',
252 elements='str'
253 )
254 )
255 # store the results of the module operation
256 self.results = dict(
257 changed=False,
258 )
259 self.resource_group = None
260 self.name = None
261 self.tags = None
262
263 super(AzureRMContainerInstanceInfo, self).__init__(self.module_arg_spec,
264 supports_check_mode=True,
265 supports_tags=False,
266 facts_module=True)
267
268 def exec_module(self, **kwargs):
269
270 for key in self.module_arg_spec:
271 setattr(self, key, kwargs[key])
272
273 if (self.name is not None):
274 self.results['containerinstances'] = self.get()
275 elif (self.resource_group is not None):
276 self.results['containerinstances'] = self.list_by_resource_group()
277 else:
278 self.results['containerinstances'] = self.list_all()
279 return self.results
280
281 def get(self):
282 response = None
283 results = []
284 try:
285 response = self.containerinstance_client.container_groups.get(resource_group_name=self.resource_group,
286 container_group_name=self.name)
287 self.log("Response : {0}".format(response))
288 except ResourceNotFoundError as e:
289 self.log('Could not get facts for Container Instances.')
290
291 if response is not None and self.has_tags(response.tags, self.tags):
292 results.append(self.format_item(response))
293
294 return results
295
296 def list_by_resource_group(self):
297 response = None
298 results = []
299 try:
300 response = self.containerinstance_client.container_groups.list_by_resource_group(resource_group_name=self.resource_group)
301 self.log("Response : {0}".format(response))
302 except Exception as e:
303 self.fail('Could not list facts for Container Instances.')
304
305 if response is not None:
306 for item in response:
307 if self.has_tags(item.tags, self.tags):
308 results.append(self.format_item(item))
309
310 return results
311
312 def list_all(self):
313 response = None
314 results = []
315 try:
316 response = self.containerinstance_client.container_groups.list()
317 self.log("Response : {0}".format(response))
318 except Exception as e:
319 self.fail('Could not list facts for Container Instances.')
320
321 if response is not None:
322 for item in response:
323 if self.has_tags(item.tags, self.tags):
324 results.append(self.format_item(item))
325
326 return results
327
328 def format_item(self, item):
329 d = item.as_dict()
330 containers = d['containers']
331 ports = d['ip_address']['ports'] if 'ip_address' in d else []
332 resource_group = d['id'].split('resourceGroups/')[1].split('/')[0]
333
334 for port_index in range(len(ports)):
335 ports[port_index] = ports[port_index]['port']
336
337 for container_index in range(len(containers)):
338 old_container = containers[container_index]
339 new_container = {
340 'name': old_container['name'],
341 'image': old_container['image'],
342 'memory': old_container['resources']['requests']['memory_in_gb'],
343 'cpu': old_container['resources']['requests']['cpu'],
344 'ports': [],
345 'commands': old_container.get('command'),
346 'environment_variables': old_container.get('environment_variables'),
347 'volume_mounts': []
348 }
349 for port_index in range(len(old_container['ports'])):
350 new_container['ports'].append(old_container['ports'][port_index]['port'])
351 if 'volume_mounts' in old_container:
352 for volume_mount_index in range(len(old_container['volume_mounts'])):
353 new_container['volume_mounts'].append(old_container['volume_mounts'][volume_mount_index])
354 containers[container_index] = new_container
355
356 d = {
357 'id': d['id'],
358 'resource_group': resource_group,
359 'name': d['name'],
360 'os_type': d['os_type'],
361 'dns_name_label': d['ip_address'].get('dns_name_label'),
362 'ip_address': d['ip_address']['ip'] if 'ip_address' in d else '',
363 'ports': ports,
364 'location': d['location'],
365 'containers': containers,
366 'restart_policy': _camel_to_snake(d.get('restart_policy')) if d.get('restart_policy') else None,
367 'tags': d.get('tags', None),
368 'subnet_ids': d.get('subnet_ids', None),
369 'volumes': d['volumes'] if 'volumes' in d else [],
370 'identity': d.get('identity', None)
371 }
372 return d
373
374
375 def main():
376 AzureRMContainerInstanceInfo()
377
378
379 if __name__ == '__main__':
380 main()