├── .gitignore ├── .travis.yml ├── CHANGES.md ├── LICENSE ├── README.md ├── defaults └── main.yml ├── files └── usr │ └── local │ └── bin │ └── acme_tiny ├── handlers └── main.yml ├── meta └── main.yml ├── tasks └── main.yml ├── templates └── usr │ └── local │ └── acme-tiny │ └── renew_certificate.sh.j2 └── tests └── main.yml /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | */**.DS_Store 3 | ._* 4 | .*.sw* 5 | *~ 6 | .idea/ 7 | 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | sudo: required 4 | 5 | env: 6 | - distro: 'ubuntu1604' 7 | init: '/lib/systemd/systemd' 8 | run_opts: '--privileged --volume=/sys/fs/cgroup:/sys/fs/cgroup:ro' 9 | - distro: 'debian8' 10 | init: '/lib/systemd/systemd' 11 | run_opts: '--privileged --volume=/sys/fs/cgroup:/sys/fs/cgroup:ro' 12 | 13 | services: 14 | - docker 15 | 16 | before_install: 17 | - 'docker pull geerlingguy/docker-${distro}-ansible:latest' 18 | 19 | script: 20 | - container_id=$(mktemp) 21 | - > 22 | docker run 23 | --detach 24 | --volume="${PWD}":/etc/ansible/roles/this_role:ro ${run_opts} 25 | geerlingguy/docker-${distro}-ansible:latest "${init}" > "${container_id}" 26 | 27 | - > 28 | docker exec --tty "$(cat ${container_id})" env TERM=xterm 29 | ansible-playbook /etc/ansible/roles/this_role/tests/main.yml 30 | --syntax-check 31 | -------------------------------------------------------------------------------- /CHANGES.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ### v0.3.2 4 | 5 | *Released: January 29th 2020* 6 | 7 | - Update acme_tiny to its latest version 8 | - Switch from `--ca` to `--directory-url` 9 | - Fix `KeyError: newAccount` error 10 | - Fix error 104 related to creating a new-nonce 11 | 12 | ### v0.3.1 13 | 14 | *Released: November 9th 2019* 15 | 16 | - Fix README to reference the correct ACME v2 API endpoints 17 | 18 | ### v0.3.0 19 | 20 | *Released: November 9th 2019* 21 | 22 | - Update to using the ACME v2 API since v1 is on its way to being deprecated 23 | 24 | ### v0.2.3 25 | 26 | *Released: November 19th 2017* 27 | 28 | - Update Agreement URL in acme-tiny to reflect the latest Let's Encrypt changes 29 | 30 | ### v0.2.2 31 | 32 | *Released: January 23rd 2017* 33 | 34 | - Add `sudo` when restarting web service to pick up the changes 35 | 36 | ### v0.2.1 37 | 38 | *Released: December 22nd 2016* 39 | 40 | - Fix "Scheme missing" wget v1.16 issue in renew script 41 | - Fix `acme_tiny` path not existing in the renew script 42 | 43 | ### v0.2.0 44 | 45 | *Released: November 2nd 2016* 46 | 47 | - Add syntax test (due to not being able to mock acme-tiny easily) 48 | - Remove unused root CA URL 49 | - Use a more friendly cron syntax 50 | 51 | ### v0.1.0 52 | 53 | *Released: October 27th 2016* 54 | 55 | - Initial release 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Nick Janetakis nick.janetakis@gmail.com 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the 7 | 'Software'), to deal in the Software without restriction, including 8 | without limitation the rights to use, copy, modify, merge, publish, 9 | distribute, sublicense, and/or sell copies of the Software, and to 10 | permit persons to whom the Software is furnished to do so, subject to 11 | the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 21 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 22 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## What is ansible-letsencrypt? [![Build Status](https://secure.travis-ci.org/nickjj/ansible-letsencrypt.png)](http://travis-ci.org/nickjj/ansible-letsencrypt) 2 | 3 | It is an [Ansible](http://www.ansible.com/home) role to generate and automate 4 | renewal for Let's Encrypt SSL certificates. It uses 5 | [acme-tiny](https://github.com/diafygi/acme-tiny). 6 | 7 | ##### Supported platforms: 8 | 9 | - Ubuntu 16.04 LTS (Xenial) 10 | - Debian 8 (Jessie) 11 | 12 | ### What problem does it solve and why is it useful? 13 | 14 | Let's Encrypt allows you to create free SSL certificates. They have a short 15 | half-life and must be renewed every 90 days or they will expire. 16 | 17 | Having to manually keep track of renewals is an excellent way to forget by 18 | accident so this role will do everything for you. 19 | 20 | Feel free to use it with any web server configuration you want. If you 21 | want a near zero configuration nginx role to go along with this role then check 22 | out my https://github.com/nickjj/ansible-nginx role. 23 | 24 | ## Role variables 25 | 26 | Below is a list of default values along with a description of what they do. 27 | 28 | ``` 29 | --- 30 | 31 | # A list of domain names to register certificates for. This has a limit of 100. 32 | # The first item in the list will end up being the file name, for example: 33 | # letsencrypt_domains: ['example.com', 'www.example.com'] 34 | # The above will create example.com.pem and example.com.key files that work for 35 | # both the root domain and the www sub-domain. 36 | letsencrypt_domains: [] 37 | 38 | # Which web server service name needs to get restarted at the end of the run? 39 | letsencrypt_restart_service_name: 'nginx' 40 | 41 | # Installation paths. 42 | letsencrypt_install_path: '/usr/local/acme-tiny' 43 | letsencrypt_challenge_path: '/usr/share/nginx/challenges/.well-known/acme-challenge' 44 | letsencrypt_certificate_path: '/etc/nginx/ssl' 45 | letsencrypt_log_path: '/var/log/acme-tiny' 46 | 47 | # Generated private keys and certificates. 48 | letsencrypt_account_key_path: '{{ letsencrypt_install_path }}/account.key' 49 | letsencrypt_domain_csr_path: '{{ letsencrypt_install_path }}/{{ letsencrypt_domains[0] }}.csr' 50 | letsencrypt_valid_certificate_path: '{{ letsencrypt_install_path }}/{{ letsencrypt_domains[0] }}.crt' 51 | 52 | # Final generated private key and certificate. 53 | letsencrypt_domain_key_path: '{{ letsencrypt_certificate_path }}/{{ letsencrypt_domains[0] }}.key' 54 | letsencrypt_chained_pem_path: '{{ letsencrypt_certificate_path }}/{{ letsencrypt_domains[0] }}.pem' 55 | 56 | # Locations of the intermediate certificate used in the chain. 57 | letsencrypt_intermediate_url: 'https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem' 58 | 59 | # By default we'll use the staging server endpoint so that you're forced to 60 | # explicitly set this when you're ready for production. 61 | # 62 | # For production, set this to: 63 | # letsencrypt_default_ca: 'https://acme-v02.api.letsencrypt.org/directory' 64 | letsencrypt_default_ca: 'https://acme-staging-v02.api.letsencrypt.org/directory' 65 | 66 | # How often should we try to renew certificates? Default is once per month. 67 | letsencrypt_cron_renew: ['0', '0', '1', '*', '*'] 68 | 69 | # When set to True this will delete all private keys, CSRs and certificates. 70 | # You would use this when you want to force create new certificates, such as 71 | # adding a new sub-domain to your certificate file. 72 | # 73 | # Don't always keep this enabled or you'll likely run into rate limits. 74 | letsencrypt_force_reset_all: False 75 | ``` 76 | 77 | ## Example playbook 78 | 79 | For the sake of this example let's assume you have a group called **app** and 80 | you have a typical `site.yml` file. 81 | 82 | To use this role edit your `site.yml` file to look something like this: 83 | 84 | ``` 85 | --- 86 | 87 | - name: Configure app server(s) 88 | hosts: app 89 | become: True 90 | 91 | roles: 92 | - { role: nickjj.letsencrypt, tags: letsencrypt } 93 | ``` 94 | 95 | Let's say you want to generate certs for blog.example.com in production. 96 | You can do this by opening or creating `group_vars/app.yml` which is located 97 | relative to your `inventory` directory and then making it look like this: 98 | 99 | ``` 100 | --- 101 | 102 | letsencrypt_domains: ['blog.example.com'] 103 | letsencrypt_default_ca: 'https://acme-staging-v02.api.letsencrypt.org/directory' 104 | ``` 105 | 106 | ## Revoking certificates 107 | 108 | Certificates expire in 90 days and you can issue new certificates at will so 109 | there's no way to revoke them built into this role. 110 | 111 | If you really need to revoke them then I recommend checking out 112 | [this project](https://github.com/diafygi/letsencrypt-nosudo) because it 113 | includes a way to revoke certificates and is made by the same author as acme-tiny. 114 | 115 | ## Installation 116 | 117 | `$ ansible-galaxy install nickjj.letsencrypt` 118 | 119 | ## Ansible Galaxy 120 | 121 | You can find it on the official 122 | [Ansible Galaxy](https://galaxy.ansible.com/nickjj/letsencrypt/) if you want to 123 | rate it. 124 | 125 | ## License 126 | 127 | MIT 128 | 129 | ## Special thanks 130 | 131 | Thanks to [Maciej Delmanowski](https://twitter.com/drybjed) for helping me debug 132 | a few tricky issues with this role. He is the creator of [DebOps](https://debops.org/). 133 | -------------------------------------------------------------------------------- /defaults/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | letsencrypt_domains: [] 4 | 5 | letsencrypt_restart_service_name: 'nginx' 6 | 7 | letsencrypt_install_path: '/usr/local/acme-tiny' 8 | letsencrypt_challenge_path: '/usr/share/nginx/challenges/.well-known/acme-challenge' 9 | letsencrypt_certificate_path: '/etc/nginx/ssl' 10 | letsencrypt_log_path: '/var/log/acme-tiny' 11 | 12 | letsencrypt_account_key_path: '{{ letsencrypt_install_path }}/account.key' 13 | letsencrypt_domain_csr_path: '{{ letsencrypt_install_path }}/{{ letsencrypt_domains[0] }}.csr' 14 | letsencrypt_valid_certificate_path: '{{ letsencrypt_install_path }}/{{ letsencrypt_domains[0] }}.crt' 15 | letsencrypt_domain_key_path: '{{ letsencrypt_certificate_path }}/{{ letsencrypt_domains[0] }}.key' 16 | letsencrypt_chained_pem_path: '{{ letsencrypt_certificate_path }}/{{ letsencrypt_domains[0] }}.pem' 17 | 18 | letsencrypt_intermediate_url: 'https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem' 19 | letsencrypt_default_ca: 'https://acme-staging-v02.api.letsencrypt.org/directory' 20 | 21 | letsencrypt_cron_renew: ['0', '0', '1', '*', '*'] 22 | 23 | letsencrypt_force_reset_all: False 24 | -------------------------------------------------------------------------------- /files/usr/local/bin/acme_tiny: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # {{ ansible_managed }} 4 | # Taken from https://github.com/diafygi/acme-tiny on Jan 29th 2020 5 | # 6 | # Copyright Daniel Roesler, under MIT license, see LICENSE at github.com/diafygi/acme-tiny 7 | 8 | import argparse, subprocess, json, os, sys, base64, binascii, time, hashlib, re, copy, textwrap, logging 9 | try: 10 | from urllib.request import urlopen, Request # Python 3 11 | except ImportError: 12 | from urllib2 import urlopen, Request # Python 2 13 | 14 | DEFAULT_CA = "https://acme-v02.api.letsencrypt.org" # DEPRECATED! USE DEFAULT_DIRECTORY_URL INSTEAD 15 | DEFAULT_DIRECTORY_URL = "https://acme-v02.api.letsencrypt.org/directory" 16 | 17 | LOGGER = logging.getLogger(__name__) 18 | LOGGER.addHandler(logging.StreamHandler()) 19 | LOGGER.setLevel(logging.INFO) 20 | 21 | def get_crt(account_key, csr, acme_dir, log=LOGGER, CA=DEFAULT_CA, disable_check=False, directory_url=DEFAULT_DIRECTORY_URL, contact=None): 22 | directory, acct_headers, alg, jwk = None, None, None, None # global variables 23 | 24 | # helper functions - base64 encode for jose spec 25 | def _b64(b): 26 | return base64.urlsafe_b64encode(b).decode('utf8').replace("=", "") 27 | 28 | # helper function - run external commands 29 | def _cmd(cmd_list, stdin=None, cmd_input=None, err_msg="Command Line Error"): 30 | proc = subprocess.Popen(cmd_list, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 31 | out, err = proc.communicate(cmd_input) 32 | if proc.returncode != 0: 33 | raise IOError("{0}\n{1}".format(err_msg, err)) 34 | return out 35 | 36 | # helper function - make request and automatically parse json response 37 | def _do_request(url, data=None, err_msg="Error", depth=0): 38 | try: 39 | resp = urlopen(Request(url, data=data, headers={"Content-Type": "application/jose+json", "User-Agent": "acme-tiny"})) 40 | resp_data, code, headers = resp.read().decode("utf8"), resp.getcode(), resp.headers 41 | except IOError as e: 42 | resp_data = e.read().decode("utf8") if hasattr(e, "read") else str(e) 43 | code, headers = getattr(e, "code", None), {} 44 | try: 45 | resp_data = json.loads(resp_data) # try to parse json results 46 | except ValueError: 47 | pass # ignore json parsing errors 48 | if depth < 100 and code == 400 and resp_data['type'] == "urn:ietf:params:acme:error:badNonce": 49 | raise IndexError(resp_data) # allow 100 retrys for bad nonces 50 | if code not in [200, 201, 204]: 51 | raise ValueError("{0}:\nUrl: {1}\nData: {2}\nResponse Code: {3}\nResponse: {4}".format(err_msg, url, data, code, resp_data)) 52 | return resp_data, code, headers 53 | 54 | # helper function - make signed requests 55 | def _send_signed_request(url, payload, err_msg, depth=0): 56 | payload64 = "" if payload is None else _b64(json.dumps(payload).encode('utf8')) 57 | new_nonce = _do_request(directory['newNonce'])[2]['Replay-Nonce'] 58 | protected = {"url": url, "alg": alg, "nonce": new_nonce} 59 | protected.update({"jwk": jwk} if acct_headers is None else {"kid": acct_headers['Location']}) 60 | protected64 = _b64(json.dumps(protected).encode('utf8')) 61 | protected_input = "{0}.{1}".format(protected64, payload64).encode('utf8') 62 | out = _cmd(["openssl", "dgst", "-sha256", "-sign", account_key], stdin=subprocess.PIPE, cmd_input=protected_input, err_msg="OpenSSL Error") 63 | data = json.dumps({"protected": protected64, "payload": payload64, "signature": _b64(out)}) 64 | try: 65 | return _do_request(url, data=data.encode('utf8'), err_msg=err_msg, depth=depth) 66 | except IndexError: # retry bad nonces (they raise IndexError) 67 | return _send_signed_request(url, payload, err_msg, depth=(depth + 1)) 68 | 69 | # helper function - poll until complete 70 | def _poll_until_not(url, pending_statuses, err_msg): 71 | result, t0 = None, time.time() 72 | while result is None or result['status'] in pending_statuses: 73 | assert (time.time() - t0 < 3600), "Polling timeout" # 1 hour timeout 74 | time.sleep(0 if result is None else 2) 75 | result, _, _ = _send_signed_request(url, None, err_msg) 76 | return result 77 | 78 | # parse account key to get public key 79 | log.info("Parsing account key...") 80 | out = _cmd(["openssl", "rsa", "-in", account_key, "-noout", "-text"], err_msg="OpenSSL Error") 81 | pub_pattern = r"modulus:[\s]+?00:([a-f0-9\:\s]+?)\npublicExponent: ([0-9]+)" 82 | pub_hex, pub_exp = re.search(pub_pattern, out.decode('utf8'), re.MULTILINE|re.DOTALL).groups() 83 | pub_exp = "{0:x}".format(int(pub_exp)) 84 | pub_exp = "0{0}".format(pub_exp) if len(pub_exp) % 2 else pub_exp 85 | alg = "RS256" 86 | jwk = { 87 | "e": _b64(binascii.unhexlify(pub_exp.encode("utf-8"))), 88 | "kty": "RSA", 89 | "n": _b64(binascii.unhexlify(re.sub(r"(\s|:)", "", pub_hex).encode("utf-8"))), 90 | } 91 | accountkey_json = json.dumps(jwk, sort_keys=True, separators=(',', ':')) 92 | thumbprint = _b64(hashlib.sha256(accountkey_json.encode('utf8')).digest()) 93 | 94 | # find domains 95 | log.info("Parsing CSR...") 96 | out = _cmd(["openssl", "req", "-in", csr, "-noout", "-text"], err_msg="Error loading {0}".format(csr)) 97 | domains = set([]) 98 | common_name = re.search(r"Subject:.*? CN\s?=\s?([^\s,;/]+)", out.decode('utf8')) 99 | if common_name is not None: 100 | domains.add(common_name.group(1)) 101 | subject_alt_names = re.search(r"X509v3 Subject Alternative Name: (?:critical)?\n +([^\n]+)\n", out.decode('utf8'), re.MULTILINE|re.DOTALL) 102 | if subject_alt_names is not None: 103 | for san in subject_alt_names.group(1).split(", "): 104 | if san.startswith("DNS:"): 105 | domains.add(san[4:]) 106 | log.info("Found domains: {0}".format(", ".join(domains))) 107 | 108 | # get the ACME directory of urls 109 | log.info("Getting directory...") 110 | directory_url = CA + "/directory" if CA != DEFAULT_CA else directory_url # backwards compatibility with deprecated CA kwarg 111 | directory, _, _ = _do_request(directory_url, err_msg="Error getting directory") 112 | log.info("Directory found!") 113 | 114 | # create account, update contact details (if any), and set the global key identifier 115 | log.info("Registering account...") 116 | reg_payload = {"termsOfServiceAgreed": True} 117 | account, code, acct_headers = _send_signed_request(directory['newAccount'], reg_payload, "Error registering") 118 | log.info("Registered!" if code == 201 else "Already registered!") 119 | if contact is not None: 120 | account, _, _ = _send_signed_request(acct_headers['Location'], {"contact": contact}, "Error updating contact details") 121 | log.info("Updated contact details:\n{0}".format("\n".join(account['contact']))) 122 | 123 | # create a new order 124 | log.info("Creating new order...") 125 | order_payload = {"identifiers": [{"type": "dns", "value": d} for d in domains]} 126 | order, _, order_headers = _send_signed_request(directory['newOrder'], order_payload, "Error creating new order") 127 | log.info("Order created!") 128 | 129 | # get the authorizations that need to be completed 130 | for auth_url in order['authorizations']: 131 | authorization, _, _ = _send_signed_request(auth_url, None, "Error getting challenges") 132 | domain = authorization['identifier']['value'] 133 | log.info("Verifying {0}...".format(domain)) 134 | 135 | # find the http-01 challenge and write the challenge file 136 | challenge = [c for c in authorization['challenges'] if c['type'] == "http-01"][0] 137 | token = re.sub(r"[^A-Za-z0-9_\-]", "_", challenge['token']) 138 | keyauthorization = "{0}.{1}".format(token, thumbprint) 139 | wellknown_path = os.path.join(acme_dir, token) 140 | with open(wellknown_path, "w") as wellknown_file: 141 | wellknown_file.write(keyauthorization) 142 | 143 | # check that the file is in place 144 | try: 145 | wellknown_url = "http://{0}/.well-known/acme-challenge/{1}".format(domain, token) 146 | assert (disable_check or _do_request(wellknown_url)[0] == keyauthorization) 147 | except (AssertionError, ValueError) as e: 148 | raise ValueError("Wrote file to {0}, but couldn't download {1}: {2}".format(wellknown_path, wellknown_url, e)) 149 | 150 | # say the challenge is done 151 | _send_signed_request(challenge['url'], {}, "Error submitting challenges: {0}".format(domain)) 152 | authorization = _poll_until_not(auth_url, ["pending"], "Error checking challenge status for {0}".format(domain)) 153 | if authorization['status'] != "valid": 154 | raise ValueError("Challenge did not pass for {0}: {1}".format(domain, authorization)) 155 | os.remove(wellknown_path) 156 | log.info("{0} verified!".format(domain)) 157 | 158 | # finalize the order with the csr 159 | log.info("Signing certificate...") 160 | csr_der = _cmd(["openssl", "req", "-in", csr, "-outform", "DER"], err_msg="DER Export Error") 161 | _send_signed_request(order['finalize'], {"csr": _b64(csr_der)}, "Error finalizing order") 162 | 163 | # poll the order to monitor when it's done 164 | order = _poll_until_not(order_headers['Location'], ["pending", "processing"], "Error checking order status") 165 | if order['status'] != "valid": 166 | raise ValueError("Order failed: {0}".format(order)) 167 | 168 | # download the certificate 169 | certificate_pem, _, _ = _send_signed_request(order['certificate'], None, "Certificate download failed") 170 | log.info("Certificate signed!") 171 | return certificate_pem 172 | 173 | def main(argv=None): 174 | parser = argparse.ArgumentParser( 175 | formatter_class=argparse.RawDescriptionHelpFormatter, 176 | description=textwrap.dedent("""\ 177 | This script automates the process of getting a signed TLS certificate from Let's Encrypt using 178 | the ACME protocol. It will need to be run on your server and have access to your private 179 | account key, so PLEASE READ THROUGH IT! It's only ~200 lines, so it won't take long. 180 | 181 | Example Usage: 182 | python acme_tiny.py --account-key ./account.key --csr ./domain.csr --acme-dir /usr/share/nginx/html/.well-known/acme-challenge/ > signed_chain.crt 183 | 184 | Example Crontab Renewal (once per month): 185 | 0 0 1 * * python /path/to/acme_tiny.py --account-key /path/to/account.key --csr /path/to/domain.csr --acme-dir /usr/share/nginx/html/.well-known/acme-challenge/ > /path/to/signed_chain.crt 2>> /var/log/acme_tiny.log 186 | """) 187 | ) 188 | parser.add_argument("--account-key", required=True, help="path to your Let's Encrypt account private key") 189 | parser.add_argument("--csr", required=True, help="path to your certificate signing request") 190 | parser.add_argument("--acme-dir", required=True, help="path to the .well-known/acme-challenge/ directory") 191 | parser.add_argument("--quiet", action="store_const", const=logging.ERROR, help="suppress output except for errors") 192 | parser.add_argument("--disable-check", default=False, action="store_true", help="disable checking if the challenge file is hosted correctly before telling the CA") 193 | parser.add_argument("--directory-url", default=DEFAULT_DIRECTORY_URL, help="certificate authority directory url, default is Let's Encrypt") 194 | parser.add_argument("--ca", default=DEFAULT_CA, help="DEPRECATED! USE --directory-url INSTEAD!") 195 | parser.add_argument("--contact", metavar="CONTACT", default=None, nargs="*", help="Contact details (e.g. mailto:aaa@bbb.com) for your account-key") 196 | 197 | args = parser.parse_args(argv) 198 | LOGGER.setLevel(args.quiet or LOGGER.level) 199 | signed_crt = get_crt(args.account_key, args.csr, args.acme_dir, log=LOGGER, CA=args.ca, disable_check=args.disable_check, directory_url=args.directory_url, contact=args.contact) 200 | sys.stdout.write(signed_crt) 201 | 202 | if __name__ == "__main__": # pragma: no cover 203 | main(sys.argv[1:]) 204 | -------------------------------------------------------------------------------- /handlers/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | - name: Restart service (nginx, apache, haproxy, etc.) 4 | service: 5 | name: '{{ letsencrypt_restart_service_name }}' 6 | state: 'restarted' 7 | -------------------------------------------------------------------------------- /meta/main.yml: -------------------------------------------------------------------------------- 1 | galaxy_info: 2 | author: Nick Janetakis 3 | description: Install and auto-renew SSL certificates with Let's Encrypt. 4 | company: 5 | license: license MIT 6 | min_ansible_version: 2.0 7 | 8 | platforms: 9 | - name: Ubuntu 10 | versions: 11 | - xenial 12 | - name: Debian 13 | versions: 14 | - jessie 15 | 16 | categories: 17 | - system 18 | - networking 19 | - web 20 | 21 | dependencies: [] 22 | -------------------------------------------------------------------------------- /tasks/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | - name: Create default acme-tiny directories 4 | file: 5 | path: '{{ item }}' 6 | state: 'directory' 7 | owner: 'root' 8 | group: 'root' 9 | mode: '0755' 10 | with_items: 11 | - '{{ letsencrypt_install_path }}' 12 | - '{{ letsencrypt_challenge_path }}' 13 | - '{{ letsencrypt_certificate_path }}' 14 | - '{{ letsencrypt_log_path }}' 15 | 16 | - name: Download Let's Encrypt intermediate certificate 17 | get_url: 18 | url: '{{ letsencrypt_intermediate_url }}' 19 | dest: '{{ letsencrypt_install_path }}/intermediate.crt' 20 | owner: 'root' 21 | group: 'root' 22 | mode: '0644' 23 | force: True 24 | 25 | - name: Force delete all keys, CSRs and certificates 26 | file: 27 | path: '{{ item }}' 28 | state: 'absent' 29 | with_items: 30 | - '{{ letsencrypt_account_key_path }}' 31 | - '{{ letsencrypt_domain_csr_path }}' 32 | - '{{ letsencrypt_valid_certificate_path }}' 33 | - '{{ letsencrypt_domain_key_path }}' 34 | - '{{ letsencrypt_chained_pem_path }}' 35 | when: letsencrypt_force_reset_all 36 | 37 | - name: Generate private account key 38 | command: openssl genrsa -out {{ letsencrypt_account_key_path }} 39 | args: 40 | creates: '{{ letsencrypt_account_key_path }}' 41 | 42 | - name: Generate private domain key 43 | command: openssl genrsa -out {{ letsencrypt_domain_key_path }} 44 | args: 45 | creates: '{{ letsencrypt_domain_key_path }}' 46 | 47 | - name: Generate certificate signing request (CSR) for your domain(s) 48 | shell: > 49 | openssl req \ 50 | -new \ 51 | -sha256 \ 52 | -key {{ letsencrypt_domain_key_path }} \ 53 | -subj "/" \ 54 | -reqexts SAN \ 55 | -config <(cat /etc/ssl/openssl.cnf <(printf "[SAN]\nsubjectAltName=DNS:{{ letsencrypt_domains | join(",DNS:") }}")) \ 56 | -out {{ letsencrypt_domain_csr_path }} 57 | args: 58 | executable: '/bin/bash' 59 | creates: '{{ letsencrypt_domain_csr_path }}' 60 | 61 | - name: Copy acme_tiny to the system path 62 | copy: 63 | src: 'usr/local/bin/acme_tiny' 64 | dest: '/usr/local/bin/acme_tiny' 65 | group: 'root' 66 | owner: 'root' 67 | mode: '0755' 68 | 69 | - name: Investigate the Let's Encrypt SSL certificate 70 | stat: 71 | path: '{{ letsencrypt_valid_certificate_path }}' 72 | register: letsencrypt_stat 73 | 74 | - name: Delete an invalid Let's Encrypt SSL certificate 75 | file: 76 | path: '{{ letsencrypt_valid_certificate_path }}' 77 | state: 'absent' 78 | when: ('size' in letsencrypt_stat.stat.keys()) and (letsencrypt_stat.stat.size == 0) 79 | 80 | - name: Generate Let's Encrypt SSL certificate for your domain(s) 81 | shell: > 82 | acme_tiny --account-key {{ letsencrypt_account_key_path }} \ 83 | --csr {{ letsencrypt_domain_csr_path }} \ 84 | --acme-dir {{ letsencrypt_challenge_path }} \ 85 | --directory-url {{ letsencrypt_default_ca }} > {{ letsencrypt_valid_certificate_path }} 86 | args: 87 | creates: '{{ letsencrypt_valid_certificate_path }}' 88 | register: letsencrypt_register_output 89 | failed_when: False 90 | 91 | - name: Show SSL certificate generation output 92 | debug: 93 | var: letsencrypt_register_output 94 | failed_when: ('rc' in letsencrypt_register_output) and (not letsencrypt_register_output.rc == 0) 95 | 96 | - name: Complete trust chain 97 | shell: 'cat {{ letsencrypt_valid_certificate_path }} {{ letsencrypt_install_path }}/intermediate.crt > {{ letsencrypt_chained_pem_path }}' 98 | when: (letsencrypt_register_output is changed) and (letsencrypt_register_output.stderr.endswith('Certificate signed!')) 99 | notify: 100 | - Restart service (nginx, apache, haproxy, etc.) 101 | 102 | - name: Copy renew_certificate to the installation path 103 | template: 104 | src: 'usr/local/acme-tiny/renew_certificate.sh.j2' 105 | dest: '{{ letsencrypt_install_path }}/renew_certificate.sh' 106 | group: 'root' 107 | owner: 'root' 108 | mode: '0755' 109 | 110 | - name: Create crontab to renew SSL certificates 111 | cron: 112 | name: 'renew SSL certificates' 113 | job: '{{ letsencrypt_install_path }}/renew_certificate.sh' 114 | minute: '{{ letsencrypt_cron_renew[0] }}' 115 | hour: '{{ letsencrypt_cron_renew[1] }}' 116 | day: '{{ letsencrypt_cron_renew[2] }}' 117 | weekday: '{{ letsencrypt_cron_renew[3] }}' 118 | month: '{{ letsencrypt_cron_renew[4] }}' 119 | -------------------------------------------------------------------------------- /templates/usr/local/acme-tiny/renew_certificate.sh.j2: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | TEMP_CERT_PATH="/tmp/{{ letsencrypt_domains[0] }}.crt" 6 | INTERMEDIATE_PATH="{{ letsencrypt_install_path }}/intermediate.crt" 7 | 8 | # Generate Let's Encrypt certificate for your domain(s). 9 | /usr/local/bin/acme_tiny \ 10 | --account-key {{ letsencrypt_account_key_path }} \ 11 | --csr {{ letsencrypt_domain_csr_path }} \ 12 | --acme-dir {{ letsencrypt_challenge_path }} \ 13 | --directory-url {{ letsencrypt_default_ca }} > "${TEMP_CERT_PATH}" \ 14 | 2>> {{ letsencrypt_log_path }}/acme-tiny.log 15 | 16 | # Complete trust chain by pulling down a fresh intermediate certificate. 17 | wget {{ letsencrypt_intermediate_url }} -O "${INTERMEDIATE_PATH}" 18 | cat "${TEMP_CERT_PATH}" "${INTERMEDIATE_PATH}" > {{ letsencrypt_chained_pem_path }} 19 | 20 | # Restart service to pickup the certificate change. 21 | sudo service {{ letsencrypt_restart_service_name }} restart 22 | -------------------------------------------------------------------------------- /tests/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | - hosts: all 4 | 5 | roles: 6 | - this_role 7 | --------------------------------------------------------------------------------