1#!/usr/bin/python
2#
3# Copyright (c) 2017 Yuwei Zhou, <yuwzho@microsoft.com>
4#
5# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7from __future__ import absolute_import, division, print_function
8__metaclass__ = type
9
10
11ANSIBLE_METADATA = {'metadata_version': '1.1',
12                    'status': ['preview'],
13                    'supported_by': 'community'}
14
15
16DOCUMENTATION = '''
17---
18module: azure_rm_automationaccount_info
19version_added: '2.9'
20short_description: Get Azure automation account facts
21description:
22    - Get facts of automation account.
23
24options:
25    resource_group:
26        description:
27            - The name of the resource group.
28        type: str
29        required: True
30    name:
31        description:
32            - The name of the automation account.
33        type: str
34    tags:
35        description:
36            - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'.
37        type: list
38    list_statistics:
39        description:
40            - List statistics details for a automation account.
41            - Note this will cost network overhead, suggest only used when I(name) set.
42        type: bool
43    list_usages:
44        description:
45            - List usage details for a automation account.
46            - Note this will cost network overhead, suggest only used when I(name) set.
47        type: bool
48    list_keys:
49        description:
50            - List keys for a automation account.
51            - Note this will cost network overhead, suggest only used when I(name) set.
52        type: bool
53
54extends_documentation_fragment:
55    - azure
56
57author:
58    - Yuwei Zhou (@yuwzho)
59
60'''
61
62EXAMPLES = '''
63- name: Get details of an automation account
64  azure_rm_automationaccount_info:
65      name: Testing
66      resource_group: myResourceGroup
67      list_statistics: yes
68      list_usages: yes
69      list_keys: yes
70
71- name: List automation account in a resource group
72  azure_rm_automationaccount_info:
73      resource_group: myResourceGroup
74
75- name: List automation account in a resource group
76  azure_rm_automationaccount_info:
77'''
78
79RETURN = '''
80automation_accounts:
81    description:
82        - List of automation account dicts.
83    returned: always
84    type: complex
85    contains:
86        id:
87            description:
88                - Resource ID.
89            type: str
90            returned: always
91            sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups
92                     /myResourceGroup/providers/Microsoft.Automation/automationAccounts/Testing"
93        resource_group:
94            description:
95                - Resource group name.
96            type: str
97            returned: always
98            sample: myResourceGroup
99        name:
100            description:
101                - Resource name.
102            type: str
103            returned: always
104            sample: Testing
105        location:
106            description:
107                - Resource location.
108            type: str
109            returned: always
110            sample: eastus
111        creation_time:
112            description:
113                - Resource creation date time.
114            type: str
115            returned: always
116            sample: "2019-04-26T02:55:16.500Z"
117        last_modified_time:
118            description:
119                - Resource last modified date time.
120            type: str
121            returned: always
122            sample: "2019-04-26T02:55:16.500Z"
123        state:
124            description:
125                - Resource state.
126            type: str
127            returned: always
128            sample: ok
129        keys:
130            description:
131                - Resource keys.
132            type: complex
133            returned: always
134            contains:
135                key_name:
136                    description:
137                        - Name of the key.
138                    type: str
139                    returned: always
140                    sample: Primary
141                permissions:
142                    description:
143                        - Permission of the key.
144                    type: str
145                    returned: always
146                    sample: Full
147                value:
148                    description:
149                        - Value of the key.
150                    type: str
151                    returned: always
152                    sample: "MbepKTO6IyGwml0GaKBkKN"
153        statistics:
154            description:
155                - Resource statistics.
156            type: complex
157            returned: always
158            contains:
159                counter_property:
160                    description:
161                        - Property value of the statistic.
162                    type: str
163                    returned: always
164                    sample: New
165                counter_value:
166                    description:
167                        - Value of the statistic.
168                    type: int
169                    returned: always
170                    sample: 0
171                end_time:
172                    description:
173                        - EndTime of the statistic.
174                    type: str
175                    returned: always
176                    sample: "2019-04-26T06:29:43.587518Z"
177                id:
178                    description:
179                        - ID of the statistic.
180                    type: str
181                    returned: always
182                    sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups
183                             /myResourceGroup/providers/Microsoft.Automation/automationAccounts/Testing/statistics/New"
184                start_time:
185                    description:
186                        - StartTime of the statistic.
187                    type: str
188                    returned: always
189                    sample: "2019-04-26T06:29:43.587518Z"
190        usages:
191            description:
192                - Resource usages.
193            type: complex
194            returned: always
195            contains:
196                current_value:
197                    description:
198                        - Current usage.
199                    type: float
200                    returned: always
201                    sample: 0.0
202                limit:
203                    description:
204                        - Max limit, C(-1) for unlimited.
205                    type: int
206                    returned: always
207                    sample: -1
208                name:
209                    description:
210                        - Usage counter name.
211                    type: complex
212                    returned: always
213                    contains:
214                        localized_value:
215                            description:
216                                - Localized name.
217                            type: str
218                            returned: always
219                            sample: "SubscriptionUsage"
220                        value:
221                            description:
222                                - Name value.
223                            type: str
224                            returned: always
225                            sample: "SubscriptionUsage"
226                unit:
227                    description:
228                        - Usage unit name.
229                    type: str
230                    returned: always
231                    sample: "Minute"
232                throttle_status:
233                    description:
234                        - Usage throttle status.
235                    type: str
236                    returned: always
237                    sample: "NotThrottled"
238
239'''
240
241from ansible.module_utils.azure_rm_common import AzureRMModuleBase
242
243try:
244    from msrestazure.tools import parse_resource_id
245except ImportError:
246    pass
247
248
249class AzureRMAutomationAccountInfo(AzureRMModuleBase):
250    def __init__(self):
251        # define user inputs into argument
252        self.module_arg_spec = dict(
253            resource_group=dict(
254                type='str',
255                required=True
256            ),
257            name=dict(
258                type='str'
259            ),
260            tags=dict(
261                type='list'
262            ),
263            list_statistics=dict(
264                type='bool'
265            ),
266            list_usages=dict(
267                type='bool'
268            ),
269            list_keys=dict(
270                type='bool'
271            )
272        )
273        # store the results of the module operation
274        self.results = dict()
275        self.resource_group = None
276        self.name = None
277        self.tags = None
278        self.list_statistics = None
279        self.list_usages = None
280        self.list_keys = None
281
282        super(AzureRMAutomationAccountInfo, self).__init__(self.module_arg_spec, supports_tags=False, facts_module=True)
283
284    def exec_module(self, **kwargs):
285
286        is_old_facts = self.module._name == 'azure_rm_automationaccount_facts'
287        if is_old_facts:
288            self.module.deprecate("The 'azure_rm_automationaccount_facts' module has been renamed to 'azure_rm_automationaccount_info'", version='2.13')
289
290        for key in list(self.module_arg_spec):
291            setattr(self, key, kwargs[key])
292
293        if self.resource_group and self.name:
294            accounts = [self.get()]
295        elif self.resource_group:
296            accounts = self.list_by_resource_group()
297        else:
298            accounts = self.list_all()
299        self.results['automation_accounts'] = [self.to_dict(x) for x in accounts if self.has_tags(x.tags, self.tags)]
300        return self.results
301
302    def to_dict(self, account):
303        if not account:
304            return None
305        id_dict = parse_resource_id(account.id)
306        result = account.as_dict()
307        result['resource_group'] = id_dict['resource_group']
308        if self.list_statistics:
309            result['statistics'] = self.get_statics(id_dict['resource_group'], account.name)
310        if self.list_usages:
311            result['usages'] = self.get_usages(id_dict['resource_group'], account.name)
312        if self.list_keys:
313            result['keys'] = self.list_account_keys(id_dict['resource_group'], account.name)
314        return result
315
316    def get(self):
317        try:
318            return self.automation_client.automation_account.get(self.resource_group, self.name)
319        except self.automation_models.ErrorResponseException as exc:
320            self.fail('Error when getting automation account {0}: {1}'.format(self.name, exc.message))
321
322    def list_by_resource_group(self):
323        result = []
324        try:
325            resp = self.automation_client.automation_account.list_by_resource_group(self.resource_group)
326            while True:
327                result.append(resp.next())
328        except StopIteration:
329            pass
330        except self.automation_models.ErrorResponseException as exc:
331            self.fail('Error when listing automation account in resource group {0}: {1}'.format(self.resource_group, exc.message))
332        return result
333
334    def list_all(self):
335        result = []
336        try:
337            resp = self.automation_client.automation_account.list()
338            while True:
339                result.append(resp.next())
340        except StopIteration:
341            pass
342        except self.automation_models.ErrorResponseException as exc:
343            self.fail('Error when listing automation account: {0}'.format(exc.message))
344        return result
345
346    def get_statics(self, resource_group, name):
347        result = []
348        try:
349            resp = self.automation_client.statistics.list_by_automation_account(resource_group, name)
350            while True:
351                result.append(resp.next().as_dict())
352        except StopIteration:
353            pass
354        except self.automation_models.ErrorResponseException as exc:
355            self.fail('Error when getting statics for automation account {0}/{1}: {2}'.format(resource_group, name, exc.message))
356        return result
357
358    def get_usages(self, resource_group, name):
359        result = []
360        try:
361            resp = self.automation_client.usages.list_by_automation_account(resource_group, name)
362            while True:
363                result.append(resp.next().as_dict())
364        except StopIteration:
365            pass
366        except self.automation_models.ErrorResponseException as exc:
367            self.fail('Error when getting usage for automation account {0}/{1}: {2}'.format(resource_group, name, exc.message))
368        return result
369
370    def list_account_keys(self, resource_group, name):
371        try:
372            resp = self.automation_client.keys.list_by_automation_account(resource_group, name)
373            return [x.as_dict() for x in resp.keys]
374        except self.automation_models.ErrorResponseException as exc:
375            self.fail('Error when listing keys for automation account {0}/{1}: {2}'.format(resource_group, name, exc.message))
376
377
378def main():
379    AzureRMAutomationAccountInfo()
380
381
382if __name__ == '__main__':
383    main()
384