diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index 50abd6d..e65ef75 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -1,14 +1,16 @@
# purpose: run Continuous Integration (build, unit test, lint, scan)
-# variables: [ SONAR_HOST_URL, SONAR_ORG, SONAR_PROJECT_KEY ]
-# secrets: [ SONAR_TOKEN ]
+# variables: [SONAR_HOST_URL, SONAR_ORG, SONAR_PROJECT_KEY]
+# secrets: [SONAR_TOKEN]
name: CI
on:
push:
- branches: ["main"]
+ branches:
+ - main
pull_request:
- branches: ["main"]
+ branches:
+ - main
workflow_dispatch: {}
concurrency:
@@ -31,17 +33,17 @@ jobs:
uses: actions/checkout@v4
with:
repository: devpro/github-workflow-parts
- ref: feature/sonar-login-deprecation
+ ref: main
path: workflow-parts
- name: Start MongoDB
uses: ./workflow-parts/mongodb/start
- - name: Initialize database
+ - name: Initialize database (indexes, tenants & users)
run: |
- mongosh mongodb://localhost:27017/terraform_backend_dev scripts/mongo-create-index.js
- sudo apt-get -y install apache2-utils
- ./scripts/mongo-create-user.sh admin admin123 dummy
- mongosh mongodb://localhost:27017/terraform_backend_dev scripts/add-user.js
+ ./scripts/tfbeadm create-indexes
+ ./scripts/tfbeadm create-user admin admin123 dummy
shell: bash
+ env:
+ MONGODB_URI: mongodb://localhost:27017/terraform_backend_dev
- name: Build, lint & test
uses: ./workflow-parts/dotnet/build-lint-test
with:
@@ -62,7 +64,7 @@ jobs:
uses: actions/checkout@v3
with:
repository: devpro/github-workflow-parts
- ref: feature/sonar-login-deprecation
+ ref: main
path: workflow-parts
- name: Create and scan container image
uses: ./workflow-parts/docker/build-scan
diff --git a/.github/workflows/pages.yaml b/.github/workflows/pages.yaml
new file mode 100644
index 0000000..c3fbadc
--- /dev/null
+++ b/.github/workflows/pages.yaml
@@ -0,0 +1,32 @@
+name: Pages
+
+on:
+ push:
+ branches:
+ - main
+ workflow_dispatch: {}
+
+permissions:
+ contents: write
+
+jobs:
+ deploy:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - name: Configure Git Credentials
+ run: |
+ git config user.name github-actions[bot]
+ git config user.email 41898282+github-actions[bot]@users.noreply.github.com
+ - uses: actions/setup-python@v5
+ with:
+ python-version: 3.x
+ - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
+ - uses: actions/cache@v4
+ with:
+ key: mkdocs-material-${{ env.cache_id }}
+ path: ~/.cache
+ restore-keys: |
+ mkdocs-material-
+ - run: pip install mkdocs-material
+ - run: mkdocs gh-deploy --force
diff --git a/.github/workflows/pkg.yaml b/.github/workflows/pkg.yaml
index cd9a3b0..6f8fc46 100644
--- a/.github/workflows/pkg.yaml
+++ b/.github/workflows/pkg.yaml
@@ -1,13 +1,13 @@
# purpose: run Continuous Delivery / Packaging (package)
# variables: []
-# secrets: [ DOCKERHUB_USERNAME, DOCKERHUB_TOKEN ]
-
+# secrets: [DOCKERHUB_USERNAME, DOCKERHUB_TOKEN]
+
name: PKG
on:
push:
- branches: ["main"]
- # tags: [ 'v*.*.*' ]
+ branches:
+ - main
workflow_dispatch: {}
jobs:
diff --git a/.gitignore b/.gitignore
index 056db93..d7c48f7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -356,6 +356,3 @@ appsettings.Development.json
.terraform/
.terraform.lock.hcl
errored.tfstate
-
-# temp script files
-scripts/add-user.js
diff --git a/.markdownlint.yml b/.markdownlint.yml
new file mode 100644
index 0000000..03c928b
--- /dev/null
+++ b/.markdownlint.yml
@@ -0,0 +1,5 @@
+# ref. https://github.com/DavidAnson/markdownlint
+default: true
+MD013:
+ line_length: 240
+MD046: false
diff --git a/.yamllint.yaml b/.yamllint.yaml
new file mode 100644
index 0000000..f8ef3a1
--- /dev/null
+++ b/.yamllint.yaml
@@ -0,0 +1,10 @@
+# ref. https://yamllint.readthedocs.io/en/stable/configuration.html
+extends: default
+rules:
+ document-start: disable
+ line-length:
+ level: warning
+ max: 120
+ truthy: disable
+ tags:
+ disable: true
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 53a0106..2f50bea 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,10 +1,8 @@
-# Project development guide
+# Contribution guide
-## Design
+## Application codebase
-The application is entirely based on open-source, cross-platform (Linux/Windows), highly performant, free, object-oriented technologies: .NET / C#.
-
-### Projects
+### .NET projects
Project name | Technology | Project type
---------------------------|------------|---------------------------
@@ -15,7 +13,7 @@ Project name | Technology | Project type
`Infrastructure.MongoDb` | .NET 8 | Library
`WebApi` | ASP.NET 8 | Web application (REST API)
-### Packages (NuGet)
+### .NET packages (NuGet)
Name | Description
-------------------------|-----------------------------
@@ -24,60 +22,33 @@ Name | Description
`Swashbuckle.AspNetCore` | OpenAPI / Swagger generation
`System.Text.Json` | JSON support
-### Documentation
-
-* [OpenTofu](https://opentofu.org/)
-* [MongoDB](https://www.mongodb.com/)
-* [Terraform](https://www.terraform.io)
- * [HTTP backend](https://developer.hashicorp.com/terraform/language/backend/http)
- * [Remote state backend](https://github.com/hashicorp/terraform/tree/main/internal/backend/remote-state).
-
-### References of other implementations
-
-* [GitLab](https://gitlab.com/gitlab-org/manage/import/gitlab/-/blob/master/doc/user/infrastructure/terraform_state.md)
- * [lib/api/terraform/state.rb](https://gitlab.com/gitlab-org/manage/import/gitlab/-/blob/master/lib/api/terraform/state.rb)
-* HTTP
- * [akshay/terraform-http-backend-pass](https://git.coop/akshay/terraform-http-backend-pass)
- * [bhoriuchi/terraform-backend-http](https://github.com/bhoriuchi/terraform-backend-http)
-* git
- * [plumber-cd/terraform-backend-git](https://github.com/plumber-cd/terraform-backend-git)
-
-## Automation
+### Terraform specifications
-### Build (CI/CD pipelines)
+- [HTTP backend](https://developer.hashicorp.com/terraform/language/backend/http)
+- [Remote state backend](https://github.com/hashicorp/terraform/tree/main/internal/backend/remote-state)
-GitHub Actions are triggered to automate the integration and delivery of the application:
+### Other community implementations
-- [CI](.github/workflows/ci.yaml)
-- [PKG](.github/workflows/pkg.yaml)
-
-GitHub project has been configured, in **General** / **Security** / **Secrets and Variables** / **Actions**:
-
-- DOCKERHUB_TOKEN
-- DOCKERHUB_USERNAME
-- SONAR_HOST_URL
-- SONAR_ORG
-- SONAR_PROJECT_KEY
-- SONAR_TOKEN
+- [GitLab](https://gitlab.com/gitlab-org/manage/import/gitlab/-/blob/master/doc/user/infrastructure/terraform_state.md)
+ - [lib/api/terraform/state.rb](https://gitlab.com/gitlab-org/manage/import/gitlab/-/blob/master/lib/api/terraform/state.rb)
+- HTTP
+ - [akshay/terraform-http-backend-pass](https://git.coop/akshay/terraform-http-backend-pass)
+ - [bhoriuchi/terraform-backend-http](https://github.com/bhoriuchi/terraform-backend-http)
+ - [nimbolus/terraform-backend](https://github.com/nimbolus/terraform-backend)
+- git
+ - [plumber-cd/terraform-backend-git](https://github.com/plumber-cd/terraform-backend-git)
## Procedures
### Run locally the application
-Create/have a MongoDB database (example with a local container but you can provision a cluster in MongoDB Atlas):
+Run MongoDB in a database and add the indexes and test tenant/user:
```bash
-# creates a container
docker run --name mongodb -d -p 27017:27017 mongo:8.0
-# (optional) adds indexes for optimal performances
-docker run --rm --link mongodb \
- -v "$(pwd)/scripts":/home/scripts mongo:8.0 \
- bash -c "mongosh mongodb://mongodb:27017/terraform_backend_dev /home/scripts/mongo-create-index.js"
-# creates one user
-./scripts/mongo-create-user.sh admin admin123 dummy
-docker run --rm --link mongodb \
- -v "$(pwd)/scripts":/home/scripts mongo:8.0 \
- bash -c "mongosh mongodb://mongodb:27017/terraform_backend_dev /home/scripts/add-user.js"
+MONGODB_CONTAINERNAME=mongodb
+./scripts/tfbeadm create-indexes
+./scripts/tfbeadm create-user admin admin123 dummy
```
Run the web API (example with the command line but an IDE like Visual Studio or Rider would be nice to be able to debug):
@@ -88,8 +59,12 @@ dotnet run --project src/WebApi
Open Swagger in a browser: [localhost:5293/swagger](http://localhost:5293/swagger).
-## Backlog
+## Documentation codebase
+
+The documentation is a static website built with [Material for MkDocs](https://squidfunk.github.io/mkdocs-material/).
-### New features
+Run locally with:
-* Store only one version of the state in tf_state and save the others in tf_state_revision
+```bash
+docker run --rm -it -p 8000:8000 -v ${PWD}:/docs squidfunk/mkdocs-material
+```
diff --git a/LICENSE b/LICENSE
index f288702..0ad25db 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,5 +1,5 @@
- GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
@@ -7,17 +7,15 @@
Preamble
- The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom to
+our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
-software for all its users. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
-your programs, too.
+software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
@@ -26,44 +24,34 @@ them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
The precise terms and conditions for copying, distribution and
modification follow.
@@ -72,7 +60,7 @@ modification follow.
0. Definitions.
- "This License" refers to version 3 of the GNU General Public License.
+ "This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
@@ -549,35 +537,45 @@ to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
- 13. Use with the GNU Affero General Public License.
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
+under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU General
+Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
+GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
+versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
@@ -635,40 +633,29 @@ the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program 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
+ it under the terms of the GNU Affero General Public License as published
+ by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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.
+ GNU Affero General Public License for more details.
- You should have received a copy of the GNU General Public License
+ You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
- Copyright (C)
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
+For more information on this, and how to apply and follow the GNU AGPL, see
.
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-.
diff --git a/README.md b/README.md
index fc24a94..d43226e 100644
--- a/README.md
+++ b/README.md
@@ -1,43 +1,17 @@
# MongoDB HTTP backend for Terraform/OpenTofu state
[](https://github.com/devpro/terraform-backend-mongodb/actions/workflows/ci.yaml)
+[](https://github.com/devpro/terraform-backend-mongodb/actions/workflows/pages.yaml)
[](https://github.com/devpro/terraform-backend-mongodb/actions/workflows/pkg.yaml)
[](https://sonarcloud.io/summary/new_code?id=devpro_terraform-backend-mongodb)
[](https://hub.docker.com/r/devprofr/terraform-backend-mongodb)
Manage Terraform/OpenTofu state through a secured REST API and take advatange of MongoDB greatness!
-The [project development guide](CONTRIBUTING.md) provides the implementation details.
+## Getting started
-## Quick start
+Best place to start is the [documentation website](https://devpro.github.io/terraform-backend-mongodb/).
-1. Make sure a you have access to a MongoDB database
+## Going further
-2. Configure the application with the MongoDB database connection information
-
-2. Run the web API
-
-3. Update the Terraform file
-
-```tf
-terraform {
- backend "http" {
- address = "//state/"
- lock_address = "//state//lock"
- unlock_address = "//state//lock"
- lock_method = "POST"
- unlock_method = "DELETE"
- username = ""
- password = ""
- # uncomment if HTTPS certificate is not valid
- # skip_cert_verification = "true"
- }
-}
-```
-
-4. Execute usual Terraform command lines
-
-## Samples
-
-* [Make local actions on files](samples/local-files/README.md)
-* [Run NGINX container with Docker](samples/docker-nginx/README.md)
+Technical implementation is described in the [contribution guide](CONTRIBUTING.md).
diff --git a/Devpro.TerraformBackend.sln b/TerraformBackend.sln
similarity index 100%
rename from Devpro.TerraformBackend.sln
rename to TerraformBackend.sln
diff --git a/docs/.gitkeep b/docs/.gitkeep
deleted file mode 100644
index e69de29..0000000
diff --git a/docs/index.md b/docs/index.md
new file mode 100644
index 0000000..d89c9e8
--- /dev/null
+++ b/docs/index.md
@@ -0,0 +1,11 @@
+# Welcome
+
+This project provides an HTTP backend for [Terraform](https://www.terraform.io) and [OpenTofu](https://opentofu.org/) that will save and manage state data in a [MongoDB](https://www.mongodb.com/) database.
+
+As the state is a JSON content, it makes sense to use the best-in-class database technology to work with it.
+
+The goal is to:
+
+- provide an highly available, and performant, storage
+- share a secured access to sensitive information
+- value the infrastructure data
diff --git a/docs/project.md b/docs/project.md
new file mode 100644
index 0000000..4a70c93
--- /dev/null
+++ b/docs/project.md
@@ -0,0 +1,37 @@
+# Project
+
+## Automation
+
+### CI/CD pipelines
+
+GitHub Actions are triggered to automate the integration and delivery of the application:
+
+Role | Definition file
+----------|-------------------------------
+**CI** | `.github/workflows/ci.yaml`
+**Pages** | `.github/workflows/pages.yaml`
+**PKG** | `.github/workflows/pkg.yaml`
+
+GitHub configuration (**General** / **Security** / **Secrets and Variables** / **Actions**):
+
+- DOCKERHUB_TOKEN
+- DOCKERHUB_USERNAME
+- SONAR_HOST_URL
+- SONAR_ORG
+- SONAR_PROJECT_KEY
+- SONAR_TOKEN
+
+## Backlog
+
+### V2.0
+
+New features:
+
+- :material-square: Store in the database only one version of the state in tf_state (the latest) and save the others in tf_state_revision
+- :material-square: Send traces, logs, metrics to OpenTelemetry Collector
+
+## Design
+
+### Programming languages
+
+The code is mainly written in C# / .NET: open-source, cross-platform (Linux/Windows), highly performant, object-oriented.
diff --git a/docs/quickstart.md b/docs/quickstart.md
new file mode 100644
index 0000000..1668a1a
--- /dev/null
+++ b/docs/quickstart.md
@@ -0,0 +1,22 @@
+# Quickstart
+
+## Demo
+
+Before looking at all the options, let's do a quick demonstration of the application.
+
+=== "Containers (Docker Compose)"
+
+ ```bash
+ docker compose
+ ```
+
+=== "Kubernetes (Helm)"
+
+ ```bash
+ helm upgrade --install tfbackend https://github.com/devpro/helm-charts/releases/download/terraform-backend-mongodb-0.1.0/terraform-backend-mongodb-0.1.0.tgz --create-namespace --namespace tfbackend
+ ```
+
+## Samples
+
+* Make local actions on files: `samples/local-files/README.md`
+* Run NGINX container with Docker: `samples/docker-nginx/README.md`
diff --git a/docs/setup.md b/docs/setup.md
new file mode 100644
index 0000000..7fc4dd3
--- /dev/null
+++ b/docs/setup.md
@@ -0,0 +1,84 @@
+# Setup
+
+## Requirements
+
+### Database server
+
+Make sure you have access to a MongoDB database (with a connection string containing a user that have admin permissions).
+
+The MongoDB server can run:
+
+- On a machine from binaries
+- On multiple machines binaries
+- In a container
+- In a Kubernetes cluster
+- In MongoDB Atlas (free tier available!)
+
+!!! warning
+
+ Double check any network/security restrictions such as MongoDB IP access list as the application needs to access the MongoDB server
+
+### Database indexes
+
+Add indexes for optimal performances:
+
+```bash
+MONGODB_URI=mongodb://:27017/
+curl -O https://raw.githubusercontent.com/devpro/terraform-backend-mongodb/refs/heads/main/scripts/tfbeadm
+tfbeadm create-indexes
+```
+
+!!! warning
+
+ `mongosh` or `Docker` packages must be available on the machine running the commands
+
+## Installation
+
+### Kubernetes
+
+Use the official Helm chart:
+
+```bash
+# adds the chart repository
+helm repo add devpro https://devpro.github.io/helm-charts
+helm repo update
+
+# installs the chart
+helm upgrade --install tfbackend devpro/terraform-backend-mongodb [-f values.yaml] --create-namespace --namespace tfbackend
+```
+
+Values file examples:
+
+=== "Embedded MongoDB chart"
+
+ ```yaml
+ mongodb:
+ enabled: true
+ auth:
+ rootPassword: admin
+ webapi:
+ db:
+ connectionString: mongodb://root:admin@tfbackend-mongodb:27017/terraform_backend_beta?authSource=admin
+ databaseName: terraform_backend_beta
+ ```
+
+=== "Traefik Ingress with Let's Encrypt cert-manager issuer"
+
+ ```yaml
+ webapi:
+ host: tfbackend.mydomain
+ ingress:
+ enabled: true
+ className: traefik
+ annotations:
+ cert-manager.io/cluster-issuer: letsencrypt-prod
+ ```
+
+=== "Development environment with Swagger"
+
+ ```yaml
+ dotnet:
+ environment: Development
+ enableSwagger: true
+ enableOpenTelemetry: false
+ ```
diff --git a/docs/usage.md b/docs/usage.md
new file mode 100644
index 0000000..b57bab8
--- /dev/null
+++ b/docs/usage.md
@@ -0,0 +1,34 @@
+# Usage
+
+## Tenant authentication
+
+API calls are secured through tenant isolation and user authentication, which are stored in the MongoDB database.
+
+You can add a user with the following commands (replace the parameters):
+
+```bash
+MONGODB_URI=mongodb://:27017/
+curl -O https://raw.githubusercontent.com/devpro/terraform-backend-mongodb/refs/heads/main/scripts/tfbeadm
+tfbeadm create-user
+```
+
+## Client configuration
+
+In the tf file, configure the backend to use the REST API:
+
+```tf
+terraform {
+ backend "http" {
+ address = "http:////state/"
+ lock_address = "http:////state//lock"
+ unlock_address = "http:////state//lock"
+ lock_method = "POST"
+ unlock_method = "DELETE"
+ username = ""
+ password = ""
+ #skip_cert_verification = "true"
+ }
+}
+```
+
+And now, you can take advantage of a MongoDB backend for your Terraform/OpenTofu actions!
diff --git a/mkdocs.yml b/mkdocs.yml
new file mode 100644
index 0000000..84ee1d9
--- /dev/null
+++ b/mkdocs.yml
@@ -0,0 +1,42 @@
+site_name: Terraform Backend MongoDB
+theme:
+ name: material
+ # logo: assets/logo.png
+ # favicon: images/favicon.png
+ language: en
+ features:
+ - navigation.footer
+ - content.tabs.link
+ - navigation.tabs
+ - navigation.path
+ - toc.integrate
+ palette:
+ - media: "(prefers-color-scheme: dark)"
+ scheme: slate
+ toggle:
+ icon: material/brightness-4
+ name: Switch to light mode
+ - media: "(prefers-color-scheme: light)"
+ scheme: default
+ toggle:
+ icon: material/brightness-7
+ name: Switch to dark mode
+repo_url: https://github.com/devpro/terraform-backend-mongodb
+extra:
+ generator: false
+nav:
+ - index.md
+ - quickstart.md
+ - setup.md
+ - usage.md
+ - project.md
+markdown_extensions:
+ - admonition
+ - pymdownx.details
+ - pymdownx.superfences
+ - pymdownx.tabbed:
+ alternate_style: true
+ - attr_list
+ - pymdownx.emoji:
+ emoji_index: !!python/name:material.extensions.emoji.twemoji
+ emoji_generator: !!python/name:material.extensions.emoji.to_svg
diff --git a/samples/docker-nginx/README.md b/samples/docker-nginx/README.md
index 8c1fba6..ef52b1e 100644
--- a/samples/docker-nginx/README.md
+++ b/samples/docker-nginx/README.md
@@ -10,7 +10,7 @@ The following tools must be available from the command line:
- [.NET](https://dotnet.microsoft.com/download) or an IDE (Visual Studio or Rider)
- [Terraform](https://developer.hashicorp.com/terraform/install) or [OpenTofu](https://opentofu.org/docs/intro/install/)
- Docker
-
+
## Workflow
Run the application (example given for information but feel free to start from the IDE):
diff --git a/scripts/mongo-create-index.js b/scripts/mongo-create-index.js
deleted file mode 100644
index a9d2879..0000000
--- a/scripts/mongo-create-index.js
+++ /dev/null
@@ -1,2 +0,0 @@
-db.tf_state.createIndex({ "tenant": 1, "name": 1 });
-db.tf_state_lock.createIndex({ "tenant": 1, "name": 1 });
diff --git a/scripts/mongo-create-user.sh b/scripts/mongo-create-user.sh
deleted file mode 100755
index 9f2ca5b..0000000
--- a/scripts/mongo-create-user.sh
+++ /dev/null
@@ -1,39 +0,0 @@
-#!/bin/bash
-
-if [ "$#" -ne 3 ]; then
- echo "Usage: $0 "
- exit 1
-fi
-
-USERNAME="$1"
-PASSWORD="$2"
-TENANT="$3"
-
-if ! command -v htpasswd &> /dev/null; then
- echo "Error: htpasswd is not installed."
- echo "Please install apache2-utils (on Debian/Ubuntu) or httpd-tools (on CentOS/RHEL)."
- echo "Installation commands:"
- echo " Debian/Ubuntu: sudo apt-get install apache2-utils"
- echo " CentOS/RHEL: sudo yum install httpd-tools"
- exit 1
-fi
-
-SCRIPT_DIR=$(dirname "$(realpath "$0")")
-JS_FILE="$SCRIPT_DIR/add-user.js"
-
-HASH=$(htpasswd -bnBC 10 "" "$PASSWORD" | tr -d ':\n')
-if [ $? -ne 0 ] || [ -z "$HASH" ]; then
- echo "Error: Failed to generate BCrypt hash."
- exit 1
-fi
-
-cat > "$JS_FILE" << EOF
-db.user.insertOne({
- username: '$USERNAME',
- password_hash: '$HASH',
- tenant: '$TENANT'
-});
-db.user.createIndex({ "username": 1 }, { unique: true });
-EOF
-
-echo "Generated "$JS_FILE" successfully"
diff --git a/scripts/tfbeadm b/scripts/tfbeadm
new file mode 100755
index 0000000..491c9e4
--- /dev/null
+++ b/scripts/tfbeadm
@@ -0,0 +1,202 @@
+#!/bin/bash
+
+MONGODB_URI="${MONGODB_URI:-mongodb://mongodb:27017/test}"
+#MONGODB_CONTAINERNAME
+MONGODB_VERSION="${MONGODB_VERSION:-8.0}"
+
+MONGODB_INDEX_COMMANDS=(
+ 'db.tf_state.createIndex({"tenant": 1, "name": 1})'
+ 'db.tf_state_lock.createIndex({"tenant": 1, "name": 1}, {unique: true})'
+ 'db.user.createIndex({"username": 1}, {unique: true})'
+)
+
+log_info() {
+ local message="$1"
+ echo -e "$message"
+}
+
+log_header() {
+ local message="$1"
+ echo -e "\033[1;34m$message\033[0m" # blue
+}
+
+log_success() {
+ local message="$1"
+ echo -e "\033[1;32m$message\033[0m" # green
+}
+
+log_warn() {
+ local message="$1"
+ echo -e "\033[1;33mWarn: $message\033[0m" # yello
+}
+
+log_error() {
+ local message="$1"
+ echo -e "\033[1;31mError: $message\033[0m" # red
+}
+
+usage() {
+ echo -e "\033[1;34mUsage:\033[0m $0 [command] [arguments...]"
+ echo -e "\033[1;34mCommands:\033[0m"
+ echo " create-indexes : Create indexes in database"
+ echo " create-user : Create user in database"
+ echo " help : Show this help message"
+ # echo " (no arguments) : Run in interactive mode"
+ exit 1
+}
+
+check_command() {
+ local cmd=$1
+ if command -v "$cmd" &> /dev/null; then
+ return 0
+ else
+ return 1
+ fi
+}
+
+check_htpasswd() {
+ if ! command -v htpasswd &> /dev/null; then
+ log_error "htpasswd is not installed."
+ log_info "Please install apache2-utils (on Debian/Ubuntu) or httpd-tools (on CentOS/RHEL)."
+ log_info "Installation commands:"
+ log_info " Debian/Ubuntu: sudo apt-get install apache2-utils"
+ log_info " CentOS/RHEL: sudo yum install httpd-tools"
+ exit 1
+ fi
+}
+
+execute_mongosh() {
+ local mongodb_cmd="$1"
+ if check_command "mongosh"; then
+ execute_mongosh_package "$mongodb_cmd" || return 1
+ else
+ if check_command "docker"; then
+ if [[ -n "$MONGODB_CONTAINERNAME" ]]; then
+ execute_mongosh_docker_link "$mongodb_cmd" || return 1
+ else
+ execute_mongosh_docker "$mongodb_cmd" || return 1
+ fi
+ else
+ echo "Error: Neither mongosh nor Docker is installed. Please install one to proceed."
+ return 1
+ fi
+ fi
+}
+
+execute_mongosh_package() {
+ local mongodb_cmd="$1"
+ log_info "Executing MongoDB command in the shell: $mongodb_cmd"
+ if output=$(mongosh "$MONGODB_URI" --quiet --eval "$mongodb_cmd" 2>&1); then
+ log_info "Output:\n$output"
+ else
+ log_warn "$output"
+ return 1
+ fi
+}
+
+execute_mongosh_docker() {
+ local mongodb_cmd="$1"
+ log_info "Executing MongoDB command in a container: $mongodb_cmd"
+ if output=$(docker run --rm "mongo:$MONGODB_VERSION" bash -c "mongosh \"$MONGODB_URI\" --quiet --eval \"$mongodb_cmd\"" 2>&1); then
+ log_info "Output:\n$output"
+ else
+ log_warn "$output"
+ return 1
+ fi
+}
+
+execute_mongosh_docker_link() {
+ local mongodb_cmd="$1"
+ log_info "Executing MongoDB command in a container with a link: $mongodb_cmd"
+ if output=$(docker run --rm --link "$MONGODB_CONTAINERNAME" "mongo:$MONGODB_VERSION" bash -c "mongosh \"$MONGODB_URI\" --quiet --eval \"$mongodb_cmd\"" 2>&1); then
+ log_info "Output:\n$output"
+ else
+ log_warn "$output"
+ return 1
+ fi
+}
+
+create_indexes() {
+ local status=0
+ log_header "Creating predefined MongoDB indexes"
+ for cmd in "${MONGODB_INDEX_COMMANDS[@]}"; do
+ execute_mongosh "$cmd" || status=1
+ done
+ if [ $status -eq 0 ]; then
+ log_success "All indexes created successfully"
+ else
+ log_error "One or more index creations failed"
+ fi
+ return $status
+}
+
+create_user() {
+ local username=$1
+ local password=$2
+ local tenant=$3
+ log_header "Creating user"
+
+ hash=$(htpasswd -bnBC 10 "" "$password" | tr -d ':\n')
+ if [ $? -ne 0 ] || [ -z "$hash" ]; then
+ log_error "Failed to generate BCrypt hash"
+ exit 1
+ fi
+
+ creation_command=$(cat < TryGetSection("Application:IsOpenTelemetryEnabled").Get();
+ public bool IsOpenTelemetryEnabled => TryGetSection("Application:IsOpenTelemetryEnabled");
- public bool IsHttpsRedirectionEnabled => TryGetSection("Application:IsHttpsRedirectionEnabled").Get();
+ public bool IsHttpsRedirectionEnabled => TryGetSection("Application:IsHttpsRedirectionEnabled");
- public bool IsSwaggerEnabled => TryGetSection("Application:IsSwaggerEnabled").Get();
+ public bool IsSwaggerEnabled => TryGetSection("Application:IsSwaggerEnabled");
// definitions
public static string HealthCheckEndpoint => "/health";
- public OpenApiInfo OpenApi => TryGetSection("OpenApi").Get() ?? throw new Exception("");
+ public OpenApiInfo OpenApi => TryGetSection("OpenApi");
- public string OpenTelemetryService => TryGetSection("OpenTelemetry:ServiceName").Get() ?? "";
+ public string OpenTelemetryService => TryGetSection("OpenTelemetry:ServiceName");
// infrastructure
- public string OpenTelemetryCollectorEndpoint => TryGetSection("OpenTelemetry:CollectorEndpoint").Get() ?? "";
+ public string OpenTelemetryCollectorEndpoint => TryGetSection("OpenTelemetry:CollectorEndpoint");
// protected methods
- protected IConfigurationSection TryGetSection(string sectionKey)
+ protected T TryGetSection(string sectionKey)
{
- return ConfigurationRoot.GetSection(sectionKey)
- ?? throw new ArgumentException("Missing section \"" + sectionKey + "\" in configuration", nameof(sectionKey));
+ var section = ConfigurationRoot.GetSection(sectionKey)
+ ?? throw new ArgumentException($"Missing section \"{sectionKey}\" in configuration", nameof(sectionKey));
+ return section.Get()
+ ?? throw new ArgumentException($"Section \"{sectionKey}\" value cannot be read as \"{nameof(T)}\"", nameof(sectionKey));
}
}
diff --git a/src/Domain/Models/StateLockModel.cs b/src/Domain/Models/StateLockModel.cs
index 1fd6e35..af0be9b 100644
--- a/src/Domain/Models/StateLockModel.cs
+++ b/src/Domain/Models/StateLockModel.cs
@@ -15,7 +15,7 @@ public class StateLockModel
public string Id { get; set; } = null!;
///
- ///
+ ///
///
public string Tenant { get; set; } = string.Empty;
diff --git a/src/WebApi/ApplicationConfiguration.cs b/src/WebApi/ApplicationConfiguration.cs
index bc58750..2985dc8 100644
--- a/src/WebApi/ApplicationConfiguration.cs
+++ b/src/WebApi/ApplicationConfiguration.cs
@@ -8,7 +8,7 @@ public class ApplicationConfiguration(IConfigurationRoot configurationRoot)
public MongoDbConfiguration MongoDbConfiguration =>
new()
{
- ConnectionString = ConfigurationRoot.GetConnectionString(TryGetSection("MongoDb:ConnectionStringName")?.Get() ?? string.Empty) ?? string.Empty,
- DatabaseName = TryGetSection("MongoDb:DatabaseName").Get() ?? string.Empty
+ ConnectionString = ConfigurationRoot.GetConnectionString(TryGetSection("MongoDb:ConnectionStringName")) ?? string.Empty,
+ DatabaseName = TryGetSection("MongoDb:DatabaseName")
};
}
diff --git a/src/WebApi/Program.cs b/src/WebApi/Program.cs
index 62ae714..4e8f7eb 100644
--- a/src/WebApi/Program.cs
+++ b/src/WebApi/Program.cs
@@ -21,5 +21,5 @@
// runs the application
app.Run();
-// adds explicit class definition for integration test project
+[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "S1118:Utility classes should not have public constructors", Justification = "Explicit class definition needed for integration test project")]
public partial class Program { }
diff --git a/src/WebApi/WebApi.csproj b/src/WebApi/WebApi.csproj
index 2ea7686..ddf1ad0 100644
--- a/src/WebApi/WebApi.csproj
+++ b/src/WebApi/WebApi.csproj
@@ -10,10 +10,6 @@
78fb2134-a177-45da-a7e1-5800154c5f5b
-
-
-
-
diff --git a/src/WebApi/appsettings.json b/src/WebApi/appsettings.json
index e8a6552..2e90252 100644
--- a/src/WebApi/appsettings.json
+++ b/src/WebApi/appsettings.json
@@ -19,7 +19,7 @@
"DatabaseName": "terraform_backend_dev"
},
"OpenApi": {
- "Title": "Terraform Backend (REST API)",
- "Version": "v1.0"
+ "Title": "Terraform Backend MongoDB",
+ "Version": "v1.1"
}
}
diff --git a/test/WebApi.IntegrationTests/Behaviors/InvalidModelStateBehaviorTest.cs b/test/WebApi.IntegrationTests/Behaviors/InvalidModelStateBehaviorTest.cs
index e5f763b..5745b9f 100644
--- a/test/WebApi.IntegrationTests/Behaviors/InvalidModelStateBehaviorTest.cs
+++ b/test/WebApi.IntegrationTests/Behaviors/InvalidModelStateBehaviorTest.cs
@@ -26,7 +26,7 @@ public async Task InvalidModelStateBehavior_OnInvalidModelState_LogsWarning()
});
});
var invalidModel = new { Name = (string?)null };
- var name = Faker.Random.Word();
+ var name = Faker.Random.AlphaNumeric(8);
// Act
var response = await client.PostAsync($"/dummy/state/{name}/lock", Serialize(invalidModel));