-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathghpubkey
201 lines (175 loc) · 6.32 KB
/
ghpubkey
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
#!/usr/bin/python
import requests
"""
Ansible module for adding or removing public keys to Github.
The MIT License (MIT)
Copyright (c) 2014 Productsup GmbH, Yorick Terweijden [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
DOCUMENTATION = '''
---
module: ghpubkey
version_added: 1.6
short_description: Adds or removes an SSH public key to Github
description:
- Adds or removes an SSH public key to a Github account
options:
user:
description:
- Github account username
required: true
default: null
aliases: [name]
password:
description:
- Github account password
required: true
default: null
key:
description:
- The SSH public key, as a string
required: true
default: null
title:
description:
- Title under which the Key will be known at Github
required: false
default: null
state:
description:
- Whether the given key should or should not be added or not to the Github account
required: false
choices: [ "present", "absent" ]
default: "present"
author: Yorick Terweijden
'''
EXAMPLES = '''
# Add each SSH Public key collected in the Inventory sub-dir keys to Github
- ghpubkey: user={{github.username}} password={{github.password}} key="{{item}}" title="Ansible imported for {{ ansible_fqdn }}"
with_file: "{{ inventory_dir }}/keys/{{ ansible_fqdn }}.pub"
# Add a single SSH Public Key using the Comment as a title
- ghpubkey: user={{github.username}} password={{github.password}} key="{{ssh_pub_key}}"
'''
class Pubkey(object):
platform = 'Generic'
distribution = None
current_keys = None
module = object
def __new__(cls, *args, **kwargs):
return load_platform_subclass(Pubkey, args, kwargs)
def __init__(self, module):
self.module = module
self.state = module.params['state']
self.name = module.params['name']
self.password = module.params['password']
self.key = module.params['key']
if not self.key:
self.module.fail_json(msg="Key is empty")
self.title = module.params['title']
# select whether we dump additional debug info through syslog
self.syslogging = False
def fetch_current_keys(self):
r = requests.get('https://api.github.com/user/keys', auth=(self.name, self.password))
self.current_keys = r.json()
return r.status_code == requests.codes.ok
def process_key(self):
# copied from authorized_keys
VALID_SSH2_KEY_TYPES = [
'ssh-ed25519',
'ecdsa-sha2-nistp256',
'ecdsa-sha2-nistp384',
'ecdsa-sha2-nistp521',
'ssh-dss',
'ssh-rsa',
]
type, key_string_with_comment = self.key.split(' ', 1)
if type not in VALID_SSH2_KEY_TYPES:
self.module.fail_json(msg="SSH2 Key invalid: %s" % self.key)
key_string_array = key_string_with_comment.split(' ', 1)
if len(key_string_array) == 2:
return type, key_string_array[0], key_string_array[1]
else:
return type, key_string_array[0], None
def key_exists(self):
(type, key_string, comment) = self.process_key()
self.fetch_current_keys()
for key in self.current_keys:
if type+' '+key_string == key[u'key']:
return key[u'id']
def add_key(self):
(type, key_string, comment) = self.process_key()
if self.title:
comment = self.title
payload = {'title': comment, 'key': type+' '+key_string}
r = requests.post('https://api.github.com/user/keys', data=json.dumps(payload), auth=(self.name, self.password))
if r.status_code == requests.codes.created:
out = "Added"
err = None
rc = 1
else:
out = "Adding failed"
err = r.text
rc = None
return rc, out, err
def delete_key(self, id):
r = requests.delete('https://api.github.com/user/keys/' + str(id), auth=(self.name, self.password))
if r.status_code == requests.codes.no_content:
out = "Removed"
err = None
rc = 1
else:
out = "Removing failed"
err = r.ktext
rc = None
return rc, out, err
def main():
module = AnsibleModule(
argument_spec = dict(
state=dict(default='present', choices=['present', 'absent'], type='str'),
name=dict(required=True, aliases=['user','username'], type='str'),
password=dict(required=True, type='str'),
key=dict(required=True, type='str'),
title=dict(required=False, type='str')
),
supports_check_mode=False
)
pubkey = Pubkey(module)
rc = None
out = ''
err = ''
result = {}
result['name'] = pubkey.name
result['state'] = pubkey.state
id = pubkey.key_exists()
if pubkey.state == 'absent':
if id:
(rc, out, err) = pubkey.delete_key(id)
elif pubkey.state == 'present':
if not id:
(rc, out, err) = pubkey.add_key()
if rc is None:
result['changed'] = False
else:
result['changed'] = True
if out:
result['stdout'] = out
if err:
result['stderr'] = err
module.exit_json(**result)
# import module snippets
from ansible.module_utils.basic import *
main()