summaryrefslogtreecommitdiff
path: root/source_control/github_hooks.py
blob: eec7a6f990df712ef3d8d876655a50ec3ef839c5 (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
#!/usr/bin/python
# -*- coding: utf-8 -*-

# (c) 2013, Phillip Gentry <phillip@cx.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

try:
    import json
except ImportError:
    try:
        import simplejson as json
    except ImportError:
        # Let snippet from module_utils/basic.py return a proper error in this case
        pass

import base64

DOCUMENTATION = '''
---
module: github_hooks
short_description: Manages github service hooks.
description:
     - Adds service hooks and removes service hooks that have an error status.
version_added: "1.4"
options:
  user:
    description:
      - Github username.
    required: true
  oauthkey:
    description:
      - The oauth key provided by github. It can be found/generated on github under "Edit Your Profile" >> "Applications" >> "Personal Access Tokens"
    required: true
  repo:
    description:
      - "This is the API url for the repository you want to manage hooks for. It should be in the form of: https://api.github.com/repos/user:/repo:. Note this is different than the normal repo url."
    required: true
  hookurl:
    description:
      - When creating a new hook, this is the url that you want github to post to. It is only required when creating a new hook.
    required: false
  action:
    description:
      - This tells the githooks module what you want it to do.
    required: true
    choices: [ "create", "cleanall", "list", "clean504" ]
  validate_certs:
    description:
      - If C(no), SSL certificates for the target repo will not be validated. This should only be used
        on personally controlled sites using self-signed certificates.
    required: false
    default: 'yes'
    choices: ['yes', 'no']
  content_type:
    description:
      - Content type to use for requests made to the webhook
    required: false
    default: 'json'
    choices: ['json', 'form']

author: "Phillip Gentry, CX Inc (@pcgentry)"
'''

EXAMPLES = '''
# Example creating a new service hook. It ignores duplicates.
- github_hooks:
    action: create
    hookurl: 'http://11.111.111.111:2222'
    user: '{{ gituser }}'
    oauthkey: '{{ oauthkey }}'
    repo: 'https://api.github.com/repos/pcgentry/Github-Auto-Deploy'

# Cleaning all hooks for this repo that had an error on the last update. Since this works for all hooks in a repo it is probably best that this would be called from a handler.
- github_hooks:
    action: cleanall
    user: '{{ gituser }}'
    oauthkey: '{{ oauthkey }}'
    repo: '{{ repo }}'
  delegate_to: localhost
'''

def _list(module, hookurl, oauthkey, repo, user):
    url = "%s/hooks" % repo
    auth = base64.encodestring('%s:%s' % (user, oauthkey)).replace('\n', '')
    headers = {
        'Authorization': 'Basic %s' % auth,
    }
    response, info = fetch_url(module, url, headers=headers)
    if info['status'] != 200:
        return False, ''
    else:
        return False, response.read()

def _clean504(module, hookurl, oauthkey, repo, user):
    current_hooks = _list(hookurl, oauthkey, repo, user)[1]
    decoded = json.loads(current_hooks)

    for hook in decoded:
        if hook['last_response']['code'] == 504:
            # print "Last response was an ERROR for hook:"
            # print hook['id']
            _delete(module, hookurl, oauthkey, repo, user, hook['id'])
            
    return 0, current_hooks

def _cleanall(module, hookurl, oauthkey, repo, user):
    current_hooks = _list(hookurl, oauthkey, repo, user)[1]
    decoded = json.loads(current_hooks)

    for hook in decoded:
        if hook['last_response']['code'] != 200:
            # print "Last response was an ERROR for hook:"
            # print hook['id']
            _delete(module, hookurl, oauthkey, repo, user, hook['id'])
            
    return 0, current_hooks

def _create(module, hookurl, oauthkey, repo, user, content_type):
    url = "%s/hooks" % repo
    values = {
        "active": True,
        "name": "web",
        "config": {
            "url": "%s" % hookurl,
            "content_type": "%s" % content_type
            }
        }
    data = json.dumps(values)
    auth = base64.encodestring('%s:%s' % (user, oauthkey)).replace('\n', '')
    headers = {
        'Authorization': 'Basic %s' % auth,
    }
    response, info = fetch_url(module, url, data=data, headers=headers)
    if info['status'] != 200:
        return 0, '[]'
    else:
        return 0, response.read()

def _delete(module, hookurl, oauthkey, repo, user, hookid):
    url = "%s/hooks/%s" % (repo, hookid)
    auth = base64.encodestring('%s:%s' % (user, oauthkey)).replace('\n', '')
    headers = {
        'Authorization': 'Basic %s' % auth,
    }
    response, info = fetch_url(module, url, data=data, headers=headers, method='DELETE')
    return response.read()

def main():
    module = AnsibleModule(
        argument_spec=dict(
        action=dict(required=True, choices=['list','clean504','cleanall','create']),
        hookurl=dict(required=False),
        oauthkey=dict(required=True, no_log=True),
        repo=dict(required=True),
        user=dict(required=True),
        validate_certs=dict(default='yes', type='bool'),
        content_type=dict(default='json', choices=['json', 'form']),
        )
    )

    action = module.params['action']
    hookurl = module.params['hookurl']
    oauthkey = module.params['oauthkey']
    repo = module.params['repo']
    user = module.params['user']
    content_type = module.params['content_type']

    if action == "list":
        (rc, out) = _list(module, hookurl, oauthkey, repo, user)

    if action == "clean504":
        (rc, out) = _clean504(module, hookurl, oauthkey, repo, user)

    if action == "cleanall":
        (rc, out) = _cleanall(module, hookurl, oauthkey, repo, user)

    if action == "create":
        (rc, out) = _create(module, hookurl, oauthkey, repo, user, content_type)

    if rc != 0:
        module.fail_json(msg="failed", result=out)

    module.exit_json(msg="success", result=out)


# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.urls import *

main()