diff --git a/.ansible-lint b/.ansible-lint new file mode 100644 index 0000000..0d93798 --- /dev/null +++ b/.ansible-lint @@ -0,0 +1,8 @@ +--- +warn_list: + - experimental # all rules tagged as experimental + - yaml # violations reported by yamllint + - meta-no-info + +skip_list: + - jinja[spacing] # Rule that looks inside jinja2 templates. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..03ffe07 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +# ignore molecule/testinfra pycache +**/__pycache__ \ No newline at end of file diff --git a/.yamllint b/.yamllint new file mode 100644 index 0000000..24fdec5 --- /dev/null +++ b/.yamllint @@ -0,0 +1,40 @@ +--- +# Based on ansible-lint config +extends: default + +rules: + braces: + max-spaces-inside: 1 + level: error + brackets: + max-spaces-inside: 1 + level: error + colons: + max-spaces-after: -1 + level: error + commas: + max-spaces-after: -1 + level: error + comments: enable + comments-indentation: disable + document-start: enable + empty-lines: + max: 3 + level: error + hyphens: + level: error + indentation: enable + key-duplicates: enable + line-length: + max: 80 + level: warning + new-line-at-end-of-file: enable + new-lines: + type: unix + trailing-spaces: enable + truthy: + allowed-values: + - 'true' + - 'false' + - 'yes' + - 'no' diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9ef042d --- /dev/null +++ b/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2017 Jeff Geerling + +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. \ No newline at end of file diff --git a/README.md b/README.md index 6d67dc8..152f8a7 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,115 @@ -# renew_nomad_certificates +Renew nomad certificates +========= +> This repository is only a mirror. Development and testing is done on a private gitlab server. +This role install consul-template and configure a service to automate renewal of TLS certificates for Hashicorp Nomad on **debian-based** distributions. +Requirements +------------ -## Getting started +This role assume that you already have installed a nomad server/client on the host, and is only here to assist in automating the certificate renewal process. -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +Role Variables +-------------- +Available variables are listed below, along with default values. A sample file for the default values is available in `default/renew_consul_certificates.yml.sample` in case you need it for any `group_vars` or `host_vars` configuration. +```yaml +renew_consul_certificates_config_dir: /etc/consul-template.d/consul # by default, set to /etc/consul-template.d/consul ``` -cd existing_repo -git remote add origin https://gitlab.ednz.fr/homelab/ansible-resources/roles/renew_nomad_certificates.git -git branch -M main -git push -uf origin main +This variable defines where the files for the role are stored (consul-template configuration + templates). + +```yaml +renew_vault_certificates_consul_user: consul # by default, set to consul +``` +This variable defines the user that'll be running the certificate renewal service. Defaults to `consul`, and should be present on the host prior to playing this role (ideally when installing consul). + +```yaml +renew_vault_certificates_consul_group: consul # by default, set to consul +``` +This variable defines the group that'll be running the certificate renewal service. Defaults to `consul`, and should be present on the host prior to playing this role (ideally when installing consul). + +```yaml +renew_vault_certificates_vault_addr: https://127.0.0.1:8200 # by default, set to https://127.0.0.1:8200 +``` +This variable defines the address the consul-template service will query to get the new certificates. Defaults to localhost, but can be changed if vault isnt reachable on localhost. + +```yaml +renew_vault_certificates_vault_token: mysupersecretvaulttokenthatyoushouldchange # by default, set to a dummy string +``` +This variable defines the vault token top use to access vault and renew the certificate. Default is a dummy string to pass unit tests. + +```yaml +renew_vault_certificates_vault_token_unwrap: false # by default, set to false +``` +Defines whether or not the token is wrapped and should be unwrapped (this is an enterprise-only feature of vault at the moment). + +```yaml +renew_vault_certificates_vault_token_renew: true # by default, set to true +``` +This variable defines whether or not to renew the vault token. It should probably be `true`, and you should have a periodic token to handle this. + +```yaml +renew_consul_certificates_ca_dest: /opt/consul/tls/ca.pem # by default, set to /opt/consul/tls/ca.pem +``` +This variable defines where to copy the certificate authority upon renewal. Default to `/opt/consul/tls/ca.pem` but should be changed depending on where you store the certificate authority. + +```yaml +renew_vault_certificates_cert_dest: /opt/consul/tls/cert.pem # by default, set to /opt/consul/tls/cert.pem +``` +This variable defines where to copy the certificates upon renewal. Default to `/opt/consul/tls/cert.pem` but should be changed depending on where you store the certificates. + +```yaml +renew_consul_certificates_key_dest: /opt/consul/tls/key.pem # by default, set to /opt/consul/tls/cert.pem +``` +This variable defines where to copy the private keys upon renewal. Default to `/opt/consul/tls/key.pem` but should be changed depending on where you store the keys. + +```yaml +renew_consul_certificates_info: # by default, set to: + issuer_path: pki/issue/your-issuer + common_name: consul01.example.com + ttl: 90d + is_server: false + include_consul_service: false +``` +This variable defines the path on vault to retrieve the certificates, as well as the common name and TTL to use for it. It can also include consul aliases in case you have registered consul services in itself (`consul.service.consul`). It also handles whether or not to append the server.yourdc.consul SAN, in case you're enforcing hostname checking. + +```yaml +renew_consul_certificates_consul_dc_name: dc1.consul # by default, set to dc1.consul +``` +In case you enforce hostname checking, set this variable to your desired dc and consul domain. This is used to forge the SAN that will be checked by consul to only allow specific nodes to be managers. + +```yaml +renew_consul_certificates_consul_service_name: consul.service.consul # by default, set to consul.service.consul +``` +This variable defines the consul service name in consul. Default is `consul.service.consul` + +```yaml +renew_consul_certificates_start_service: false +``` +This variable defines whether or not to start the service after creating it. By default, it is only enabled, but not started, in case you're building golden images (in which case you probably don't want a certificate generated during the build process). + +Dependencies +------------ + +This role has a task that installs its own dependencies located in `task/prerequisites.yml`, so that you don't need to manage them. This role requires both `ednxzu.manage_repositories` and `ednxzu.manage_apt_packages` to install consul-template. + +Example Playbook +---------------- + +Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too: +```yaml +# calling the role inside a playbook with either the default or group_vars/host_vars +- hosts: servers + roles: + - ednxzu.renew_consul_certificates ``` -## Integrate with your tools +License +------- -- [ ] [Set up project integrations](https://gitlab.ednz.fr/homelab/ansible-resources/roles/renew_nomad_certificates/-/settings/integrations) +MIT / BSD -## Collaborate with your team +Author Information +------------------ -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +This role was created by Bertrand Lanson in 2023. diff --git a/defaults/main.yml b/defaults/main.yml new file mode 100644 index 0000000..b7ee706 --- /dev/null +++ b/defaults/main.yml @@ -0,0 +1,21 @@ +--- +# defaults file for renew_nomad_certificates +renew_nomad_certificates_config_dir: /etc/consul-template.d/nomad +renew_nomad_certificates_nomad_user: nomad +renew_nomad_certificates_nomad_group: nomad +renew_nomad_certificates_vault_addr: "https://vault.example.com" +renew_nomad_certificates_vault_token: mysupersecretnomadtokenthatyoushouldchange +renew_nomad_certificates_vault_token_unwrap: false +renew_nomad_certificates_vault_token_renew: true +renew_nomad_certificates_ca_dest: /opt/nomad/tls/ca.pem +renew_nomad_certificates_cert_dest: /opt/nomad/tls/cert.pem +renew_nomad_certificates_key_dest: /opt/nomad/tls/key.pem +renew_nomad_certificates_info: + issuer_path: pki/issue/your-issuer + common_name: nomad01.example.com + ttl: 90d + is_server: false + include_nomad_service: false +renew_nomad_certificates_nomad_dc_name: dc1.nomad +renew_nomad_certificates_nomad_service_name: nomad.service.nomad +renew_nomad_certificates_start_service: false diff --git a/handlers/main.yml b/handlers/main.yml new file mode 100644 index 0000000..450a046 --- /dev/null +++ b/handlers/main.yml @@ -0,0 +1,19 @@ +--- +# handlers file for renew_nomad_certificates +- name: "Reload service file" + ansible.builtin.systemd: + daemon_reload: true + listen: "systemctl-daemon-reload" + +- name: "Enable nomad-certs service" + ansible.builtin.service: + name: nomad-certs + enabled: true + listen: "systemctl-enable-nomad-certs" + +- name: "Start nomad-certs service" + ansible.builtin.service: + name: nomad-certs + state: restarted + listen: "systemctl-restart-nomad-certs" + when: renew_nomad_certificates_start_service diff --git a/meta/main.yml b/meta/main.yml new file mode 100644 index 0000000..967a06f --- /dev/null +++ b/meta/main.yml @@ -0,0 +1,24 @@ +--- +# meta file for renew_nomad_certificates +galaxy_info: + namespace: 'ednxzu' + role_name: 'renew_nomad_certificates' + author: 'Bertrand Lanson' + description: 'Install and configure consul-template to renew nomad TLS certificates for debian-based distros.' + license: 'license (BSD, MIT)' + min_ansible_version: '2.10' + platforms: + - name: Ubuntu + versions: + - focal + - jammy + - name: Debian + versions: + - bullseye + galaxy_tags: + - 'ubuntu' + - 'debian' + - 'hashicorp' + - 'nomad' + +dependencies: [] diff --git a/molecule/default/converge.yml b/molecule/default/converge.yml new file mode 100644 index 0000000..e272496 --- /dev/null +++ b/molecule/default/converge.yml @@ -0,0 +1,7 @@ +--- +- name: Converge + hosts: all + tasks: + - name: "Include ednxzu.renew_nomad_certificates" + ansible.builtin.include_role: + name: "ednxzu.renew_nomad_certificates" diff --git a/molecule/default/molecule.yml b/molecule/default/molecule.yml new file mode 100644 index 0000000..6132acb --- /dev/null +++ b/molecule/default/molecule.yml @@ -0,0 +1,37 @@ +--- +dependency: + name: galaxy + options: + requirements-file: ./requirements.yml +driver: + name: docker +platforms: + - name: instance + image: geerlingguy/docker-${MOLECULE_TEST_OS}-ansible + command: "" + volumes: + - /sys/fs/cgroup:/sys/fs/cgroup + cgroupns_mode: host + privileged: true + pre_build_image: true +provisioner: + name: ansible + config_options: + defaults: + remote_tmp: /tmp/.ansible +verifier: + name: testinfra +scenario: + name: with_custom_config + test_sequence: + - dependency + - cleanup + - destroy + - syntax + - create + - prepare + - converge + - idempotence + - verify + - cleanup + - destroy diff --git a/molecule/default/prepare.yml b/molecule/default/prepare.yml new file mode 100644 index 0000000..242d4a7 --- /dev/null +++ b/molecule/default/prepare.yml @@ -0,0 +1,15 @@ +--- +- name: Prepare + hosts: all + tasks: + - name: "Create group nomad" + ansible.builtin.group: + name: "nomad" + state: present + + - name: "Create user nomad" + ansible.builtin.user: + name: "nomad" + group: "nomad" + shell: /bin/false + state: present diff --git a/molecule/default/tests/conftest.py b/molecule/default/tests/conftest.py new file mode 100644 index 0000000..a11928c --- /dev/null +++ b/molecule/default/tests/conftest.py @@ -0,0 +1,22 @@ +"""PyTest Fixtures.""" + +import os + +import pytest + + +def pytest_runtest_setup(item): + """Run tests only when under molecule with testinfra installed.""" + try: + import testinfra + except ImportError: + pytest.skip("Test requires testinfra", allow_module_level=True) + if "MOLECULE_INVENTORY_FILE" in os.environ: + pytest.testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( + os.environ["MOLECULE_INVENTORY_FILE"], + ).get_hosts("all") + else: + pytest.skip( + "Test should run only from inside molecule.", + allow_module_level=True, + ) diff --git a/molecule/default/tests/test_default.py b/molecule/default/tests/test_default.py new file mode 100644 index 0000000..0cff669 --- /dev/null +++ b/molecule/default/tests/test_default.py @@ -0,0 +1,10 @@ +"""Role testing files using testinfra.""" + + +def test_hosts_file(host): + """Validate /etc/hosts file.""" + f = host.file("/etc/hosts") + + assert f.exists + assert f.user == "root" + assert f.group == "root" diff --git a/molecule/with_custom_config/converge.yml b/molecule/with_custom_config/converge.yml new file mode 100644 index 0000000..d9ad3ce --- /dev/null +++ b/molecule/with_custom_config/converge.yml @@ -0,0 +1,7 @@ +--- +- name: Converge + hosts: all + tasks: + - name: "Include ednxzu.renew_consul_certificates" + ansible.builtin.include_role: + name: "ednxzu.renew_consul_certificates" diff --git a/molecule/with_custom_config/group_vars/all.yml b/molecule/with_custom_config/group_vars/all.yml new file mode 100644 index 0000000..60a6162 --- /dev/null +++ b/molecule/with_custom_config/group_vars/all.yml @@ -0,0 +1,20 @@ +--- +renew_nomad_certificates_config_dir: /etc/consul-template.d/nomad +renew_nomad_certificates_nomad_user: nomad +renew_nomad_certificates_nomad_group: nomad +renew_nomad_certificates_vault_addr: "https://vault.example.com" +renew_nomad_certificates_vault_token: mysupersecretnomadtokenthatyoushouldchange +renew_nomad_certificates_vault_token_unwrap: false +renew_nomad_certificates_vault_token_renew: true +renew_nomad_certificates_ca_dest: /opt/nomad/tls/ca.pem +renew_nomad_certificates_cert_dest: /opt/nomad/tls/cert.pem +renew_nomad_certificates_key_dest: /opt/nomad/tls/key.pem +renew_nomad_certificates_info: + issuer_path: pki/issue/your-issuer + common_name: nomad01.example.com + ttl: 90d + is_server: true + include_nomad_service: true +renew_nomad_certificates_nomad_dc_name: dc1.nomad +renew_nomad_certificates_nomad_service_name: nomad.service.nomad +renew_nomad_certificates_start_service: false diff --git a/molecule/with_custom_config/molecule.yml b/molecule/with_custom_config/molecule.yml new file mode 100644 index 0000000..6132acb --- /dev/null +++ b/molecule/with_custom_config/molecule.yml @@ -0,0 +1,37 @@ +--- +dependency: + name: galaxy + options: + requirements-file: ./requirements.yml +driver: + name: docker +platforms: + - name: instance + image: geerlingguy/docker-${MOLECULE_TEST_OS}-ansible + command: "" + volumes: + - /sys/fs/cgroup:/sys/fs/cgroup + cgroupns_mode: host + privileged: true + pre_build_image: true +provisioner: + name: ansible + config_options: + defaults: + remote_tmp: /tmp/.ansible +verifier: + name: testinfra +scenario: + name: with_custom_config + test_sequence: + - dependency + - cleanup + - destroy + - syntax + - create + - prepare + - converge + - idempotence + - verify + - cleanup + - destroy diff --git a/molecule/with_custom_config/prepare.yml b/molecule/with_custom_config/prepare.yml new file mode 100644 index 0000000..242d4a7 --- /dev/null +++ b/molecule/with_custom_config/prepare.yml @@ -0,0 +1,15 @@ +--- +- name: Prepare + hosts: all + tasks: + - name: "Create group nomad" + ansible.builtin.group: + name: "nomad" + state: present + + - name: "Create user nomad" + ansible.builtin.user: + name: "nomad" + group: "nomad" + shell: /bin/false + state: present diff --git a/molecule/with_custom_config/requirements.yml b/molecule/with_custom_config/requirements.yml new file mode 100644 index 0000000..0a4a9fb --- /dev/null +++ b/molecule/with_custom_config/requirements.yml @@ -0,0 +1,5 @@ +--- +# requirements file for molecule +roles: + - name: ednxzu.manage_repositories + - name: ednxzu.manage_apt_packages diff --git a/molecule/with_custom_config/tests/conftest.py b/molecule/with_custom_config/tests/conftest.py new file mode 100644 index 0000000..f7ddb3f --- /dev/null +++ b/molecule/with_custom_config/tests/conftest.py @@ -0,0 +1,22 @@ +"""PyTest Fixtures.""" +from __future__ import absolute_import + +import os + +import pytest + + +def pytest_runtest_setup(item): + """Run tests only when under molecule with testinfra installed.""" + try: + import testinfra + except ImportError: + pytest.skip("Test requires testinfra", allow_module_level=True) + if "MOLECULE_INVENTORY_FILE" in os.environ: + pytest.testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( + os.environ["MOLECULE_INVENTORY_FILE"] + ).get_hosts("all") + else: + pytest.skip( + "Test should run only from inside molecule.", allow_module_level=True + ) diff --git a/molecule/with_custom_config/tests/test_default.py b/molecule/with_custom_config/tests/test_default.py new file mode 100644 index 0000000..c411ac2 --- /dev/null +++ b/molecule/with_custom_config/tests/test_default.py @@ -0,0 +1,50 @@ +"""Role testing files using testinfra.""" + + +def test_hosts_file(host): + """Validate /etc/hosts file.""" + etc_hosts = host.file("/etc/hosts") + assert etc_hosts.exists + assert etc_hosts.user == "root" + assert etc_hosts.group == "root" + +def test_consul_template_config(host): + """Validate /etc/consul-template.d/consul/ files.""" + etc_consul_template_d_consul_config_hcl = host.file("/etc/consul-template.d/consul/consul_config.hcl") + assert etc_consul_template_d_consul_config_hcl.exists + assert etc_consul_template_d_consul_config_hcl.user == "consul" + assert etc_consul_template_d_consul_config_hcl.group == "consul" + assert etc_consul_template_d_consul_config_hcl.mode == 0o600 + +def test_template_files(host): + """Validate /etc/consul-template.d/consul/templates/ files.""" + consul_ca_pem_tpl = host.file("/etc/consul-template.d/consul/templates/consul_ca.pem.tpl") + consul_cert_pem_tpl = host.file("/etc/consul-template.d/consul/templates/consul_cert.pem.tpl") + consul_key_pem_tpl = host.file("/etc/consul-template.d/consul/templates/consul_key.pem.tpl") + for file in consul_cert_pem_tpl, consul_key_pem_tpl: + assert file.exists + assert file.user == "consul" + assert file.group == "consul" + assert file.mode == 0o600 + assert consul_ca_pem_tpl.content_string == '{{ with secret "pki/issue/your-issuer" "common_name=consul01.example.com" "ttl=90d" "alt_names=localhost,server.dc1.consul,consul.service.consul" "ip_sans=127.0.0.1" }}\n{{ .Data.issuing_ca }}\n{{ end }}\n' + assert consul_cert_pem_tpl.content_string == '{{ with secret "pki/issue/your-issuer" "common_name=consul01.example.com" "ttl=90d" "alt_names=localhost,server.dc1.consul,consul.service.consul" "ip_sans=127.0.0.1" }}\n{{ .Data.certificate }}\n{{ .Data.issuing_ca }}\n{{ end }}\n' + assert consul_key_pem_tpl.content_string == '{{ with secret "pki/issue/your-issuer" "common_name=consul01.example.com" "ttl=90d" "alt_names=localhost,server.dc1.consul,consul.service.consul" "ip_sans=127.0.0.1" }}\n{{ .Data.private_key }}\n{{ end }}\n' + +def test_consul_certs_service_file(host): + """Validate consul-certs service file.""" + etc_systemd_system_consul_certs_service = host.file("/etc/systemd/system/consul-certs.service") + assert etc_systemd_system_consul_certs_service.exists + assert etc_systemd_system_consul_certs_service.user == "root" + assert etc_systemd_system_consul_certs_service.group == "root" + assert etc_systemd_system_consul_certs_service.mode == 0o644 + assert etc_systemd_system_consul_certs_service.content_string != "" + +def test_consul_certs_service(host): + """Validate consul-certs service.""" + consul_certs_service = host.service("consul-certs.service") + assert consul_certs_service.is_enabled + assert not consul_certs_service.is_running + assert consul_certs_service.systemd_properties["Restart"] == "on-failure" + assert consul_certs_service.systemd_properties["User"] == "consul" + assert consul_certs_service.systemd_properties["Group"] == "consul" + assert consul_certs_service.systemd_properties["FragmentPath"] == "/etc/systemd/system/consul-certs.service" diff --git a/tasks/configure.yml b/tasks/configure.yml new file mode 100644 index 0000000..4c576ee --- /dev/null +++ b/tasks/configure.yml @@ -0,0 +1,48 @@ +--- +# task/configure file for renew_nomad_certificates +- name: "Configure files for nomad certificate renewal" + notify: + - "systemctl-enable-nomad-certs" + - "systemctl-restart-nomad-certs" + block: + - name: "Copy nomad_config.hcl template" + ansible.builtin.template: + src: nomad_config.hcl.j2 + dest: "{{ renew_nomad_certificates_config_dir }}/nomad_config.hcl" + owner: "{{ renew_nomad_certificates_nomad_user }}" + group: "{{ renew_nomad_certificates_nomad_group }}" + mode: '0600' + + - name: "Copy nomad_ca.pem.tpl template" + ansible.builtin.template: + src: nomad_ca.pem.tpl.j2 + dest: "{{ renew_nomad_certificates_config_dir }}/templates/nomad_ca.pem.tpl" + owner: "{{ renew_nomad_certificates_nomad_user }}" + group: "{{ renew_nomad_certificates_nomad_group }}" + mode: '0600' + + - name: "Copy nomad_cert.pem.tpl template" + ansible.builtin.template: + src: nomad_cert.pem.tpl.j2 + dest: "{{ renew_nomad_certificates_config_dir }}/templates/nomad_cert.pem.tpl" + owner: "{{ renew_nomad_certificates_nomad_user }}" + group: "{{ renew_nomad_certificates_nomad_group }}" + mode: '0600' + + - name: "Copy nomad_cert.key.tpl template" + ansible.builtin.template: + src: nomad_key.pem.tpl.j2 + dest: "{{ renew_nomad_certificates_config_dir }}/templates/nomad_key.pem.tpl" + owner: "{{ renew_nomad_certificates_nomad_user }}" + group: "{{ renew_nomad_certificates_nomad_group }}" + mode: '0600' + +- name: "Configure nomad-certs systemd service" + ansible.builtin.template: + src: nomad-certs.service.j2 + dest: /etc/systemd/system/nomad-certs.service + owner: root + group: root + mode: '0644' + notify: + - "systemctl-daemon-reload" diff --git a/tasks/install.yml b/tasks/install.yml new file mode 100644 index 0000000..b454eac --- /dev/null +++ b/tasks/install.yml @@ -0,0 +1,15 @@ +--- +# task/install file for renew_nomad_certificates +- name: "Configure hashicorp repository" + ansible.builtin.include_role: + name: ednxzu.manage_repositories + vars: + manage_repositories_enable_default_repo: false + manage_repositories_enable_custom_repo: true + manage_repositories_custom_repo: "{{ renew_nomad_certificates_repository }}" + +- name: "Install nomad-template" + ansible.builtin.include_role: + name: ednxzu.manage_apt_packages + vars: + manage_apt_packages_list: "{{ renew_nomad_certificates_packages }}" diff --git a/tasks/main.yml b/tasks/main.yml new file mode 100644 index 0000000..c1b578e --- /dev/null +++ b/tasks/main.yml @@ -0,0 +1,10 @@ +--- +# task/main file for renew_nomad_certificates +- name: "Import prerequisites.yml" + ansible.builtin.include_tasks: prerequisites.yml + +- name: "Import install.yml" + ansible.builtin.include_tasks: install.yml + +- name: "Import configure.yml" + ansible.builtin.include_tasks: configure.yml diff --git a/tasks/prerequisites.yml b/tasks/prerequisites.yml new file mode 100644 index 0000000..7326fad --- /dev/null +++ b/tasks/prerequisites.yml @@ -0,0 +1,37 @@ +--- +# task/prerequisites file for renew_nomad_certificates +- name: "Install required roles" + ansible.builtin.command: + cmd: "ansible-galaxy install {{ item }}" + loop: "{{ renew_nomad_certificates_prerequisites_roles }}" + changed_when: false + delegate_to: localhost + run_once: true + +- name: "Create directory {{ renew_nomad_certificates_config_dir }}" + ansible.builtin.file: + path: "{{ renew_nomad_certificates_config_dir }}" + state: directory + owner: "{{ renew_nomad_certificates_nomad_user }}" + group: "{{ renew_nomad_certificates_nomad_group }}" + mode: '0755' + +- name: "Create directory templates directory in {{ renew_nomad_certificates_config_dir }}" + ansible.builtin.file: + path: "{{ renew_nomad_certificates_config_dir }}/templates" + state: directory + owner: "{{ renew_nomad_certificates_nomad_user }}" + group: "{{ renew_nomad_certificates_nomad_group }}" + mode: '0755' + +- name: "Ensure certificate/key directory(ies) exist(s)" + ansible.builtin.file: + path: "{{item | dirname }}" + state: directory + owner: "{{ renew_nomad_certificates_nomad_user }}" + group: "{{ renew_nomad_certificates_nomad_group }}" + mode: '0755' + loop: + - "{{ renew_nomad_certificates_cert_dest }}" + - "{{ renew_nomad_certificates_key_dest }}" + - "{{ renew_nomad_certificates_ca_dest }}" diff --git a/templates/consul-certs.service.j2 b/templates/consul-certs.service.j2 new file mode 100644 index 0000000..f43d719 --- /dev/null +++ b/templates/consul-certs.service.j2 @@ -0,0 +1,16 @@ +[Unit] +Description=Automatic renewal of consul certificate using consul-template +Requires=network-online.target +After=network-online.target consul.service +ConditionFileNotEmpty={{ renew_consul_certificates_config_dir }}/consul_config.hcl + +[Service] +User={{ renew_consul_certificates_consul_user }} +Group={{ renew_consul_certificates_consul_group }} +ExecStart=/usr/bin/consul-template $OPTIONS -config={{ renew_consul_certificates_config_dir }}/consul_config.hcl +ExecReload=/bin/kill --signal HUP $MAINPID +KillSignal=SIGINT +Restart=on-failure + +[Install] +WantedBy=multi-user.target \ No newline at end of file diff --git a/templates/consul_ca.pem.tpl.j2 b/templates/consul_ca.pem.tpl.j2 new file mode 100644 index 0000000..65e4826 --- /dev/null +++ b/templates/consul_ca.pem.tpl.j2 @@ -0,0 +1,5 @@ +{% raw %}{{ with secret {% endraw %}"{{ renew_consul_certificates_info['issuer_path'] }}" "common_name={{ renew_consul_certificates_info['common_name'] }}" "ttl={{ renew_consul_certificates_info['ttl'] }}" "alt_names=localhost{% if renew_consul_certificates_info['is_server'] %},server.{{ renew_consul_certificates_consul_dc_name }}{% endif %}{% if renew_consul_certificates_info['include_consul_service']%},{{ renew_consul_certificates_consul_service_name }}{% endif %}" "ip_sans=127.0.0.1"{% raw %} }}{% endraw %} + +{% raw %}{{ .Data.issuing_ca }}{% endraw %} + +{% raw %}{{ end }}{% endraw %} diff --git a/templates/consul_cert.pem.tpl.j2 b/templates/consul_cert.pem.tpl.j2 new file mode 100644 index 0000000..b45ded2 --- /dev/null +++ b/templates/consul_cert.pem.tpl.j2 @@ -0,0 +1,7 @@ +{% raw %}{{ with secret {% endraw %}"{{ renew_consul_certificates_info['issuer_path'] }}" "common_name={{ renew_consul_certificates_info['common_name'] }}" "ttl={{ renew_consul_certificates_info['ttl'] }}" "alt_names=localhost{% if renew_consul_certificates_info['is_server'] %},server.{{ renew_consul_certificates_consul_dc_name }}{% endif %}{% if renew_consul_certificates_info['include_consul_service']%},{{ renew_consul_certificates_consul_service_name }}{% endif %}" "ip_sans=127.0.0.1"{% raw %} }}{% endraw %} + +{% raw %}{{ .Data.certificate }}{% endraw %} + +{% raw %}{{ .Data.issuing_ca }}{% endraw %} + +{% raw %}{{ end }}{% endraw %} diff --git a/templates/consul_config.hcl.j2 b/templates/consul_config.hcl.j2 new file mode 100644 index 0000000..cf34570 --- /dev/null +++ b/templates/consul_config.hcl.j2 @@ -0,0 +1,33 @@ +vault { + address = "{{ renew_consul_certificates_vault_addr }}" + token = "{{ renew_consul_certificates_vault_token }}" + unwrap_token = {{ renew_consul_certificates_vault_token_unwrap|lower }} + renew_token = {{ renew_consul_certificates_vault_token_renew|lower }} +} + +template { + source = "{{ renew_consul_certificates_config_dir }}/templates/consul_ca.pem.tpl" + destination = "{{ renew_consul_certificates_ca_dest }}" + perms = 0700 + user = "{{ renew_consul_certificates_consul_user }}" + group = "{{ renew_consul_certificates_consul_group }}" + command = "sh -c 'echo \"$(date) Update certificate and key file for {{ renew_consul_certificates_info['common_name'] }}\" && consul reload '" +} + +template { + source = "{{ renew_consul_certificates_config_dir }}/templates/consul_cert.pem.tpl" + destination = "{{ renew_consul_certificates_cert_dest }}" + perms = 0700 + user = "{{ renew_consul_certificates_consul_user }}" + group = "{{ renew_consul_certificates_consul_group }}" + command = "sh -c 'echo \"$(date) Update certificate and key file for {{ renew_consul_certificates_info['common_name'] }}\" && consul reload '" +} + +template { + source = "{{ renew_consul_certificates_config_dir }}/templates/consul_key.pem.tpl" + destination = "{{ renew_consul_certificates_key_dest }}" + perms = 0700 + user = "{{ renew_consul_certificates_consul_user }}" + group = "{{ renew_consul_certificates_consul_group }}" + command = "sh -c 'echo \"$(date) Update certificate and key file for {{ renew_consul_certificates_info['common_name'] }}\" && consul reload '" +} diff --git a/templates/consul_key.pem.tpl.j2 b/templates/consul_key.pem.tpl.j2 new file mode 100644 index 0000000..234de6c --- /dev/null +++ b/templates/consul_key.pem.tpl.j2 @@ -0,0 +1,5 @@ +{% raw %}{{ with secret {% endraw %}"{{ renew_consul_certificates_info['issuer_path'] }}" "common_name={{ renew_consul_certificates_info['common_name'] }}" "ttl={{ renew_consul_certificates_info['ttl'] }}" "alt_names=localhost{% if renew_consul_certificates_info['is_server'] %},server.{{ renew_consul_certificates_consul_dc_name }}{% endif %}{% if renew_consul_certificates_info['include_consul_service']%},{{ renew_consul_certificates_consul_service_name }}{% endif %}" "ip_sans=127.0.0.1"{% raw %} }}{% endraw %} + +{% raw %}{{ .Data.private_key }}{% endraw %} + +{% raw %}{{ end }}{% endraw %} diff --git a/vars/main.yml b/vars/main.yml new file mode 100644 index 0000000..4ee0df8 --- /dev/null +++ b/vars/main.yml @@ -0,0 +1,17 @@ +--- +# vars file for renew_nomad_certificates +renew_nomad_certificates_prerequisites_roles: + - ednxzu.manage_repositories + - ednxzu.manage_apt_packages +renew_nomad_certificates_repository: + - uri: "https://apt.releases.hashicorp.com" + gpg_key: "https://apt.releases.hashicorp.com/gpg" + comments: "hashicorp repository" + type: "deb" + suites: "{{ ansible_distribution_release }}" + components: "main" + filename: "hashicorp" +renew_nomad_certificates_packages: + - name: consul-template + version: latest + state: present