# Install in cloud with Terraform

Install Platforma in AWS or Google Cloud with the Terraform modules.

Other ways: [Install in cloud with installer](/install-cloud-installer/), [Install in custom infrastructure](/install-custom-infrastructure/), [Install in Single Server mode](/install-single-server/).

The cloud-specific Terraform modules (The Terraform modules platforma-tf-cloud-base and platforma-tf-cloud-cluster. There is one pair for each cloud, AWS and Google Cloud. The roots cloud and cluster apply them. They make the network, the Kubernetes cluster, the storage, the cloud identities and the registry caches. They give the hand-off file cluster_config to the cloud-agnostic Terraform modules.) make the cluster and all its cloud parts. Then the cloud-agnostic Terraform modules (The Terraform modules platforma-tf-services-cluster and platforma-tf-services. They do not depend on the infrastructure and install Platforma into any cluster that meets the Kubernetes contract, in a cloud or in the company's own infrastructure.), the same as for any cluster, install Platforma. Each module checks its inputs before it changes anything. You apply three Terraform roots, one after the other: `cloud`, `cluster` and `services` (see [The roots](/infrastructure-contract-modules/#the-roots)). For a Kubernetes (A system that runs programs on a group of machines (a cluster). Platforma can run in a Kubernetes cluster.) cluster that the company already has, see [Install in custom infrastructure](/install-custom-infrastructure/). The installer is the other installation path (A set of tools and steps that installs Platforma. There are five installation paths: the AWS installer, the Google Cloud installer, the Terraform modules, the Helm chart and Single Server mode.) in these clouds: for which of the two fits, see [Installation paths](/plan-choose-installation-path/#installation-paths).

## What you get

#### Variant: AWS

The Terraform modules (The Terraform code that MiLaboratories provides to install Platforma. The cloud-specific Terraform modules make the cluster and its cloud parts in AWS or Google Cloud; the cloud-agnostic Terraform modules install Platforma into the cluster.) for AWS make all the infrastructure in an AWS account. You give only a region, a name, a host, the DNS zone of the host and the networks that can reach the Kubernetes API. With these settings, the modules make:

- a VPC in two availability zones, with one NAT gateway;
- an EKS cluster with two system nodes and one node of 8 CPUs (The compute units of a node or of the server, as Kubernetes and the operating system count them. A job asks for a number of CPUs. The cloud quotas call them vCPUs.) and 32 GiB for the Backend (The server program of Platforma. It keeps the projects, runs the Blocks and starts jobs.), which run all the time. The job (One run of a tool on data. The Backend starts jobs on the server where it runs, or in a Kubernetes cluster.) node groups `ui` and `batch` scale from zero: a job node starts only when a job needs it. The largest batch nodes have 32 CPUs and 256 GiB;
- an S3 bucket as the primary storage (The bucket (Amazon S3 or Google Cloud Storage) or folder where Platforma keeps all results and uploaded files.), which the Backend reads and writes with its [cloud identity](/infrastructure-contract-identity/), with no access keys;
- an Amazon EFS file system as the workspace (The storage where the Backend and all jobs keep the working files of running jobs. The Backend and the jobs use it at the same time. In Kubernetes, it is a network file system; in Single Server mode, it is a folder on the server.), and EBS volumes for the database and the logs of the Backend;
- the entry point (The way in to the Backend from outside the cluster, a load balancer or an Ingress with a DNS name. It usually ends TLS and sends the traffic to the Backend pod.): an Application Load Balancer with an ACM certificate for the host, and the DNS record of the host in the Route 53 zone. TLS ends at the load balancer, and ACM renews the certificate.

Users sign in (To show the Backend who you are, with a sign-in provider or a single-user token. The verb is "sign in"; the noun and the adjective are "sign-in".) with a [static list of users](/configuration-authentication/#static-list-of-users), and the Desktop App (The program that each user installs on their own computer to work with Platforma. It is a client of the Backend.) connects to the host on port 443. A Backend node of this size is enough for up to about 30 users who work at the same time. For the time and the cost of the analyses, see [Size and cost of an analysis](/plan-analysis-size-and-cost/).

#### Variant: Google Cloud

The Terraform modules for Google Cloud make all the infrastructure in a Google Cloud project. You give only the project, the region and zone, a name, a host, the DNS zone of the host and the networks that can reach the Kubernetes API. With these settings, the modules make:

- a VPC with Cloud NAT: the nodes have private addresses only;
- a zonal GKE cluster with system nodes and one node for the Backend, which run all the time. The job node groups `ui` and `batch` scale from zero: a job node starts only when a job needs it;
- a Cloud Storage bucket as the primary storage, which the Backend reads and writes with its [cloud identity](/infrastructure-contract-identity/), with no keys;
- a Filestore instance of 1 TiB as the workspace, and disks for the database and the logs of the Backend. Filestore bills the full capacity all the time;
- the entry point: an external Application Load Balancer through the GKE Gateway, with a certificate that Google manages and renews, and the A record of the host in the zone. TLS ends at the load balancer.

Users sign in with a [static list of users](/configuration-authentication/#static-list-of-users), and the Desktop App connects to the host on port 443. For the size of the nodes, see [Size and cost](/plan-sizing-and-cost/). For the time and the cost of the analyses, see [Size and cost of an analysis](/plan-analysis-size-and-cost/).

## Before you start

Prepare these items before the first apply:

- **Rights.** The roots need the rights in the AWS account or the Google Cloud project and in the cluster that [Rights to install](/plan-permissions/#rights-to-install) lists. An administrator of the account or the project has them.

- **Quotas.** The vCPU quota of the region must have room for the nodes at their maximum size: see [Cloud quotas](/plan-permissions/#cloud-quotas).

- **A host and its DNS zone.** Choose the host name that users type in the Desktop App, for example `platforma.example.com`, and a public DNS zone that contains it: a Route 53 hosted zone on AWS, a Cloud DNS zone on Google Cloud. The parent zone must delegate to this zone before the first apply, because the cloud checks the domain through it before it gives the certificate. Check the delegation with `dig +short NS <zone name>`, for example `dig +short NS example.com`: the answer must show the name servers of the zone.

- **The license key.** See [License](/configuration-license/).

- **A clone of platforma-install** at a release tag. See [Where the modules are](/install-cloud-terraform/#where-the-modules-are).

- **Network access** from the computer that runs Terraform to `github.com` (the modules) and `ghcr.io` (the charts), or a clone and a chart mirror in the corporate network. For all hosts, see [Outbound connections](/security-outbound-connections/).

- **Tools** on the computer that runs Terraform: Terraform 1.12 or later, `kubectl` (at most one minor version from the version of the cluster), `openssl` and `htpasswd` (the package `apache2-utils` or `httpd-tools`). Terraform installs the charts itself, so the `helm` tool is not necessary. OpenTofu 1.12 or later also works: then use `tofu` in place of `terraform` in the commands.

  #### Variant: AWS

  The AWS CLI, with the credentials of the account:

  ```sh
  aws configure          # or: aws sso login --profile <profile>
  aws sts get-caller-identity
  ```

  #### Variant: Google Cloud

  `gcloud` with the plugin `gke-gcloud-auth-plugin`, and two sign-ins: one for `gcloud` and the plugin, one for Terraform.

  ```sh
  gcloud components install gke-gcloud-auth-plugin kubectl
  gke-gcloud-auth-plugin --version          # the plugin must be on PATH
  gcloud auth login
  gcloud auth application-default login
  gcloud config set project <project>
  ```

  After you change the identity (impersonation or another account), delete the file `gke_gcloud_auth_plugin_cache` in the folder of the kubeconfig. Otherwise `kubectl` keeps the token of the old identity for up to about 1 hour.

When the cluster cannot reach the public registries, make a mirror of each of them before the first apply, and keep the mirrors for as long as Platforma runs: see [Registries mirroring](/registries-mirroring/).

## Where the modules are

The Terraform modules, their example roots and the Helm charts are in the public repository [platforma-install](https://github.com/milaboratory/platforma-install). Each release of Platforma is a tag of this repository. Use the same tag for all the modules and charts of one installation.

| Folder                           | What it holds                                                                                                             |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `terraform/aws`, `terraform/gcp` | The modules `platforma-tf-cloud-base` and `platforma-tf-cloud-cluster` of the cloud, and its example roots in `examples/` |
| `terraform/cloud-agnostic`       | The modules `platforma-tf-services-cluster` and `platforma-tf-services`, and their example roots in `examples/`           |
| `helm/charts`                    | The charts `platforma-backend` and `appwrapper`                                                                           |

Each path has example roots: you apply them where they are, with a file of your values.

| Path                  | Root `cloud`                   | Root `cluster`                                       | Root `services`                              |
| --------------------- | ------------------------------ | ---------------------------------------------------- | -------------------------------------------- |
| AWS                   | `terraform/aws/examples/cloud` | `terraform/aws/examples/cluster`                     | `terraform/cloud-agnostic/examples/services` |
| Google Cloud          | `terraform/gcp/examples/cloud` | `terraform/gcp/examples/cluster`                     | `terraform/cloud-agnostic/examples/services` |
| A cluster that exists | none                           | `terraform/cloud-agnostic/examples/services-cluster` | `terraform/cloud-agnostic/examples/services` |

To use the example roots, clone the repository at a release tag:

```sh
git clone --branch <release tag> https://github.com/milaboratory/platforma-install.git
```

The example roots read the charts from the folder `helm/charts` of the same clone, so keep the whole clone. On the installation pages, `<platforma-install>` is the folder of this clone on your computer.

In a Terraform root of your own, use a module as a git source at the release tag. Such a module gets its chart from `oci://ghcr.io/milaboratory/platforma-install/<chart>`, at the version that the module pins. On a computer without internet access, set `chart_repository` to the folder `helm/charts` of the clone. For example:

```hcl
source = "git::https://github.com/milaboratory/platforma-install.git//terraform/aws/platforma-tf-cloud-base?ref=<release tag>"
```

## Secret values

The Backend needs three secret values. Make them one time, in a folder that only you can read, and keep the folder in a safe place:

1. Put the license key into a file, with no final newline. For the key, see [License](/configuration-license/).

   ```sh
   mkdir -p ~/platforma-secrets && chmod 700 ~/platforma-secrets && cd ~/platforma-secrets
   printf '%s' '<license-key>' > license.txt
   ```

2. Make the [master secret](/security-secrets/#master-secret). Keep this file: a new master secret signs out all users (see [The secrets of Platforma](/security-secrets/#the-secrets-of-platforma)).

   ```sh
   openssl rand -base64 32 | tr -d '\n' > master-secret.txt
   ```

3. Make the list of users with one user, `admin`. The examples give this login the administrator role (The role in the Backend that can read and change the data of all users and run the pl-cli administrator commands. The operator sets rules that give it to users by login, group or attribute.).

   ```sh
   htpasswd -cB users.htpasswd admin   # asks for the password of admin
   ```

## Steps

Run all commands on the computer with the tools. Each root keeps its Terraform state in a local file in its folder: keep the folder of the clone, or move the state to the storage of Terraform states of the company.

1. **Apply the root `cloud`.** It makes the network, the cluster, the storage and the entry point. Write the values into the file `terraform.tfvars` of the root: Terraform reads it by itself, and git ignores it. The `name` is the name of the cluster and the start of the names of most cloud resources. Use 1 to 18 characters (lowercase letters, digits and `-`), start with a letter, and end with a letter or a digit. The module refuses a longer name before it changes anything.

   #### Variant: AWS

   ```sh
   cd <platforma-install>/terraform/aws/examples/cloud
   ```

   *terraform.tfvars*

   ```hcl
   region = "eu-central-1"
   name   = "platforma"
   hosts  = ["platforma.example.com"]
   dns    = { zone_id = "<Route 53 zone ID>" }
   tls    = { mode = "managed" } # the default


   # The networks that can reach the Kubernetes API
   kubernetes = { api_allowed_cidrs = ["198.51.100.0/24"] } # computers that run Terraform and kubectl
   ```

   `kubernetes.api_allowed_cidrs` does not have a default: the plan stops until you set it. We recommend the networks of the computers that run Terraform and `kubectl` only. To open the Kubernetes API to the whole internet, set `["0.0.0.0/0"]`.

   The entry point of Platforma is open to all addresses by default (`gateway.allowed_cidrs`, default `["0.0.0.0/0"]`), so users connect from any network. Each request still needs a session of a user. To let only some networks reach the entry point, set them, for example `gateway = { allowed_cidrs = ["203.0.113.0/24"] }`. The list becomes the rules of the security group of the load balancer.

   The apply takes about 15 minutes. When the AWS credentials are a named profile, also set `aws_profile = "<profile>"` in this file, and add `-var aws_profile=<profile>` to the apply of the roots `cluster` and `services`.

   #### Variant: Google Cloud

   ```sh
   cd <platforma-install>/terraform/gcp/examples/cloud
   ```

   *terraform.tfvars*

   ```hcl
   project_id = "my-project"
   region     = "europe-west1"
   zone       = "europe-west1-b"
   name       = "platforma"
   hosts      = ["platforma.example.com"]
   tls        = { mode = "managed" } # the default
   dns        = { managed_zone = "<Cloud DNS zone name>" }


   # The networks that can reach the Kubernetes API
   kubernetes = { api_allowed_cidrs = ["198.51.100.0/24"] } # computers that run Terraform and kubectl
   ```

   `kubernetes.api_allowed_cidrs` does not have a default: the plan stops until you set it. We recommend the networks of the computers that run Terraform and `kubectl` only. To open the Kubernetes API to the whole internet, set `["0.0.0.0/0"]`.

   The entry point of Platforma is open to all addresses by default (`gateway.allowed_cidrs`, default `["0.0.0.0/0"]`), so users connect from any network. Each request still needs a session of a user. To let only some networks reach the entry point, set them, for example `gateway = { allowed_cidrs = ["203.0.113.0/24"] }`. The module then makes a Cloud Armor security policy, which costs about 7 USD each month and a fee for each request (see [What you pay all the time](/plan-sizing-and-cost/#what-you-pay-all-the-time)). Google Cloud starts to apply a new list about 10 minutes after the apply: wait before you test it.

   The apply takes about 20 minutes. It does not wait for the certificate: Google gives it some minutes later (step 5).

   ```sh
   terraform init
   terraform apply
   terraform output -json platforma_infrastructure > ../handoff/platforma-infrastructure.json
   terraform output -json cluster_connection > ../handoff/cluster-connection.json
   export KUBECONFIG="$HOME/.kube/platforma"   # optional: keeps your other kubeconfig unchanged
   eval "$(terraform output -raw kubeconfig_command)"
   ```

   Result: `kubectl get nodes` shows the system nodes `Ready`.

   To change the sizes of the nodes or to add GPU nodes, see [Jobs and resources](/configuration-jobs-and-resources/). To limit the networks that reach the cluster and the entry point, to use a private entry point or a certificate of the company, see [Domain and TLS](/configuration-domain-and-tls/). For the buckets of the data libraries (A folder or bucket with input data of the company. Users select files from it in the Desktop App. Platforma only reads it.), see [Data libraries](/configuration-data-libraries/).

2. **Apply the root `cluster`.** It installs the storage drivers, the Gateway and the cloud controllers, then Kueue (A Kubernetes add-on that holds jobs in a queue until the cluster has free CPU, memory and GPU for them.), AppWrapper (A Kubernetes add-on that wraps the pods of one job into a single unit, so that Kueue admits and starts them together.) and the job queues, and creates the namespace `platforma`. It reads the hand-off files of the root `cloud`, so it does not need values of its own. The apply takes about 2 minutes.

   ```sh
   cd ../cluster
   terraform init
   terraform apply
   terraform output -json infrastructure > ../handoff/infrastructure.json
   ```

   Result: `kubectl get namespace platforma` shows `Active`.

3. **Create the Secrets**, from the three files of the [secret values](/install-cloud-terraform/#secret-values). These are the default names and keys of the modules, so the values of the root `services` do not name them.

   ```sh
   cd ~/platforma-secrets
   kubectl -n platforma create secret generic platforma-license --from-file=MI_LICENSE=license.txt
   kubectl -n platforma create secret generic platforma-master-secret --from-file=master-secret=master-secret.txt
   kubectl -n platforma create secret generic platforma-users --from-file=htpasswd=users.htpasswd
   ```

   Result: `kubectl -n platforma get secrets` lists the three Secrets.

   For the Secrets of other sign-in providers (A configured way for users to sign in to the Backend: single sign-on (SSO), LDAP or a static list of users. One Backend can have more than one.), see [Authentication](/configuration-authentication/).

4. **Apply the root `services`.** It installs the Backend.

   ```sh
   cd <platforma-install>/terraform/cloud-agnostic/examples/services
   ```

   *terraform.tfvars*

   ```hcl
   backend_service = {
     auth = {
       providers = [
         {
           name        = "local"
           title       = "Local password"
           htpasswd    = { secret = { name = "platforma-users", key = "htpasswd" } }
           admin_users = ["admin"]
         },
       ]
     }
   }
   ```

   To pull the Backend image through the [Backend cache](/install-cloud-terraform/#caches-of-the-cloud-specific-modules) of the root `cloud`, also add to `backend_service` the value `registries.backend_image_repository` of `handoff/platforma-infrastructure.json` of the root `cloud`:

   *terraform.tfvars, in backend_service*

   ```hcl
   backend = { image = { repository = "<registries.backend_image_repository>" } }
   ```

   #### Variant: AWS

   ```sh
   terraform init
   terraform apply \
     -var infrastructure_file=../../../aws/examples/handoff/infrastructure.json \
     -var cluster_connection_file=../../../aws/examples/handoff/cluster-connection.json
   ```

   The apply waits until the Backend is ready: about 2 minutes.

   #### Variant: Google Cloud

   ```sh
   terraform init
   terraform apply \
     -var infrastructure_file=../../../gcp/examples/handoff/infrastructure.json \
     -var cluster_connection_file=../../../gcp/examples/handoff/cluster-connection.json
   ```

   The apply waits until the Backend is ready: about 3 minutes, while the cluster starts the node of the Backend.

   Result: `kubectl -n platforma get pods` shows the Backend pod `Running`, and `terraform output entry_points` shows the host.

   To change the sign-in, see [Authentication](/configuration-authentication/) and [Users and roles](/configuration-users-and-roles/). For the other settings of the Backend, see [Storage](/configuration-storage/), [Data libraries](/configuration-data-libraries/), [Jobs and resources](/configuration-jobs-and-resources/), [Proxy and custom CA](/configuration-proxy-and-custom-ca/) and [Registries](/configuration-registries/).

5. **Check DNS and the certificate.**

   #### Variant: AWS

   The root `cluster` writes the DNS record of the host. For about 2 minutes after the apply of the root `services`, the Gateway can show `Accepted=False`: the load balancer controller then tries again by itself. Do not change anything in this time.

   ```sh
   kubectl -n platforma-gateway get gateway platforma-gateway   # PROGRAMMED: True
   ```

   #### Variant: Google Cloud

   Google gives the certificate some minutes after the apply of the root `cloud`: in tests, 15 to 45 minutes. Until then, the entry point fails with a TLS error. In the folder of the root `cloud`:

   ```sh
   eval "$(terraform output -raw certificate_state_command)"   # ACTIVE: ready; PROVISIONING: wait
   ```

   While you wait, do not apply the root `cloud` again and do not change the DNS records of the module: Google then starts again.

   ```sh
   dig +short platforma.example.com
   openssl s_client -connect platforma.example.com:443 -servername platforma.example.com \
     -verify_hostname platforma.example.com -verify_return_error -alpn h2 </dev/null >/dev/null 2>&1 \
     && echo "certificate OK"
   ```

   Result: the host resolves to the address of the load balancer, and the second command shows `certificate OK`. When it shows nothing, the certificate is not valid for the host name: run `openssl` again without `>/dev/null 2>&1` to see the error.

6. **Verify the installation.** See [Verify the installation](/install-verify/).

7. **Connect the Desktop App** to `https://platforma.example.com`, and sign in as `admin` with the password of the list of users. See [Connect clients](/install-connect-clients/).

After a change of the values of one root, apply it, write its hand-off files again, and then run `terraform plan` in each later root, in the order of the roots. Apply each root whose plan shows changes. On Google Cloud, a change of `gateway.scheme` needs more applies: see [Change the entry point type on Google Cloud](/configuration-domain-and-tls/#change-the-entry-point-type-on-google-cloud). To put the modules into the infrastructure code of the company, use the example roots as a reference, with the inputs in [Terraform modules](/reference-terraform-modules/).

## Caches of the cloud-specific modules

By default, the root `cloud` makes two pull-through caches in the registry service of the cloud (Amazon ECR or Artifact Registry). A cache gets an image at the first pull and keeps it: the nodes do not pull each image from the internet, and the large software images of the jobs come faster.

| Cache             | Images                                                          | Default upstream in AWS | Default upstream in Google Cloud     |
| ----------------- | --------------------------------------------------------------- | ----------------------- | ------------------------------------ |
| `<name>-software` | the software images of the jobs, `milaboratories/pl-containers` | `https://quay.io`       | `https://containers.pl-open.science` |
| `<name>-backend`  | the Backend image, `milaboratories/platforma`                   | `https://quay.io`       | `https://quay.io`                    |

The input `registry_mirrors` of the root `cloud` sets the caches:

*terraform.tfvars*

```hcl
registry_mirrors = {
  software = { enabled = true }   # upstream = "..." to change the upstream
  backend  = { enabled = true }
}
```

`enabled = false` turns a cache off: the nodes then pull these images from the upstream. In AWS, ECR accepts only `https://quay.io`, `https://public.ecr.aws` and `https://registry.k8s.io` as an upstream, and the module always gives the nodes the right to read the caches. In Google Cloud, any upstream is possible, and the input also takes `grant_node_access` (default `true`): it gives the nodes the right to read the caches, and with `false`, the module does not use the caches.

The jobs use the software cache by themselves: when `registries.default_docker_registry` is empty, the module sets it to the path of this cache. A value that you set wins.

The Backend does not use its cache by itself. In the root `services`, set `backend_service.backend.image.repository` to the value `registries.backend_image_repository` of the hand-off file `platforma-infrastructure.json`. This value is empty when the Backend cache is off or the nodes cannot read it.

For mirrors that the company makes itself, see [Registries mirroring](/registries-mirroring/#what-the-cloud-specific-modules-do).

## Next

- [Verify the installation](/install-verify/)
- [Authentication](/configuration-authentication/)
- [Backup and restore](/maintain-backup-and-restore/)

Source: https://docs.platforma.bio/install-cloud-terraform/
