google_create_resource.py 5.89 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python
import argparse
import logging
import logging.handlers
import re
import string
import yaml

from subprocess import check_output as cmd
from subprocess import CalledProcessError
from time import sleep


class Resource:

    def __init__(self, args, config):
        self.__dict__.update(args)
        self.config = config
Rob Carleski's avatar
Rob Carleski committed
19
        self.logger = logging.getLogger(__name__)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
        self.resource_id = ''
        _allowed = string.ascii_letters + string.digits
        for char in self.name:
            if char in _allowed:
                self.resource_id += char.lower()

    def create_resource(self):
        try:
            cmd([
                self.config['google']['gam_command'],
                'create',
                'resource',
                self.resource_id,
                self.name,
                'description',
                self.description,
                'type',
                self.resource_type
            ])
            sleep(1)
        except CalledProcessError:
Rob Carleski's avatar
Rob Carleski committed
41
            self.logger.error(
42
43
44
45
46
47
48
49
50
51
52
53
54
55
                'Failed to create resource.',
                extra={'entity': self.name}
            )
            exit(2)

        try:
            resource_info = cmd([
                self.config['google']['gam_command'],
                'info',
                'resource',
                self.resource_id
            ])
            self.email = re.findall(b'Email: (.+)', resource_info)[0]
        except CalledProcessError:
Rob Carleski's avatar
Rob Carleski committed
56
            self.logger.error(
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
                'Failed to fetch resource data after creation.',
                extra={'entity': self.name}
            )
            exit(2)

    def add_resource_owners(self):
        for owner in self.owners:
            try:
                cmd([
                    self.config['google']['gam_command'],
                    'calendar',
                    self.email,
                    'add',
                    'owner',
                    owner
                ])
            except CalledProcessError:
Rob Carleski's avatar
Rob Carleski committed
74
                self.logger.warning(
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
                    'Failed to add {} as calendar owner'.format(owner),
                    extra={'entity': self.name}
                )
                continue

    def strip_global_access(self):
        try:
            cmd([
                self.config['google']['gam_command'],
                'calendar',
                self.email,
                'delete',
                'user',
                'domain'
            ])
            cmd([
                self.config['google']['gam_command'],
                'calendar',
                self.email,
                'delete',
                'user',
                'default'
            ])
        except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
99
            self.logger.warning(
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
                'Unable to remove domain-wide access to resource: {}'.format(
                    e.output
                ),
                extra={'entity': self.name}
            )

    def generate_canned_text(self):
        canned_text = '''
Hello,

Your requested resource calendar has been created. As the requester of
the resource, you and your fellow owners should now see it listed in
your own Google calendar.

Information about this new resource is as follows:

Calendar Name: {}
Calendar Type: {}
Calendar Description: {}
Calendar Owners: {}
Calendar ID: {}

If you have any questions about how to utilize this calendar, please
consult the documentation found at the following link:

http://documentation.its.umich.edu/node/660

If any of the above information is incorrect, please feel free to reply
to this message and your incident will be automatically reopened.'''.format(
            self.name,
            self.resource_type,
            self.description,
            ','.join(self.owners),
            self.email
            )

        print(
            '============================================',
            canned_text
        )


def main():

    helptext = '''examples:
    google-create-resource -n AL1-B1-2510 -o kmoss aaliyah
    google-create-resource --name AL1-B1-2510 --owners kmoss aaliyah
        --type 'Private Office'
    '''

    parser = argparse.ArgumentParser(
        description='Creates a new resource in GSuite',
        epilog=helptext,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        '--name',
        '-n',
        help='The name to assign to the resource.',
        required=True
    )
    parser.add_argument(
        '--owners',
        '-o',
        help='Users to give management access to.',
        nargs='+',
        required=True
    )
    parser.add_argument(
        '--resource_type',
        '-t',
        help='The resource type.'
    )
    parser.add_argument(
        '--description',
        '-d',
        help='A description of the resource.'
    )
    parser.add_argument(
        '--config',
        '-c',
        help='The CAK config to use.',
        default='/etc/collab-admin-kit.yml'
    )
    args = parser.parse_args()

    # Open the CAK Config
    with open(args.config) as stream:
        config = yaml.load(stream, Loader=yaml.BaseLoader)

    # Get the root logger and set the debug level
Rob Carleski's avatar
Rob Carleski committed
191
    logger = logging.getLogger(__name__)
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
    logger.setLevel(logging.DEBUG)

    # Create a syslog handler, set format, and associate.
    sh = logging.handlers.SysLogHandler(
        address='/dev/log',
        facility=config['general']['log_facility']
    )
    formatter = logging.Formatter(config['general']['log_format'])
    sh.setFormatter(formatter)
    logger.addHandler(sh)

    # Create a console handler, set format, and associate.
    ch = logging.StreamHandler()
    formatter = logging.Formatter(config['general']['console_format'])
    ch.setFormatter(formatter)
    logger.addHandler(ch)

    resource = Resource(args, config)
    resource.create_resource()
    resource.add_resource_owners()
    resource.strip_global_access()
    resource.generate_canned_text()


if __name__ == '__main__':
    main()