1#!/usr/local/bin/python3.8
2# coding: utf-8 -*-
3
4# (c) 2017, John Westcott IV <john.westcott.iv@redhat.com>
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
9__metaclass__ = type
10
11
12ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'}
13
14
15DOCUMENTATION = '''
16---
17module: export
18author: "John Westcott IV (@john-westcott-iv)"
19version_added: "3.7.0"
20short_description: export resources from Automation Platform Controller.
21description:
22    - Export assets from Automation Platform Controller.
23options:
24    all:
25      description:
26        - Export all assets
27      type: bool
28      default: 'False'
29    organizations:
30      description:
31        - organization name to export
32      type: str
33    users:
34      description:
35        - user name to export
36      type: str
37    teams:
38      description:
39        - team name to export
40      type: str
41    credential_types:
42      description:
43        - credential type name to export
44      type: str
45    credentials:
46      description:
47        - credential name to export
48      type: str
49    execution_environments:
50      description:
51        - execution environment name to export
52      type: str
53    notification_templates:
54      description:
55        - notification template name to export
56      type: str
57    inventory_sources:
58      description:
59        - inventory soruce to export
60      type: str
61    inventory:
62      description:
63        - inventory name to export
64      type: str
65    projects:
66      description:
67        - project name to export
68      type: str
69    job_templates:
70      description:
71        - job template name to export
72      type: str
73    workflow_job_templates:
74      description:
75        - workflow name to export
76      type: str
77requirements:
78  - "awxkit >= 9.3.0"
79notes:
80  - Specifying a name of "all" for any asset type will export all items of that asset type.
81extends_documentation_fragment: awx.awx.auth
82'''
83
84EXAMPLES = '''
85- name: Export all assets
86  export:
87    all: True
88
89- name: Export all inventories
90  export:
91    inventory: 'all'
92
93- name: Export a job template named "My Template" and all Credentials
94  export:
95    job_template: "My Template"
96    credential: 'all'
97'''
98
99import logging
100from ansible.module_utils.six.moves import StringIO
101from ..module_utils.awxkit import ControllerAWXKitModule
102
103try:
104    from awxkit.api.pages.api import EXPORTABLE_RESOURCES
105
106    HAS_EXPORTABLE_RESOURCES = True
107except ImportError:
108    HAS_EXPORTABLE_RESOURCES = False
109
110
111def main():
112    argument_spec = dict(
113        all=dict(type='bool', default=False),
114        credential_types=dict(type='str'),
115        credentials=dict(type='str'),
116        execution_environments=dict(type='str'),
117        inventory=dict(type='str'),
118        inventory_sources=dict(type='str'),
119        job_templates=dict(type='str'),
120        notification_templates=dict(type='str'),
121        organizations=dict(type='str'),
122        projects=dict(type='str'),
123        teams=dict(type='str'),
124        users=dict(type='str'),
125        workflow_job_templates=dict(type='str'),
126    )
127
128    # We are not going to raise an error here because the __init__ method of ControllerAWXKitModule will do that for us
129    if HAS_EXPORTABLE_RESOURCES:
130        for resource in EXPORTABLE_RESOURCES:
131            argument_spec[resource] = dict(type='str')
132
133    module = ControllerAWXKitModule(argument_spec=argument_spec)
134
135    if not HAS_EXPORTABLE_RESOURCES:
136        module.fail_json(msg="Your version of awxkit does not have import/export")
137
138    # The export process will never change the AWX system
139    module.json_output['changed'] = False
140
141    # The exporter code currently works like the following:
142    #   Empty string == all assets of that type
143    #   Non-Empty string = just one asset of that type (by name or ID)
144    #   Asset type not present or None = skip asset type (unless everything is None, then export all)
145    # Here we are going to setup a dict of values to export
146    export_args = {}
147    for resource in EXPORTABLE_RESOURCES:
148        if module.params.get('all') or module.params.get(resource) == 'all':
149            # If we are exporting everything or we got the keyword "all" we pass in an empty string for this asset type
150            export_args[resource] = ''
151        else:
152            # Otherwise we take either the string or None (if the parameter was not passed) to get one or no items
153            export_args[resource] = module.params.get(resource)
154
155    # Currently the export process does not return anything on error
156    # It simply just logs to Python's logger
157    # Set up a log gobbler to get error messages from export_assets
158    log_capture_string = StringIO()
159    ch = logging.StreamHandler(log_capture_string)
160    for logger_name in ['awxkit.api.pages.api', 'awxkit.api.pages.page']:
161        logger = logging.getLogger(logger_name)
162        logger.setLevel(logging.ERROR)
163        ch.setLevel(logging.ERROR)
164
165    logger.addHandler(ch)
166    log_contents = ''
167
168    # Run the export process
169    try:
170        module.json_output['assets'] = module.get_api_v2_object().export_assets(**export_args)
171        module.exit_json(**module.json_output)
172    except Exception as e:
173        module.fail_json(msg="Failed to export assets {0}".format(e))
174    finally:
175        # Finally, consume the logs in case there were any errors and die if there were
176        log_contents = log_capture_string.getvalue()
177        log_capture_string.close()
178        if log_contents != '':
179            module.fail_json(msg=log_contents)
180
181
182if __name__ == '__main__':
183    main()
184