diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..50e265a --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +# DO NOT COMMIT UNENCRYPTED SECRETS TO GIT YOU DUMMY +secrets.yaml +aws_key + +.terraform \ No newline at end of file diff --git a/.tool-versions b/.tool-versions new file mode 100644 index 0000000..0743dde --- /dev/null +++ b/.tool-versions @@ -0,0 +1 @@ +terraform 1.5.5 diff --git a/README.md b/README.md index c63bf49..c85118f 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,76 @@ -# tf +# infrastruktur/tf +Terraform'ed Infrastructure for Chaos-West TV. +## Not included -## Getting started +This repository just sets up all of our services on Docker Swarm. It does not take care of setting up the underlying bare-metal server, or configuring Docker Swarm itself. This is done by hand. The server is running [Arch Linux](https://archlinux.org/) and was ordered, installed and configured initially by hand. -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +Maintenance (updates, SSH key management) is still done by hand. -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)! +## Structure -## 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: - -``` -cd existing_repo -git remote add origin https://gitlab.montage2.de/infrastruktur/tf.git -git branch -M main -git push -uf origin main +```text +. +├── README.md # You are here +├── modules # Terraform modules +│   ├── swarm # Swarm Stacks +│   │   ├── traefik # Traefik Ingress +├── stacks # Terraform stacks - combinations of modules +│   ├── ax41-1 # Stack for ax41-1, big 'ol bare-metal server at Hetzner ``` -## Integrate with your tools +The Terraform code is split up into modules so that they are small and easy to understand. The modules are then combined into stacks, which are the actual Terraform configurations that are applied. Currently, there is only one stack, `ax41-1`, which is the stack for the big 'ol bare-metal server at Hetzner. -- [ ] [Set up project integrations](https://gitlab.montage2.de/infrastruktur/tf/-/settings/integrations) - -## Collaborate with your team - -- [ ] [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/) -- [ ] [Set auto-merge](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!). Thanks 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. +The Terraform state is stored in a versioned S3 bucket. The bucket is located in thunfisch's private AWS account. A dedicated AWS credential pair with minimal permissions is saved in the `aws_key.enc` file. This file is encrypted using sops and age. ## 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. +### Prerequisites -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. +- Terraform 1.5.5 (not newer because Hashicorp changed to non-free licensing) +- age (for encrypting & decrypting secrets) +- sops (for encrypting & decrypting secrets) -## Contributing -State if you are open to contributions and what your requirements are for accepting them. +### Deploying -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. +```bash +export SOPS_AGE_KEY_FILE=/path/to/your/private/key +eval $(sops -d aws_key.enc) # Sets the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables +cd stacks/ax41-1 +terraform init +terraform apply +``` -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. +Check, double-check and triple-check the changes that Terraform wants to apply. If everything looks good, type `yes` and hit enter. Terraform will then apply the changes. -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +### Secrets -## License -For open source projects, say how it is licensed. +Secrets are encrypted using [sops](https://github.com/getsops/sops) and [age](https://github.com/FiloSottile/age). The public keys for the age encryption are stored in the repository, so that anyone can encrypt secrets for the repository. Your private key is stored in your password manager and is only available to you. -## 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. +If you want to roll out changes to the actual infrastructure, you need to be able to decrypt the secrets. To do so, your private key needs to be used as a recipient for the age encryption by someone that previously had access to the secrets. If you don't have access to the secrets, ask someone who does. If you don't know who that is, you probably shouldn't be rolling out changes to the infrastructure. + +#### Decrypting Secrets + +To be able to decrypt secrets, sops needs to know where your private key is stored. This is done by setting the `SOPS_AGE_KEY_FILE` environment variable to the path of your private key or passing it directly by setting the `SOPS_AGE_KEY` environment variable. + +You can manually decrypt a file using sops: + +```bash +sops --decrypt stuff.enc.yaml > stuff.yaml +``` + +Terraform is using the [carlpett/sops](https://registry.terraform.io/providers/carlpett/sops/latest/docs) provider to decrypt secrets. This provider is configured to use these environment variables, so you don't need to do anything else. + +#### Encrypting Secrets + +To encrypt secrets, you need to have the public keys of the recipients. These are stored in the repository, so you can just use them. The public keys are stored in the `sops-age-recipients.txt` file. To encrypt a secret, load the public keys from this file to your `SOPS_AGE_RECIPIENTS` environment variable and then use sops to encrypt the secret. + +```bash +export SOPS_AGE_RECIPIENTS="$(cat sops-age-recipients.txt)" +sops --encrypt stuff.yaml > stuff.enc.yaml +``` + +#### Modifying Secrets + +To modify secrets, run `sops stuff.enc.yaml` and edit the file with your default `$EDITOR`. When you save the file, sops will automatically decrypt and re-encrypt the file. Alternatively, you can also use `sops --decrypt stuff.enc.yaml > stuff.yaml` to decrypt the file and then edit it. When you're done, use `sops --encrypt stuff.yaml > stuff.enc.yaml` to re-encrypt the file. Make sure to remove the unencrypted file afterwards. \ No newline at end of file diff --git a/aws_key.enc b/aws_key.enc new file mode 100644 index 0000000..5b6900f --- /dev/null +++ b/aws_key.enc @@ -0,0 +1,20 @@ +{ + "data": "ENC[AES256_GCM,data:JEWQ5oDpbR+mIJpTdrMBoacpUxnUA8J1EAU+0H/XIJurHGD6lveZ5FJusjAHcFHCKuG4zblKUi2OQ1gsF9Nnabfugvr7s1KnuQgqOIWqrhKzhdlj6llbNSIs2eM1pN2esZ5b8G1aBueobfHQXNuaU76kavG547nE1Q==,iv:mz0kG3Mfv2nWZIr+pfj1q9QZdda1IoL2HXE75HVQQss=,tag:oIISoRuNbil3/smqAw8otQ==,type:str]", + "sops": { + "kms": null, + "gcp_kms": null, + "azure_kv": null, + "hc_vault": null, + "age": [ + { + "recipient": "age1zwv4tl8ws6ke8wseenq4lrwcck3el2wandlgztefz9v4qdlnwu7saw7g8z", + "enc": "-----BEGIN AGE ENCRYPTED FILE-----\nYWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSAzOEp1ZDZmSEhDN3hMZDRi\ndXZIVStVbXJVL0hzWmRaNWNoTmVhMURWYkhJCjFXQm13NVY5Rkt5K0FsRHk2cmdx\nVUhQOVc0YXhVQm94Rmt5bnhjSjBTKzQKLS0tIEVsRXk4UTJoYVpCYlRFVFhIVW1l\nMklzSC9kS3BwMGU2SWgxM2ltMWh6RDgKFItY+3CFsLHEjUtmANyoQ+lLA7zfESWy\nkU+z8YNEM5rwECJAdZiqp8/nJalSRfeYYtdzw/7dNxsGGelNgibBKA==\n-----END AGE ENCRYPTED FILE-----\n" + } + ], + "lastmodified": "2024-01-25T17:29:23Z", + "mac": "ENC[AES256_GCM,data:/zhb5hGJLQvfn/1Cqu0CW/Fplq50ohWqif9hIqE9vvhAUp/r7nOSE108dEYA2/mo20yagsf5re9K92zGywPIoPYwKF1Uzm3vWuZnXST5erW3kKuSTVVzt9j3265mWx/uZi+5h+pY4/g1i10qKQV2FF8h1uwOnChSQglLbnlEE2k=,iv:Nqc3G7Ze5dAv/HEbrE1TxJsrtjwxs8A8+okceUy7gC0=,tag:i+mvDXkudii/fGaeISYkmA==,type:str]", + "pgp": null, + "unencrypted_suffix": "_unencrypted", + "version": "3.8.1" + } +} \ No newline at end of file diff --git a/modules/swarm/deckchores/main.tf b/modules/swarm/deckchores/main.tf new file mode 100644 index 0000000..a0bf31b --- /dev/null +++ b/modules/swarm/deckchores/main.tf @@ -0,0 +1,29 @@ +data "docker_registry_image" "deckchores" { + name = "funkyfuture/deck-chores:1" +} + +resource "docker_service" "deckchores" { + name = "deckchores" + + task_spec { + container_spec { + image = "${data.docker_registry_image.deckchores.name}@${data.docker_registry_image.deckchores.sha256_digest}" + + env = { + TIMEZONE = "Europe/Berlin" + DEFAULT_FLAGES = "noservice" + } + + labels { + label = "shepherd.auto-update" + value = "true" + } + + mounts { + target = "/var/run/docker.sock" + source = "/var/run/docker.sock" + type = "bind" + } + } + } +} diff --git a/modules/swarm/deckchores/version.tf b/modules/swarm/deckchores/version.tf new file mode 100644 index 0000000..be1d72e --- /dev/null +++ b/modules/swarm/deckchores/version.tf @@ -0,0 +1,13 @@ +terraform { + required_version = "1.5.5" + required_providers { + hetznerdns = { + source = "timohirt/hetznerdns" + version = "~>2.2" + } + docker = { + source = "kreuzwerker/docker" + version = "~>3.0" + } + } +} diff --git a/modules/swarm/grafana/cfg/grafana.ini b/modules/swarm/grafana/cfg/grafana.ini new file mode 100644 index 0000000..2668dfa --- /dev/null +++ b/modules/swarm/grafana/cfg/grafana.ini @@ -0,0 +1,715 @@ +##################### Grafana Configuration Example ##################### +# +# Everything has defaults so you only need to uncomment things you want to +# change + +# possible values : production, development +;app_mode = production + +# instance name, defaults to HOSTNAME environment variable value or hostname if HOSTNAME var is empty +;instance_name = ${HOSTNAME} + +#################################### Paths #################################### +[paths] +# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used) +;data = /var/lib/grafana + +# Temporary files in `data` directory older than given duration will be removed +;temp_data_lifetime = 24h + +# Directory where grafana can store logs +;logs = /var/log/grafana + +# Directory where grafana will automatically scan and look for plugins +;plugins = /var/lib/grafana/plugins + +# folder that contains provisioning config files that grafana will apply on startup and while running. +;provisioning = conf/provisioning + +#################################### Server #################################### +[server] +# Protocol (http, https, h2, socket) +protocol = http + +# The ip address to bind to, empty will bind to all interfaces +http_addr = 0.0.0.0 + +# The http port to use +http_port = 3000 + +# The public facing domain name used to access grafana from a browser +domain = "grafana.montage2.de" + +# Redirect to correct domain if host header does not match domain +# Prevents DNS rebinding attacks +;enforce_domain = false + +# The full public facing url you use in browser, used for redirects and emails +# If you use reverse proxy and sub path specify full url (with sub path) +;root_url = %(protocol)s://%(domain)s:%(http_port)s/ +root_url = "https://grafana.montage2.de/" + +# Serve Grafana from subpath specified in `root_url` setting. By default it is set to `false` for compatibility reasons. +;serve_from_sub_path = false + +# Log web requests +;router_logging = false + +# the path relative working path +;static_root_path = public + +# enable gzip +;enable_gzip = false + +# https certs & key file +;cert_file = +;cert_key = + +# Unix socket path +;socket = + +#################################### Database #################################### +[database] +# You can configure the database connection by specifying type, host, name, user and password +# as separate properties or as on string using the url properties. + +# Either "mysql", "postgres" or "sqlite3", it's your choice +type = sqlite3 +;host = 127.0.0.1:3306 +;name = grafana +;user = root +# If the password contains # or ; you have to wrap it with triple quotes. Ex """#password;""" +;password = + +# Use either URL or the previous fields to configure the database +# Example: mysql://user:secret@host:port/database +;url = + +# For "postgres" only, either "disable", "require" or "verify-full" +;ssl_mode = disable + +;ca_cert_path = +;client_key_path = +;client_cert_path = +;server_cert_name = + +# For "sqlite3" only, path relative to data_path setting +;path = grafana.db + +# Max idle conn setting default is 2 +;max_idle_conn = 2 + +# Max conn setting default is 0 (mean not set) +;max_open_conn = + +# Connection Max Lifetime default is 14400 (means 14400 seconds or 4 hours) +;conn_max_lifetime = 14400 + +# Set to true to log the sql calls and execution times. +;log_queries = + +# For "sqlite3" only. cache mode setting used for connecting to the database. (private, shared) +;cache_mode = private + +#################################### Cache server ############################# +[remote_cache] +# Either "redis", "memcached" or "database" default is "database" +;type = database + +# cache connectionstring options +# database: will use Grafana primary database. +# redis: config like redis server e.g. `addr=127.0.0.1:6379,pool_size=100,db=0,ssl=false`. Only addr is required. ssl may be 'true', 'false', or 'insecure'. +# memcache: 127.0.0.1:11211 +;connstr = + +#################################### Data proxy ########################### +[dataproxy] + +# This enables data proxy logging, default is false +;logging = false + +# How long the data proxy should wait before timing out default is 30 (seconds) +;timeout = 30 + +# If enabled and user is not anonymous, data proxy will add X-Grafana-User header with username into the request, default is false. +;send_user_header = false + +#################################### Analytics #################################### +[analytics] +# Server reporting, sends usage counters to stats.grafana.org every 24 hours. +# No ip addresses are being tracked, only simple counters to track +# running instances, dashboard and error counts. It is very helpful to us. +# Change this option to false to disable reporting. +reporting_enabled = false + +# Set to false to disable all checks to https://grafana.net +# for new vesions (grafana itself and plugins), check is used +# in some UI views to notify that grafana or plugin update exists +# This option does not cause any auto updates, nor send any information +# only a GET request to http://grafana.com to get latest versions +;check_for_updates = true + +# Google Analytics universal tracking code, only enabled if you specify an id here +;google_analytics_ua_id = + +# Google Tag Manager ID, only enabled if you specify an id here +;google_tag_manager_id = + +#################################### Security #################################### +[security] +# disable creation of admin user on first start of grafana +;disable_initial_admin_creation = false + +# default admin user, created on startup +admin_user = admin + +# default admin password, can be changed before first start of grafana, or in profile settings +#admin_password = hunter2 + +# used for signing +#secret_key = hunter42 + +# disable gravatar profile images +;disable_gravatar = false + +# data source proxy whitelist (ip_or_domain:port separated by spaces) +;data_source_proxy_whitelist = + +# disable protection against brute force login attempts +;disable_brute_force_login_protection = false + +# set to true if you host Grafana behind HTTPS. default is false. +cookie_secure = true + +# set cookie SameSite attribute. defaults to `lax`. can be set to "lax", "strict", "none" and "disabled" +;cookie_samesite = lax + +# set to true if you want to allow browsers to render Grafana in a ,