summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/cloud/azure/azure_rm_containerinstance_facts.py
blob: d278d1698e45a05897c9fb5b08c729b250fd798f (plain)
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
#!/usr/bin/python
#
# Copyright (c) 2017 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


ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}


DOCUMENTATION = '''
---
module: azure_rm_containerinstance_facts
version_added: "2.8"
short_description: Get Azure Container Instance facts.
description:
    - Get facts of Container Instance.

options:
    resource_group:
        description:
            - The name of the resource group.
        required: True
    name:
        description:
            - The name of the container instance.
    tags:
        description:
            - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'.

extends_documentation_fragment:
    - azure

author:
    - "Zim Kalinowski (@zikalino)"

'''

EXAMPLES = '''
  - name: Get specific Container Instance facts
    azure_rm_containerinstance_facts:
      resource_group: resource_group_name
      name: container_group_name

  - name: List Container Instances in a specified resource group name
    azure_rm_containerinstance_facts:
      resource_group: resource_group_name
'''

RETURN = '''
container_groups:
    description: A list of Container Instance dictionaries.
    returned: always
    type: complex
    contains:
        id:
            description:
                - The resource id.
            returned: always
            type: str
            sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/my
                    containers"
        resource_group:
            description:
                - Resource group where the container exists.
            returned: always
            type: str
            sample: testrg
        name:
            description:
                - The resource name.
            returned: always
            type: str
            sample: mycontainers
        location:
            description:
                - The resource location.
            returned: always
            type: str
            sample: westus
        os_type:
            description:
                - The OS type of containers.
            returned: always
            type: str
            sample: linux
        ip_address:
            description:
                - IP address of the container instance.
            returned: always
            type: str
            sample: 173.15.18.1
        ports:
            description:
                - List of ports exposed by the container instance.
            returned: always
            type: list
            sample: [ 80, 81 ]
        containers:
            description:
                - The containers within the container group.
            returned: always
            type: complex
            sample: containers
            contains:
                name:
                    description:
                        - The name of the container instance.
                    returned: always
                    type: str
                    sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/my
                            containers"
                image:
                    description:
                        - The container image name.
                    returned: always
                    type: str
                    sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/my
                            containers"
                memory:
                    description:
                        - The required memory of the containers in GB.
                    returned: always
                    type: float
                    sample: 1.5
                cpu:
                    description:
                        - The required number of CPU cores of the containers.
                    returned: always
                    type: int
                    sample: 1
                ports:
                    description:
                        - List of ports exposed within the container group.
                    returned: always
                    type: list
                    sample: [ 80, 81 ]
        tags:
            description: Tags assigned to the resource. Dictionary of string:string pairs.
            type: dict
            sample: { "tag1": "abc" }
'''

from ansible.module_utils.azure_rm_common import AzureRMModuleBase

try:
    from msrestazure.azure_exceptions import CloudError
    from msrestazure.azure_operation import AzureOperationPoller
    from azure.mgmt.containerinstance import ContainerInstanceManagementClient
    from msrest.serialization import Model
except ImportError:
    # This is handled in azure_rm_common
    pass


class AzureRMContainerInstanceFacts(AzureRMModuleBase):
    def __init__(self):
        # define user inputs into argument
        self.module_arg_spec = dict(
            resource_group=dict(
                type='str',
                required=True
            ),
            name=dict(
                type='str'
            ),
            tags=dict(
                type='list'
            )
        )
        # store the results of the module operation
        self.results = dict(
            changed=False,
            ansible_facts=dict()
        )
        self.resource_group = None
        self.name = None
        super(AzureRMContainerInstanceFacts, self).__init__(self.module_arg_spec, supports_tags=False)

    def exec_module(self, **kwargs):
        for key in self.module_arg_spec:
            setattr(self, key, kwargs[key])

        if (self.name is not None):
            self.results['containerinstances'] = self.get()
        elif (self.resource_group is not None):
            self.results['containerinstances'] = self.list_by_resource_group()
        else:
            self.results['containerinstances'] = self.list_all()
        return self.results

    def get(self):
        response = None
        results = []
        try:
            response = self.containerinstance_client.container_groups.get(resource_group_name=self.resource_group,
                                                                          container_group_name=self.name)
            self.log("Response : {0}".format(response))
        except CloudError as e:
            self.log('Could not get facts for Container Instances.')

        if response is not None and self.has_tags(response.tags, self.tags):
            results.append(self.format_item(response))

        return results

    def list_by_resource_group(self):
        response = None
        results = []
        try:
            response = self.containerinstance_client.container_groups.list_by_resource_group(resource_group_name=self.resource_group)
            self.log("Response : {0}".format(response))
        except CloudError as e:
            self.fail('Could not list facts for Container Instances.')

        if response is not None:
            for item in response:
                if self.has_tags(item.tags, self.tags):
                    results.append(self.format_item(item))

        return results

    def list_all(self):
        response = None
        results = []
        try:
            response = self.containerinstance_client.container_groups.list()
            self.log("Response : {0}".format(response))
        except CloudError as e:
            self.fail('Could not list facts for Container Instances.')

        if response is not None:
            for item in response:
                if self.has_tags(item.tags, self.tags):
                    results.append(self.format_item(item))

        return results

    def format_item(self, item):
        d = item.as_dict()
        containers = d['containers']
        ports = d['ip_address']['ports']
        resource_group = d['id'].split('resourceGroups/')[1].split('/')[0]

        for port_index in range(len(ports)):
            ports[port_index] = ports[port_index]['port']

        for container_index in range(len(containers)):
            old_container = containers[container_index]
            new_container = {
                'name': old_container['name'],
                'image': old_container['image'],
                'memory': old_container['resources']['requests']['memory_in_gb'],
                'cpu': old_container['resources']['requests']['cpu'],
                'ports': []
            }
            for port_index in range(len(old_container['ports'])):
                new_container['ports'].append(old_container['ports'][port_index]['port'])
            containers[container_index] = new_container

        d = {
            'id': d['id'],
            'resource_group': resource_group,
            'name': d['name'],
            'os_type': d['os_type'],
            'ip_address': 'public' if d['ip_address']['type'] == 'Public' else 'none',
            'ports': ports,
            'location': d['location'],
            'containers': containers,
            'tags': d.get('tags', None)
        }
        return d


def main():
    AzureRMContainerInstanceFacts()


if __name__ == '__main__':
    main()