diff --git a/lib/ansible/modules/extras/notification/twilio.py b/lib/ansible/modules/extras/notification/twilio.py index ee12d987e9e..58898b0bc73 100644 --- a/lib/ansible/modules/extras/notification/twilio.py +++ b/lib/ansible/modules/extras/notification/twilio.py @@ -104,10 +104,8 @@ EXAMPLES = ''' # ======================================= # twilio module support methods # -import urllib -import urllib2 - import base64 +import urllib def post_twilio_api(module, account_sid, auth_token, msg, from_number, @@ -120,14 +118,16 @@ def post_twilio_api(module, account_sid, auth_token, msg, from_number, if media_url: data['MediaUrl'] = media_url encoded_data = urllib.urlencode(data) - request = urllib2.Request(URI) + base64string = base64.encodestring('%s:%s' % \ (account_sid, auth_token)).replace('\n', '') - request.add_header('User-Agent', AGENT) - request.add_header('Content-type', 'application/x-www-form-urlencoded') - request.add_header('Accept', 'application/json') - request.add_header('Authorization', 'Basic %s' % base64string) - return urllib2.urlopen(request, encoded_data) + + headers = {'User-Agent': AGENT, + 'Content-type': 'application/x-www-form-urlencoded', + 'Accept': 'application/json', + 'Authorization': 'Basic %s' % base64string, + } + return fetch_url(module, URI, data=encoded_data, headers=headers) # ======================================= @@ -159,14 +159,15 @@ def main(): to_number = [to_number] for number in to_number: - try: - post_twilio_api(module, account_sid, auth_token, msg, + r, info = post_twilio_api(module, account_sid, auth_token, msg, from_number, number, media_url) - except Exception: + if info['status'] != 200: module.fail_json(msg="unable to send message to %s" % number) module.exit_json(msg=msg, changed=False) # import module snippets from ansible.module_utils.basic import * -main() +from ansible.module_utils.urls import * +if __name__ == '__main__': + main()