diff --git a/k8s/.header.md b/k8s/.header.md new file mode 100644 index 0000000..482f6b7 --- /dev/null +++ b/k8s/.header.md @@ -0,0 +1,286 @@ +## Fleet deployment with Terraform + +This deployment guide has been tested with +- k3s + - istio ingress + - nginx ingress + +### Usage + +#### 1. Create namespace + +This terraform will not auto-provision a namespace. You can add one with `kubectl create namespace ` or by creating a YAML file containing a service and applying it to your cluster. + +#### 2. Create Secrets + +If you have a requirement to pull container images from a Private registry via `image_pull_secrets`, you can configure them using the instructions below. Additionally, you can instruct the terraform desployment to add the image_pull_secret via `module.fleet.image_pull_secrets`. + +``` +kubectl create secret docker-registry \ + --docker-server= \ + --docker-username= \ + --docker-password= \ + --docker-email= \ + --dry-run=client -o yaml +``` + +The output that is generated by the above command will generate a file that looks like the below format, you can copy and paste to save to a file or redirect the output directly into a file. + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: + namespace: +type: kubernetes.io/dockerconfigjson +data: + .dockerconfigjson: +``` + +In order for the deployment to go through successfully, you'll need to create some secrets so Fleet knows how to authenticate against things like MySQL and Redis. While we'll only cover creating simple secrets, the deployment via terraform also supports instructing Fleet to pull the `valuesFrom:` an external secret store such as AWS Secrets Manager. + +```yaml +--- +apiVersion: v1 +kind: Secret +metadata: + name: redis-password + namespace: +type: kubernetes.io/basic-auth +stringData: + password: +--- +apiVersion: v1 +kind: Secret +metadata: + name: mysql-password + namespace: +type: kubernetes.io/basic-auth +stringData: + password: +``` + +If you use Fleet's TLS capabilities, TLS connections to the MySQL server, or AWS access secret keys, additional secrets and keys are needed. The name of each `Secret` must match the value of `secret_name` for each section in `module.fleet` located in `main.tf`. The key of each secret must match the related key value from the values file. For example, to configure Fleet's TLS, you would use a secret like the one below. + +```yaml +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet + namespace: +type: kubernetes.io/tls +data: + tls.crt: | + + tls.key: | + +``` + +If you have a Fleet premium license you would create a secret like the one below. + +```yaml +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet-license + namespace: +data: + license: +``` + +Once all of your secrets are configured, use `kubectl apply -f --namespace ` to configure them in the cluster. + +#### 3. Further Configuration + +To configure how Fleet runs, such as specifying the number of Fleet instances to deploy or changing the logger plugin for Fleet, edit the `module.fleet` located in `main.tf` file to your desired settings. + +##### nginx ingress + +Assuming no other ingress controllers are deployed to your environment, you can deploy nginx ingress components by executing `kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.7.1/deploy/static/provider/baremetal/deploy.yaml` + +You will need an nginx ingress `Service`, similar to the one below. To deploy run `kubectl apply -f `. + +```yaml +apiVersion: v1 +kind: Service +metadata: + name: ingress-nginx-controller-loadbalancer + namespace: ingress-nginx +spec: + selector: + app.kubernetes.io/component: controller + app.kubernetes.io/instance: ingress-nginx + app.kubernetes.io/name: ingress-nginx + ports: + - name: http + port: 80 + protocol: TCP + targetPort: 80 + - name: https + port: 443 + protocol: TCP + targetPort: 443 + type: LoadBalancer +``` + +The below will be in preparation for deployment through the `terraform apply` in step 5. + +In `main.tf` make sure the following variable `fleet.tls.enabled = false`, otherwise the Fleet terraform deployment will fail. +In `main.tf` make sure the following map is configured with the correct values. + - `ingress.enabled` must be `true`, if you'd like Fleet to deploy the nginx ingress for you. + - `ingress.class_name` needs to be set to `nginx` + - `ingress.hosts.name` must have a matching entry in `ingress.tls.hosts` + - example: `ingress.hosts.name = fleet.example.com` and `ingress.tls.hosts = fleet.example.com` + - Last, `ingress.tls.secret_name` must be a valid secret name in your current namespace.* + - Note: The TLS must contain a valid certificate that matches the hostnames provided for `ingress.hosts.name` and `ingress.tls.hosts`. + +``` +... + ingress = { + enabled = true + class_name = "nginx" + annotations = {} + labels = {} + hosts = [{ + name = "fleet.example.com" + paths = [{ + path = "/" + path_type = "ImplementationSpecific" + }] + }] + tls = { + secret_name = "fleet-tls" + hosts = [ + "fleet.example.com" + ] + } + } +... +``` + +##### istio ingress + +There are different ways to deploy istio to your cluster. We will cover the helm deployment in the [official istio documentation](https://istio.io/latest/docs/setup/install/helm/). + +Assuming no other ingress controllers are deployed to your environment, you can deploy istio components by executing the following commands. + +```sh +helm repo add istio https://istio-release.storage.googleapis.com/charts +helm repo update +kubectl create namespace istio-system +helm install istio-base istio/base -n istio-system +helm install istiod istio/istiod -n istio-system +kubectl create namespace istio-ingress +helm install istio-ingress istio/gateway -n istio-ingress --wait +``` + +In `main.tf` make sure the following variable `fleet.tls.enabled = false`, otherwise the Fleet terraform deployment will fail. + +You will need to create a TLS secret specifically for use by the istio ingress gateway like the example below or re-use Fleet secret created in step 2. You can apply the secret with the following command `kubectl apply -f `. + + +```yaml +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet + namespace: +type: kubernetes.io/tls +data: + tls.crt: | + + tls.key: | + +``` + +After the secret has been created, you can create your istio ingress `Gateway` and istio `Virtual Service`. In the examble below you should make reference, in the `Gateway` and `VirtualService` to hostname (example: `fleet.example.com`) covered by your TLS certificate stored in the TLS secret created above (example: `fleet`). + +```yaml +--- +apiVersion: networking.istio.io/v1 +kind: Gateway +metadata: + name: istio-gateway-fleet + namespace: +spec: + selector: + istio: ingress # use istio default ingress gateway + servers: + - port: + number: 443 + name: https + protocol: HTTPS + tls: + mode: SIMPLE + credentialName: fleet # must be the same as secret + hosts: + - 'fleet.example.com' +--- +apiVersion: networking.istio.io/v1 +kind: VirtualService +metadata: + name: fleet-vs + namespace: +spec: + hosts: + - "fleet.example.com" + gateways: + - istio-gateway-fleet + http: + - match: + - uri: + prefix: "/" + route: + - destination: + port: + number: 8080 + host: fleet +``` + +#### 4. Setup provider.tf + +Setup your `provider.tf` with the correct credentials, whether it's for a self-hosted or managed service k8s deployment. The following [link to the kubernetes provider terraform docs](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/guides/getting-started.html) has examples documented for AWS EKS, GCP GKE, and Azure. + +``` +provider "kubernetes" { + # config_path = "/path/to/kubeconfig" + config_path = "" +} +``` + +#### 5. Deploy Fleet + +From the location where your `main.tf` resides, execute the following commands. + +```sh +terraform init +terraform plan +terraform apply +``` + +### Upgrade Fleet + +Fleet should not be running when an upgrade is initiated because database migrations need to take place first. After `main.tf` has been updated to increment the version of the Fleet `image_tag`, the following commands can be executed to upgrade Fleet while bringing Fleet down so migrations can run. + +```sh +terraform init +terraform apply -replace=module.fleet.kubernetes_deployment.fleet +``` + +### Remove Fleet + +#### 1. Tear down Fleet + +From the location where your `main.tf` resides, execute the following commands. + +```sh +terraform init +terraform destroy +``` + +#### 2. Remove all secrets + +Using the file configured for your secrets, use `kubectl delete -f --namespace ` to remove the secrets. diff --git a/k8s/.terraform-docs.yml b/k8s/.terraform-docs.yml new file mode 100644 index 0000000..e532fe1 --- /dev/null +++ b/k8s/.terraform-docs.yml @@ -0,0 +1 @@ +header-from: .header.md \ No newline at end of file diff --git a/k8s/README.md b/k8s/README.md new file mode 100644 index 0000000..fc03f9b --- /dev/null +++ b/k8s/README.md @@ -0,0 +1,345 @@ +## Fleet deployment with Terraform + +This deployment guide has been tested with +- k3s + - istio ingress + - nginx ingress + +### Usage + +#### 1. Create namespace + +This terraform will not auto-provision a namespace. You can add one with `kubectl create namespace ` or by creating a YAML file containing a service and applying it to your cluster. + +#### 2. Create Secrets + +If you have a requirement to pull container images from a Private registry via `image_pull_secrets`, you can configure them using the instructions below. Additionally, you can instruct the terraform desployment to add the image\_pull\_secret via `module.fleet.image_pull_secrets`. + +``` +kubectl create secret docker-registry \ + --docker-server= \ + --docker-username= \ + --docker-password= \ + --docker-email= \ + --dry-run=client -o yaml +``` + +The output that is generated by the above command will generate a file that looks like the below format, you can copy and paste to save to a file or redirect the output directly into a file. + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: + namespace: +type: kubernetes.io/dockerconfigjson +data: + .dockerconfigjson: +``` + +In order for the deployment to go through successfully, you'll need to create some secrets so Fleet knows how to authenticate against things like MySQL and Redis. While we'll only cover creating simple secrets, the deployment via terraform also supports instructing Fleet to pull the `valuesFrom:` an external secret store such as AWS Secrets Manager. + +```yaml +--- +apiVersion: v1 +kind: Secret +metadata: + name: redis-password + namespace: +type: kubernetes.io/basic-auth +stringData: + password: +--- +apiVersion: v1 +kind: Secret +metadata: + name: mysql-password + namespace: +type: kubernetes.io/basic-auth +stringData: + password: +``` + +If you use Fleet's TLS capabilities, TLS connections to the MySQL server, or AWS access secret keys, additional secrets and keys are needed. The name of each `Secret` must match the value of `secret_name` for each section in `module.fleet` located in `main.tf`. The key of each secret must match the related key value from the values file. For example, to configure Fleet's TLS, you would use a secret like the one below. + +```yaml +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet + namespace: +type: kubernetes.io/tls +data: + tls.crt: | + + tls.key: | + +``` + +If you have a Fleet premium license you would create a secret like the one below. + +```yaml +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet-license + namespace: +data: + license: +``` + +Once all of your secrets are configured, use `kubectl apply -f --namespace ` to configure them in the cluster. + +#### 3. Further Configuration + +To configure how Fleet runs, such as specifying the number of Fleet instances to deploy or changing the logger plugin for Fleet, edit the `module.fleet` located in `main.tf` file to your desired settings. + +##### nginx ingress + +Assuming no other ingress controllers are deployed to your environment, you can deploy nginx ingress components by executing `kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.7.1/deploy/static/provider/baremetal/deploy.yaml` + +You will need an nginx ingress `Service`, similar to the one below. To deploy run `kubectl apply -f `. + +```yaml +apiVersion: v1 +kind: Service +metadata: + name: ingress-nginx-controller-loadbalancer + namespace: ingress-nginx +spec: + selector: + app.kubernetes.io/component: controller + app.kubernetes.io/instance: ingress-nginx + app.kubernetes.io/name: ingress-nginx + ports: + - name: http + port: 80 + protocol: TCP + targetPort: 80 + - name: https + port: 443 + protocol: TCP + targetPort: 443 + type: LoadBalancer +``` + +The below will be in preparation for deployment through the `terraform apply` in step 5. + +In `main.tf` make sure the following variable `fleet.tls.enabled = false`, otherwise the Fleet terraform deployment will fail. +In `main.tf` make sure the following map is configured with the correct values. + - `ingress.enabled` must be `true`, if you'd like Fleet to deploy the nginx ingress for you. + - `ingress.class_name` needs to be set to `nginx` + - `ingress.hosts.name` must have a matching entry in `ingress.tls.hosts` + - example: `ingress.hosts.name = fleet.example.com` and `ingress.tls.hosts = fleet.example.com` + - Last, `ingress.tls.secret_name` must be a valid secret name in your current namespace.* + - Note: The TLS must contain a valid certificate that matches the hostnames provided for `ingress.hosts.name` and `ingress.tls.hosts`. +``` +... + ingress = { + enabled = true + class_name = "nginx" + annotations = {} + labels = {} + hosts = [{ + name = "fleet.example.com" + paths = [{ + path = "/" + path_type = "ImplementationSpecific" + }] + }] + tls = { + secret_name = "fleet-tls" + hosts = [ + "fleet.example.com" + ] + } + } +... +``` + +##### istio ingress + +There are different ways to deploy istio to your cluster. We will cover the helm deployment in the [official istio documentation](https://istio.io/latest/docs/setup/install/helm/). + +Assuming no other ingress controllers are deployed to your environment, you can deploy istio components by executing the following commands. + +```sh +helm repo add istio https://istio-release.storage.googleapis.com/charts +helm repo update +kubectl create namespace istio-system +helm install istio-base istio/base -n istio-system +helm install istiod istio/istiod -n istio-system +kubectl create namespace istio-ingress +helm install istio-ingress istio/gateway -n istio-ingress --wait +``` + +In `main.tf` make sure the following variable `fleet.tls.enabled = false`, otherwise the Fleet terraform deployment will fail. + +You will need to create a TLS secret specifically for use by the istio ingress gateway like the example below or re-use Fleet secret created in step 2. You can apply the secret with the following command `kubectl apply -f `. + +```yaml +--- +apiVersion: v1 +kind: Secret +metadata: + name: fleet + namespace: +type: kubernetes.io/tls +data: + tls.crt: | + + tls.key: | + +``` + +After the secret has been created, you can create your istio ingress `Gateway` and istio `Virtual Service`. In the examble below you should make reference, in the `Gateway` and `VirtualService` to hostname (example: `fleet.example.com`) covered by your TLS certificate stored in the TLS secret created above (example: `fleet`). + +```yaml +--- +apiVersion: networking.istio.io/v1 +kind: Gateway +metadata: + name: istio-gateway-fleet + namespace: +spec: + selector: + istio: ingress # use istio default ingress gateway + servers: + - port: + number: 443 + name: https + protocol: HTTPS + tls: + mode: SIMPLE + credentialName: fleet # must be the same as secret + hosts: + - 'fleet.example.com' +--- +apiVersion: networking.istio.io/v1 +kind: VirtualService +metadata: + name: fleet-vs + namespace: +spec: + hosts: + - "fleet.example.com" + gateways: + - istio-gateway-fleet + http: + - match: + - uri: + prefix: "/" + route: + - destination: + port: + number: 8080 + host: fleet +``` + +#### 4. Setup provider.tf + +Setup your `provider.tf` with the correct credentials, whether it's for a self-hosted or managed service k8s deployment. The following [link to the kubernetes provider terraform docs](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/guides/getting-started.html) has examples documented for AWS EKS, GCP GKE, and Azure. + +``` +provider "kubernetes" { + # config_path = "/path/to/kubeconfig" + config_path = "" +} +``` + +#### 5. Deploy Fleet + +From the location where your `main.tf` resides, execute the following commands. + +```sh +terraform init +terraform plan +terraform apply +``` + +### Upgrade Fleet + +Fleet should not be running when an upgrade is initiated because database migrations need to take place first. After `main.tf` has been updated to increment the version of the Fleet `image_tag`, the following commands can be executed to upgrade Fleet while bringing Fleet down so migrations can run. + +```sh +terraform init +terraform apply -replace=module.fleet.kubernetes_deployment.fleet +``` + +### Remove Fleet + +#### 1. Tear down Fleet + +From the location where your `main.tf` resides, execute the following commands. + +```sh +terraform init +terraform destroy +``` + +#### 2. Remove all secrets + +Using the file configured for your secrets, use `kubectl delete -f --namespace ` to remove the secrets. + +## Requirements + +No requirements. + +## Providers + +| Name | Version | +|------|---------| +| [kubernetes](#provider\_kubernetes) | 2.36.0 | + +## Modules + +No modules. + +## Resources + +| Name | Type | +|------|------| +| [kubernetes_cron_job_v1.fleet_vuln_processing_cron_job](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/resources/cron_job_v1) | resource | +| [kubernetes_deployment.fleet](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/resources/deployment) | resource | +| [kubernetes_ingress_v1.fleet-ingress](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/resources/ingress_v1) | resource | +| [kubernetes_job.migration](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/resources/job) | resource | +| [kubernetes_role.fleet-role](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/resources/role) | resource | +| [kubernetes_role_binding.fleet-role-binding](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/resources/role_binding) | resource | +| [kubernetes_service.fleet-service](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/resources/service) | resource | +| [kubernetes_service_account.fleet-sa](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/resources/service_account) | resource | +| [kubernetes_namespace.fleet](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/data-sources/namespace) | data source | + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [affinity\_rules](#input\_affinity\_rules) | Used to configure affinity rules for the fleet deployment, migration job, and vuln-processing cron job. |
object({ 
required_during_scheduling_ignored_during_execution = optional(list(any), [])
preferred_during_scheduling_ignored_during_execution = optional(list(any), [])
})
| n/a | yes | +| [anti\_affinity\_rules](#input\_anti\_affinity\_rules) | Used to configure anti-affinity rules for the fleet deployment, migration job, and vuln-processing cron job. |
object({ 
required_during_scheduling_ignored_during_execution = optional(list(any), [])
preferred_during_scheduling_ignored_during_execution = optional(list(any),
[
{
weight = 100
label_selector = {
match_expressions = [
{
key = "app"
operator = "In"
values = ["fleet"]
}
]
}
topology_key = "kubernetes.io/hostname"
}
])
})
| n/a | yes | +| [cache](#input\_cache) | Used to configure redis specific values for use in the Fleet deployment, migration job, and vuln-processing cron job. |
object({
enabled = optional(bool, false)
address = optional(string, "redis:6379")
database = optional(number, 0)
use_password = optional(bool, false)
secret_name = optional(string, "redis-password")
password_key = optional(string, "redis")
})
| n/a | yes | +| [database](#input\_database) | Used to configure database specific values for use in the Fleet deployment, migration job, and vuln-processing cron job. |
object({
enabled = optional(bool, false)
secret_name = optional(string, "password")
address = optional(string, "mysql:3306")
database = optional(string, "fleet")
username = optional(string, "fleet")
password_key = optional(string, "mysql-password")
max_open_conns = optional(number, 50)
max_idle_conns = optional(number, 50)
conn_max_lifetime = optional(number, 0)

tls = object({
enabled = optional(bool, false)
config = optional(string, "")
server_name = optional(string, "")
ca_cert_key = optional(string, "")
cert_key = optional(string, "")
key_key = optional(string, "")
})
})
| n/a | yes | +| [environment\_from\_config\_maps](#input\_environment\_from\_config\_maps) | Used to configure additional environment variables from a config map for the fleet deployment and vuln-processing cron job. | `list(map(string))` | `[]` | no | +| [environment\_from\_secrets](#input\_environment\_from\_secrets) | Used to configure additional environment variables from a secret for the fleet deployment and vuln-processing cron job. | `list(map(string))` | `[]` | no | +| [environment\_variables](#input\_environment\_variables) | Used to configure additional environment variables for the fleet deployment and vuln-processing cron job. | `list(map(string))` | `[]` | no | +| [fleet](#input\_fleet) | Used to configure Fleet specific values for use in the Fleet deployment, migration job, and vuln-processing cron job. |
object({
listen_port = optional(number, 8080)
secret_name = optional(string, "fleet")
migrations = object({
auto_apply_sql_migrations = optional(bool, true)
migration_job_annotations = optional(map(string), {})
parallelism = optional(number, 1)
completions = optional(number, 1)
active_deadline_seconds = optional(number, 900)
backoff_limit = optional(number, 6)
ttl_seconds_after_finished = optional(number, 100)
manual_selector = optional(bool, false)
restart_policy = optional(string, "Never")
})
tls = object({
enabled = optional(bool, false)
unique_tls_secret = optional(bool, false)
secret_name = optional(string, "fleet-tls")
compatibility = optional(string, "modern")
cert_secret_key = optional(string, "server.cert")
key_secret_key = optional(string, "server.key")
})
auth = object({
b_crypto_cost = optional(number, 12)
salt_key_size = optional(number, 24)
})
app = object({
token_key_size = optional(number, 24)
invite_token_validity_period = optional(string, "120h")
})
session = object({
key_size = optional(number, 64)
duration = optional(string, "2160h")
})
logging = object({
debug = optional(bool, false)
json = optional(bool, false)
disable_banner = optional(bool, false)
})
carving = object({
s3 = object({
bucket_name = optional(string, "")
prefix = optional(string, "")
access_key_id = optional(string, "")
secret_key = optional(string, "s3-bucket")
sts_assume_role_arn = optional(string, "")
})
})
license = object({
secret_name = optional(string, "")
license_key = optional(string, "license-key")
})
extra_volumes = optional(list(any), [])
extra_volume_mounts = optional(list(any), [])
security_context = object({
run_as_user = optional(number, 3333)
run_as_group = optional(number, 3333)
})
})
| n/a | yes | +| [gke](#input\_gke) | Used to configure gke specific values for use in the Fleet deployment, migration job, and vuln-processing cron job. |
object({
workload_identity_email = optional(string, "")
cloud_sql = object({
enable_proxy = optional(bool, false)
image_repository = optional(string, "gcr.io/cloudsql-docker/gce-proxy")
image_tag = optional(string, "1.17-alpine")
verbose = optional(bool, true)
instance_name = optional(string, "")
})
ingress = object({
use_managed_certificate = optional(bool, false)
use_gke_ingress = optional(bool, false)
node_port = optional(number, 0)
hostnames = optional(list(string), [""])
})
})
| n/a | yes | +| [hostname](#input\_hostname) | Used as the hostname that you will access fleet on. | `string` | `"fleet.localhost"` | no | +| [image\_pull\_secrets](#input\_image\_pull\_secrets) | Used to inject image pull secrets for access to a private container registry. |
list(object({
name = string
}))
| `[]` | no | +| [image\_repository](#input\_image\_repository) | Used to populate the image repository for fleet. | `string` | `"fleetdm/fleet"` | no | +| [image\_tag](#input\_image\_tag) | Used to populate the fleet version that will be deployed. | `string` | `"v4.66.0"` | no | +| [ingress](#input\_ingress) | Used to configure values for ingress. |
object({
enabled = optional(bool, false)
class_name = optional(string, "nginx")
labels = optional(map(string), {})
annotations = optional(map(string), {})
hosts = optional(list(any), [])
tls = object({
secret_name = optional(string, "")
hosts = optional(list(string),[])
})
})
| n/a | yes | +| [namespace](#input\_namespace) | The value for this variable will be used as the name of the namespace that fleet will be deployed to. | `string` | `"fleet"` | no | +| [node\_selector](#input\_node\_selector) | Used to populate node selector values. | `map` | `{}` | no | +| [osquery](#input\_osquery) | Used to configure osquery specific values for use in the Fleet deployment, migration job, and vuln-processing cron job. |
object({
secret_name = optional(string, "osquery")
node_key_size = optional(number, 24)
label_update_interval = optional(string, "30m")
detail_update_interval = optional(string, "30m")
logging = object({
status_plugin = optional(string, "filesystem")
result_plugin = optional(string, "filesystem")
filesystem = object({
status_log_file = optional(string, "osquery_status")
result_log_file = optional(string, "osquery_result")
enable_rotation = optional(bool, false)
enable_compression = optional(bool, false)
volume_size = optional(string, "20Gi")
})
firehose = object({
region = optional(string, "")
access_key_id = optional(string, "")
secret_key = optional(string, "firehose")
sts_assume_role_arn = optional(string, "")
status_stream = optional(string, "")
result_stream = optional(string, "")
})
kinesis = object({
region = optional(string, "")
access_key_id = optional(string, "")
secret_key = optional(string, "kinesis")
sts_assume_role_arn = optional(string, "")
status_stream = optional(string, "")
result_stream = optional(string, "")
})
lambda = object({
region = optional(string, "")
access_key_id = optional(string, "")
secret_key = optional(string, "lambda")
sts_assume_role_arn = optional(string, "")
status_stream = optional(string, "")
result_stream = optional(string, "")
})
pubsub = object({
project = optional(string, "")
status_topic = optional(string, "")
result_topic = optional(string, "")
})
})
})
| n/a | yes | +| [pod\_annotations](#input\_pod\_annotations) | Used to populate the annotations for pods. | `map` | `{}` | no | +| [replicas](#input\_replicas) | Used to drive the number of fleet deployment replicas. | `number` | `3` | no | +| [resources](#input\_resources) | Used to populate resource values for the fleet deployment and migration job. |
object({
limits = optional(object({
cpu = optional(string, "1")
memory = optional(string, "4Gi")
}),{
cpu = "1"
memory = "4Gi"
})
requests = optional(object({
cpu = optional(string, "0.1")
memory = optional(string, "50Mi")
}),{
cpu = "0.1"
memory = "50Mi"
})
})
| n/a | yes | +| [service\_account\_annotations](#input\_service\_account\_annotations) | Used to populate the annotations for the fleet service account. | `map` | `{}` | no | +| [service\_annotations](#input\_service\_annotations) | Used to populate the annotations for the fleet service. | `map` | `{}` | no | +| [tolerations](#input\_tolerations) | Used to configure tolerations. | `list(any)` | `[]` | no | +| [vuln\_processing](#input\_vuln\_processing) | Used to configure the values for the vuln-processing cron job. |
object({
ttl_seconds_after_finished = optional(number, 100)
restart_policy = optional(string, "Never")
dedicated = optional(bool, false)
schedule = optional(string, "0 * * * *")
resources = object({
limits = optional(object({
cpu = optional(string, "1")
memory = optional(string, "4Gi")
}),{
cpu = "1"
memory = "4Gi"
})
requests = optional(object({
cpu = optional(string, "0.1")
memory = optional(string, "50Mi")
}),{
cpu = "0.1"
memory = "50Mi"
})
})
})
| n/a | yes | + +## Outputs + +No outputs. diff --git a/k8s/cronjob.tf b/k8s/cronjob.tf new file mode 100644 index 0000000..e5682c0 --- /dev/null +++ b/k8s/cronjob.tf @@ -0,0 +1,389 @@ +resource "kubernetes_cron_job_v1" "fleet_vuln_processing_cron_job" { + metadata { + name = "fleet-vulnprocessing" + namespace = data.kubernetes_namespace.fleet.metadata[0].name + } + spec { + schedule = local.vuln_processing.schedule + concurrency_policy = "Forbid" + + job_template { + metadata { + labels = { + app = "fleet" + } + } + + spec { + ttl_seconds_after_finished = local.vuln_processing.ttl_seconds_after_finished + template { + metadata { + labels = { + app = "fleet" + } + annotations = local.pod_annotations + } + spec { + share_process_namespace = "true" + restart_policy = local.vuln_processing.restart_policy + service_account_name = resource.kubernetes_service_account.fleet-sa.metadata[0].name + + container { + name = "fleet-vulnprocessing" + image = "${local.image_repository}:${local.image_tag}" + + command = ["/bin/sh", "-c"] + args = local.gke.cloud_sql.enable_proxy ? [ + "/usr/bin/fleet vuln_processing; sql_proxy_pid=$(pgrep cloud_sql_proxy) && kill -INT $sql_proxy_pid;" + ] : [ + "/usr/bin/fleet vuln_processing;" + ] + + dynamic "env" { + for_each = [ + { name = "FLEET_VULNERABILITIES_DATABASES_PATH", value = "/tmp/vuln" }, + { name = "FLEET_LOGGING_DEBUG", value = local.fleet.logging.debug }, + { name = "FLEET_LOGGING_JSON", value = local.fleet.logging.json }, + { name = "FLEET_LOGGING_DISABLE_BANNER", value = local.fleet.logging.disable_banner } + ] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.fleet.license.secret_name != "" ? [ + { + name = "FLEET_LICENSE_KEY", + value_from = { + secret_key_ref = { + name = local.fleet.license.secret_name + key = local.fleet.license.license_key + } + } + } + ] : [] + + content { + name = env.value.name + value_from { + secret_key_ref { + name = env.value.value_from.secret_key_ref.name + key = env.value.value_from.secret_key_ref.key + } + } + } + } + + dynamic "env" { + for_each = [ + { name = "FLEET_MYSQL_ADDRESS", value = local.database.address }, + { name = "FLEET_MYSQL_DATABASE", value = local.database.database }, + { name = "FLEET_MYSQL_USERNAME", value = local.database.username }, + { name = "FLEET_MYSQL_MAX_OPEN_CONNS", value = local.database.max_open_conns }, + { name = "FLEET_MYSQL_MAX_IDLE_CONNS", value = local.database.max_idle_conns }, + { name = "FLEET_MYSQL_CONN_MAX_LIFETIME", value = local.database.conn_max_lifetime } + ] + + content { + name = env.value.name + value = env.value.value + } + } + + env { + name = "FLEET_MYSQL_PASSWORD" + value_from { + secret_key_ref { + key = local.database.secret_name + name = local.database.password_key + } + } + } + + dynamic "env" { + for_each = [ + { name = "FLEET_REDIS_ADDRESS", value = local.cache.address }, + { name = "FLEET_REDIS_DATABASE", value = local.cache.database } + ] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.cache.use_password ? [ + { + name = "FLEET_REDIS_PASSWORD", + value_from = { + secret_key_ref = { + name = local.cache.secret_name + key = local.cache.password_key + } + } + } + ] : [] + + content { + name = env.value.name + value_from { + secret_key_ref { + name = env.value.value_from.secret_key_ref.name + key = env.value.value_from.secret_key_ref.key + } + } + } + } + + dynamic "env"{ + for_each = local.environment_variables + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env_from" { + for_each = local.environment_from_config_maps + + content { + config_map_ref { + name = env_from.value.name + } + } + } + + dynamic "env_from" { + for_each = local.environment_from_secrets + + content { + secret_ref { + name = env_from.value.name + } + } + } + + security_context { + run_as_user = local.fleet.security_context.run_as_user + run_as_group = local.fleet.security_context.run_as_group + run_as_non_root = "true" + read_only_root_filesystem = "true" + privileged = "false" + allow_privilege_escalation = "false" + capabilities { + drop = ["ALL"] + } + } + + resources { + limits = { + cpu = local.vuln_processing.resources.limits.cpu + memory = local.vuln_processing.resources.limits.memory + } + requests = { + cpu = local.vuln_processing.resources.requests.cpu + memory = local.vuln_processing.resources.requests.memory + } + } + + volume_mount { + name = "tmp" + mount_path = "/tmp" + } + + dynamic "volume_mount" { + for_each = local.database.tls.enabled ? [ + { name = "mysql-tls", read_only = true, mount_path = "/secrets/mysql" } + ] : [] + + content { + name = volume_mount.value.name + read_only = volume_mount.value.read_only + mount_path = volume_mount.value.mount_path + } + } + } + + dynamic "container" { + for_each = local.gke.cloud_sql.enable_proxy ? [ + { + name = "cloudql-proxy", + image = "${local.gke.cloud_sql.image_repository}:${local.gke.cloud_sql.image_tag}", + command = ["/cloud_sql_proxy", "-verbose=${local.gke.cloud_sql.verbose}", "-instances=${local.gke.cloud_sql.instance_name}=tcp:3306"] + resources = { + limits = { + cpu = "0.5", + memory = "150Mi" + }, + requests = { + cpu = "0.1", + memory = "50Mi" + } + } + security_context = { + allow_privilege_escalation = false, + capabilities = { + drop = ["ALL"] + }, + privileged = false, + read_only_root_filesystem = true, + run_as_group = local.fleet.security_context.run_as_group, + run_as_user = local.fleet.security_context.run_as_user, + run_as_non_root = true + } + } + ] : [] + + content { + name = container.value.name + image = container.value.image + command = container.value.command + resources { + limits = { + cpu = container.value.resources.limits.cpu + memory = container.value.resources.limits.memory + } + requests = { + cpu = container.value.resources.requests.cpu + memory = container.value.resources.requests.memory + } + } + security_context { + allow_privilege_escalation = container.value.security_context.allow_privilege_escalation + capabilities { + drop = container.value.security_context.capabilities.drop + } + privileged = container.value.security_context.privileged + read_only_root_filesystem = container.value.security_context.read_only_root_filesystem + run_as_group = container.value.security_context.run_as_group + run_as_user = container.value.security_context.run_as_user + run_as_non_root = container.value.security_context.run_as_non_root + } + } + } + + volume { + name = "tmp" + empty_dir {} + } + + dynamic "volume" { + for_each = local.database.tls.enabled ? [ + { + name = "mysql-tls", + secret_name = local.database.tls.secret_name + } + ] : [] + + content { + name = volume.value.name + secret { + secret_name = volume.value.secret_name + } + } + } + + dynamic "affinity" { + for_each = local.affinity_rules.required_during_scheduling_ignored_during_execution != null ? local.affinity_rules.required_during_scheduling_ignored_during_execution : null + + content { + pod_affinity { + required_during_scheduling_ignored_during_execution { + label_selector { + match_expressions { + key = affinity.value.label_selector.match_expressions[*].key + operator = affinity.value.label_selector.match_expressions[*].operator + values = affinity.value.label_selector.match_expressions[*].values + } + } + topology_key = affinity.value.topology_key + } + } + } + } + + dynamic "affinity" { + for_each = local.affinity_rules.preferred_during_scheduling_ignored_during_execution != null ? local.affinity_rules.preferred_during_scheduling_ignored_during_execution : null + + content { + pod_affinity { + preferred_during_scheduling_ignored_during_execution { + pod_affinity_term { + preference = affinity.value.preference + } + topology_key = affinity.value.topology_key + } + } + } + } + + + dynamic "affinity" { + for_each = local.anti_affinity_rules.required_during_scheduling_ignored_during_execution != null ? local.affinity_rules.required_during_scheduling_ignored_during_execution : null + + content { + pod_anti_affinity { + required_during_scheduling_ignored_during_execution { + label_selector { + match_expressions { + key = affinity.value.label_selector.match_expressions[*].key + operator = affinity.value.label_selector.match_expressions[*].operator + values = affinity.value.label_selector.match_expressions[*].values + } + } + topology_key = affinity.value.topology_key + } + } + } + } + + dynamic "affinity" { + for_each = local.anti_affinity_rules.preferred_during_scheduling_ignored_during_execution != null ? local.affinity_rules.preferred_during_scheduling_ignored_during_execution : null + + content { + pod_anti_affinity { + preferred_during_scheduling_ignored_during_execution { + pod_affinity_term { + label_selector = affinity.value.label_selector.label_selector + } + topology_key = affinity.value.topology_key + } + } + } + } + + dynamic "toleration" { + for_each = local.tolerations + + content { + key = toleration.env.key + operator = toleration.env.operator + value = toleration.env.value + effect = toleration.env.effect + } + } + + node_selector = local.node_selector + + dynamic "image_pull_secrets" { + for_each = var.image_pull_secrets + + content { + name = image_pull_secrets.value["name"] + } + } + } + } + } + } + } + depends_on = [ + resource.kubernetes_job.migration, // Include when migration is enabled + resource.kubernetes_service_account.fleet-sa + ] +} \ No newline at end of file diff --git a/k8s/deploy.tf b/k8s/deploy.tf new file mode 100644 index 0000000..55b50d6 --- /dev/null +++ b/k8s/deploy.tf @@ -0,0 +1,873 @@ +resource "kubernetes_deployment" "fleet" { + /* + if local.jobmigration = true + don't run this block + if local.jobmigration = false + run this block + */ + metadata { + name = "fleet" + namespace = data.kubernetes_namespace.fleet.metadata[0].name + labels = { + app = "fleet" + } + } + + spec { + replicas = local.replicas + + selector { + match_labels = { + app = "fleet" + } + } + + strategy { + type = "RollingUpdate" + rolling_update { + max_unavailable = "25%" + max_surge = "25%" + } + } + + template { + metadata { + labels = { + app = "fleet" + } + annotations = local.pod_annotations + } + + spec { + service_account_name = resource.kubernetes_service_account.fleet-sa.metadata[0].name + container { + name = "fleet" + image = "${local.image_repository}:${local.image_tag}" + + command = ["/usr/bin/fleet"] + args = ["serve"] + + dynamic "env" { + for_each = [ + { name = "FLEET_VULNERABILITIES_DATABASES_PATH", value = "/tmp/vuln" }, + { name = "FLEET_SERVER_ADDRESS", value = "0.0.0.0:${local.fleet.listen_port}" }, + { name = "FLEET_AUTH_BCRYPT_COST", value = local.fleet.auth.b_crypto_cost }, + { name = "FLEET_AUTH_SALT_KEY_SIZE", value = local.fleet.auth.salt_key_size }, + { name = "FLEET_APP_TOKEN_KEY_SIZE", value = local.fleet.app.token_key_size }, + { name = "FLEET_APP_TOKEN_VALIDITY_PERIOD", value = local.fleet.app.invite_token_validity_period }, + { name = "FLEET_SESSION_KEY_SIZE", value = local.fleet.session.key_size }, + { name = "FLEET_SESSION_DURATION", value = local.fleet.session.duration }, + { name = "FLEET_LOGGING_DEBUG", value = local.fleet.logging.debug }, + { name = "FLEET_LOGGING_JSON", value = local.fleet.logging.json }, + { name = "FLEET_LOGGING_DISABLE_BANNER", value = local.fleet.logging.disable_banner }, + { name = "FLEET_SERVER_TLS", value = local.fleet.tls.enabled } + ] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.fleet.tls.enabled ? [ + { name = "FLEET_SERVER_TLS_COMPATIBILITY", value = local.fleet.tls.compatibility }, + { name = "FLEET_SERVER_CERT", value = local.fleet.tls.cert_secret_key }, + { name = "FLEET_SERVER_KEY", value = local.fleet.tls.key_secret_key } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.fleet.carving.s3.bucket_name != "" ? [ + { name = "FLEET_S3_BUCKET", value = local.fleet.carving.s3.bucket_name }, + { name = "FLEET_S3_PREFIX", value = local.fleet.carving.s3.prefix } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.fleet.carving.s3.access_key_id != "" ? [ + { + name = "FLEET_S3_SECRET_ACCESS_KEY", + value_from = { + secret_key_ref = { + name = local.fleet.secret_name + key = local.fleet.carving.s3.secret_key + } + } + } + ] : [] + + content { + name = env.value.name + value_from { + secret_key_ref { + name = env.value.value_from.secret_key_ref.name + key = env.value.value_from.secret_key_ref.key + } + } + } + } + + dynamic "env" { + for_each = local.fleet.carving.s3.access_key_id == "" ? [ + { name = "FLEET_S3_STS_ASSUME_ROLE_ARN", value = local.fleet.carving.s3.secret_key } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.fleet.license.secret_name != "" ? [ + { + name = "FLEET_LICENSE_KEY", + value_from = { + secret_key_ref = { + name = local.fleet.license.secret_name + key = local.fleet.license.license_key + } + } + } + ] : [] + + content { + name = env.value.name + value_from { + secret_key_ref { + name = env.value.value_from.secret_key_ref.name + key = env.value.value_from.secret_key_ref.key + } + } + } + } + + dynamic "env" { + for_each = [ + { name = "FLEET_MYSQL_ADDRESS", value = local.database.address }, + { name = "FLEET_MYSQL_DATABASE", value = local.database.database }, + { name = "FLEET_MYSQL_USERNAME", value = local.database.username }, + { name = "FLEET_MYSQL_MAX_OPEN_CONNS", value = local.database.max_open_conns }, + { name = "FLEET_MYSQL_MAX_IDLE_CONNS", value = local.database.max_idle_conns }, + { name = "FLEET_MYSQL_CONN_MAX_LIFETIME", value = local.database.conn_max_lifetime } + ] + + content { + name = env.value.name + value = env.value.value + } + } + + env { + name = "FLEET_MYSQL_PASSWORD" + value_from { + secret_key_ref { + key = local.database.secret_name + name = local.database.password_key + } + } + } + + dynamic "env" { + for_each = local.database.tls.enabled ? [ + { name = "FLEET_MYSQL_TLS_CA", value = "/secrets/mysql/${local.database.tls.ca_cert_key}" }, + { name = "FLEET_MYSQL_TLS_CERT", value = "/secrets/mysql/${local.database.tls.cert_secret_key}" }, + { name = "FLEET_MYSQL_TLS_KEY", value = "/secrets/mysql/${local.database.tls.key_key}" }, + { name = "FLEET_MYSQL_TLS_CONFIG", value = local.database.tls.config }, + { name = "FLEET_MYSQL_TLS_SERVER_NAME", value = local.database.tls.server_name } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = [ + { name = "FLEET_REDIS_ADDRESS", value = local.cache.address }, + { name = "FLEET_REDIS_DATABASE", value = local.cache.database } + ] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.cache.use_password ? [ + { + name = "FLEET_REDIS_PASSWORD", + value_from = { + secret_key_ref = { + name = local.cache.secret_name + key = local.cache.password_key + } + } + } + ] : [] + + content { + name = env.value.name + value_from { + secret_key_ref { + name = env.value.value_from.secret_key_ref.name + key = env.value.value_from.secret_key_ref.key + } + } + } + } + + dynamic "env" { + for_each = [ + { name = "FLEET_OSQUERY_NODE_KEY_SIZE", value = local.osquery.node_key_size }, + { name = "FLEET_OSQUERY_LABEL_UPDATE_INTERVAL", value = local.osquery.label_update_interval }, + { name = "FLEET_OSQUERY_DETAIL_UPDATE_INTERVAL", value = local.osquery.detail_update_interval }, + { name = "FLEET_OSQUERY_STATUS_LOG_PLUGIN", value = local.osquery.logging.status_plugin }, + { name = "FLEET_OSQUERY_RESULT_LOG_PLUGIN", value = local.osquery.logging.result_plugin } + ] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.status_plugin == "filesystem" ? [ + { name = "FLEET_FILESYSTEM_STATUS_LOG_FILE", value = "/logs/${local.osquery.logging.filesystem.status_log_file}" } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.result_plugin == "filesystem" ? [ + { name = "FLEET_FILESYSTEM_RESULT_LOG_FILE", value = "/logs/${local.osquery.logging.filesystem.result_log_file}" } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.status_plugin == "filesystem" || local.osquery.logging.result_plugin == "filesystem" ? [ + { name = "FLEET_FILESYSTEM_ENABLE_LOG_ROTATION", value = local.osquery.logging.filesystem.enable_rotation }, + { name = "FLEET_FILESYSTEM_ENABLE_LOG_COMPRESSION", value = local.osquery.logging.filesystem.enable_compression } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.status_plugin == "firehose" || local.osquery.logging.result_plugin == "firehose" ? [ + { name = "FLEET_FIREHOSE_REGION", value = local.osquery.logging.firehose.region } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.status_plugin == "firehose" ? [ + { name = "FLEET_FIREHOSE_STATUS_STREAM", value = local.osquery.logging.firehose.status_stream } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.result_plugin == "firehose" ? [ + { name = "FLEET_FIREHOSE_RESULT_STREAM", value = local.osquery.logging.firehose.result_stream } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.firehose.access_key_id != "" ? [ + { + name = "FLEET_FIREHOSE_SECRET_ACCESS_KEY", + value_from = { + secret_key_ref = { + name = local.osquery.secret_name + key = local.osquery.logging.firehose.secret_key + } + } + } + ] : [] + + content { + name = env.value.name + value_from { + secret_key_ref { + name = env.value.value_from.secret_key_ref.name + key = env.value.value_from.secret_key_ref.key + } + } + } + } + + dynamic "env" { + for_each = local.osquery.logging.firehose.access_key_id == "" ? [ + { name = "FLEET_FIREHOSE_STS_ASSUME_ROLE_ARN", value = local.osquery.logging.firehose.sts_assume_role_arn } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.status_plugin == "kinesis" || local.osquery.logging.result_plugin == "kinesis" ? [ + { name = "FLEET_KINESIS_REGION", value = local.osquery.logging.kinesis.region } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.status_plugin == "kinesis" ? [ + { name = "FLEET_KINESIS_STATUS_STREAM", value = local.osquery.logging.kinesis.status_stream } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.result_plugin == "kinesis" ? [ + { name = "FLEET_KINESIS_RESULT_STREAM", value = local.osquery.logging.kinesis.result_stream } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.kinesis.access_key_id != "" ? [ + { name = "FLEET_KINESIS_ACCESS_KEY_ID", value = local.osquery.logging.kinesis.access_key_id } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.kinesis.access_key_id != "" ? [ + { + name = "FLEET_KINESIS_SECRET_ACCESS_KEY", + value_from = { + secret_key_ref = { + name = local.osquery.secret_name + key = local.osquery.logging.kinesis.secret_key + } + } + } + ] : [] + + content { + name = env.value.name + value_from { + secret_key_ref { + name = env.value.value_from.secret_key_ref.name + key = env.value.value_from.secret_key_ref.key + } + } + } + } + + dynamic "env" { + for_each = local.osquery.logging.kinesis.access_key_id == "" ? [ + { name = "FLEET_KINESIS_STS_ASSUME_ROLE_ARN", value = local.osquery.logging.kinesis.sts_assume_role_arn } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.status_plugin == "lambda" || local.osquery.logging.result_plugin == "lambda" ? [ + { name = "FLEET_LAMBDA_REGION", value = local.osquery.logging.lambda.region } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.status_plugin == "lambda" ? [ + { name = "FLEET_LAMBDA_STATUS_FUNCTION", value = local.osquery.logging.lambda.status_stream } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.result_plugin == "lambda" ? [ + { name = "FLEET_LAMBDA_RESULT_FUNCTION", value = local.osquery.logging.lambda.result_stream } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.lambda.access_key_id != "" ? [ + { name = "FLEET_LAMBDA_ACCESS_KEY_ID", value = local.osquery.logging.lambda.access_key_id } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.lambda.access_key_id != "" ? [ + { + name = "FLEET_LAMBDA_SECRET_ACCESS_KEY", + value_from = { + secret_key_ref = { + name = local.osquery.secret_name + key = local.osquery.logging.lambda.secret_key + } + } + } + ] : [] + + content { + name = env.value.name + value_from { + secret_key_ref { + name = env.value.value_from.secret_key_ref.name + key = env.value.value_from.secret_key_ref.key + } + } + } + } + + dynamic "env" { + for_each = local.osquery.logging.lambda.access_key_id == "" ? [ + { name = "FLEET_LAMBDA_STS_ASSUME_ROLE_ARN", value = local.osquery.logging.lambda.sts_assume_role_arn } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.status_plugin == "pubsub" || local.osquery.logging.result_plugin == "pubsub" ? [ + { name = "FLEET_PUBSUB_PROJECT", value = local.osquery.logging.pubsub.project } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.status_plugin == "pubsub" ? [ + { name = "FLEET_PUBSUB_STATUS_TOPIC", value = local.osquery.logging.pubsub.status_topic } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.osquery.logging.result_plugin == "pubsub" ? [ + { name = "FLEET_PUBSUB_RESULT_TOPIC", value = local.osquery.logging.pubsub.result_topic } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.vuln_processing.dedicated ? [ + { name = "FLEET_VULNERABILITIES_DISABLE_SCHEDULE", value = local.vuln_processing.dedicated } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env"{ + for_each = local.environment_variables + + content { + name = env.value.name + value = env.value.value + } + } + + + dynamic "env_from" { + for_each = local.environment_from_config_maps + + content { + config_map_ref { + name = env_from.value.name + } + } + } + + dynamic "env_from" { + for_each = local.environment_from_secrets + + content { + secret_ref { + name = env_from.value.name + } + } + } + + security_context { + run_as_user = local.fleet.security_context.run_as_user + run_as_group = local.fleet.security_context.run_as_group + run_as_non_root = "true" + read_only_root_filesystem = "true" + privileged = "false" + allow_privilege_escalation = "false" + capabilities { + drop = ["ALL"] + } + } + + port { + name = "fleet" + container_port = local.fleet.listen_port + protocol = "TCP" + } + + liveness_probe { + http_get { + path = "healthz" + port = local.fleet.listen_port + scheme = local.fleet.tls.enabled ? "HTTPS" : "HTTP" + } + failure_threshold = "3" + period_seconds = "3" + success_threshold = "1" + timeout_seconds = "1" + } + + readiness_probe { + http_get { + path = "healthz" + port = local.fleet.listen_port + scheme = local.fleet.tls.enabled ? "HTTPS" : "HTTP" + } + failure_threshold = "3" + period_seconds = "10" + success_threshold = "1" + timeout_seconds = "1" + } + + resources { + limits = { + cpu = local.resources.limits.cpu + memory = local.resources.limits.memory + } + requests = { + cpu = local.resources.requests.cpu + memory = local.resources.requests.memory + } + } + + volume_mount { + name = "tmp" + mount_path = "/tmp" + } + + dynamic "volume_mount" { + for_each = local.fleet.tls.enabled ? [ + { name = "fleet-tls", read_only = true, mount_path = "/secrets/tls" } + ] : [] + + content { + name = volume_mount.value.name + read_only = volume_mount.value.read_only + mount_path = volume_mount.value.mount_path + } + } + + dynamic "volume_mount" { + for_each = local.database.tls.enabled ? [ + { name = "mysql-tls", read_only = true, mount_path = "/secrets/mysql" } + ] : [] + + content { + name = volume_mount.value.name + read_only = volume_mount.value.read_only + mount_path = volume_mount.value.mount_path + } + } + + dynamic "volume_mount" { + for_each = local.osquery.logging.status_plugin == "filesystem" || local.osquery.logging.result_plugin == "filesystem" ? [ + { name = "osquery-logs", mount_path = "/logs" } + ] : [] + + content { + name = volume_mount.value.name + mount_path = volume_mount.value.mount_path + } + } + } + + dynamic "container" { + for_each = local.gke.cloud_sql.enable_proxy ? [ + { + name = "cloudql-proxy", + image = "${local.gke.cloud_sql.image_repository}:${local.gke.cloud_sql.image_tag}", + command = ["/cloud_sql_proxy", "-verbose=${local.gke.cloud_sql.verbose}", "-instances=${local.gke.cloud_sql.instance_name}=tcp:3306"] + resources = { + limits = { + cpu = "0.1", + memory = "150Mi" + }, + requests = { + cpu = "0.1", + memory = "50Mi" + } + } + security_context = { + allow_privilege_escalation = false, + capabilities = { + drop = ["ALL"] + }, + privileged = false, + read_only_root_filesystem = true, + run_as_group = local.fleet.security_context.run_as_group, + run_as_user = local.fleet.security_context.run_as_user, + run_as_non_root = true + } + } + ] : [] + + content { + name = container.value.name + image = container.value.image + command = container.value.command + resources { + limits = { + cpu = container.value.resources.limits.cpu + memory = container.value.resources.limits.memory + } + requests = { + cpu = container.value.resources.requests.cpu + memory = container.value.resources.requests.memory + } + } + security_context { + allow_privilege_escalation = container.value.security_context.allow_privilege_escalation + capabilities { + drop = container.value.security_context.capabilities.drop + } + privileged = container.value.security_context.privileged + read_only_root_filesystem = container.value.security_context.read_only_root_filesystem + run_as_group = container.value.security_context.run_as_group + run_as_user = container.value.security_context.run_as_user + run_as_non_root = container.value.security_context.run_as_non_root + } + } + } + + host_pid = false + host_network = false + host_ipc = false + + volume { + name = "tmp" + empty_dir {} + } + + dynamic "volume" { + for_each = local.fleet.tls.enabled ? [ + { + name = "fleet-tls", + secret_name = local.fleet.tls.unique_tls_secret ? local.fleet.tls.secretName : local.fleet.secret_name + } + ] : [] + + content { + name = volume.value.name + secret { + secret_name = volume.value.secret_name + } + } + } + + dynamic "volume" { + for_each = local.database.tls.enabled ? [ + { + name = "mysql-tls", + secret_name = local.database.tls.secret_name + } + ] : [] + + content { + name = volume.value.name + secret { + secret_name = volume.value.secret_name + } + } + } + + dynamic "volume" { + for_each = local.osquery.logging.status_plugin == "filesystem" || local.osquery.logging.result_plugin == "filesystem" ? [ + { + name = "osquery-logs", + size_limit = local.osquery.logging.filesystem.volume_size + } + ] : [] + + content { + name = volume.value.name + empty_dir { + size_limit = volume.value.size_limit + } + } + } + + dynamic "affinity" { + for_each = local.affinity_rules.required_during_scheduling_ignored_during_execution != null ? local.affinity_rules.required_during_scheduling_ignored_during_execution : null + + content { + pod_affinity { + required_during_scheduling_ignored_during_execution { + label_selector { + match_expressions { + key = affinity.value.label_selector.match_expressions[*].key + operator = affinity.value.label_selector.match_expressions[*].operator + values = affinity.value.label_selector.match_expressions[*].values + } + } + topology_key = affinity.value.topology_key + } + } + } + } + + dynamic "affinity" { + for_each = local.affinity_rules.preferred_during_scheduling_ignored_during_execution != null ? local.affinity_rules.preferred_during_scheduling_ignored_during_execution : null + + content { + pod_affinity { + preferred_during_scheduling_ignored_during_execution { + pod_affinity_term { + preference = affinity.value.preference + } + topology_key = affinity.value.topology_key + } + } + } + } + + + dynamic "affinity" { + for_each = local.anti_affinity_rules.required_during_scheduling_ignored_during_execution != null ? local.affinity_rules.required_during_scheduling_ignored_during_execution : null + + content { + pod_anti_affinity { + required_during_scheduling_ignored_during_execution { + label_selector { + match_expressions { + key = affinity.value.label_selector.match_expressions[*].key + operator = affinity.value.label_selector.match_expressions[*].operator + values = affinity.value.label_selector.match_expressions[*].values + } + } + topology_key = affinity.value.topology_key + } + } + } + } + + dynamic "affinity" { + for_each = local.anti_affinity_rules.preferred_during_scheduling_ignored_during_execution != null ? local.affinity_rules.preferred_during_scheduling_ignored_during_execution : null + + content { + pod_anti_affinity { + preferred_during_scheduling_ignored_during_execution { + pod_affinity_term { + label_selector = affinity.value.label_selector.label_selector + } + topology_key = affinity.value.topology_key + } + } + } + } + + dynamic "image_pull_secrets" { + for_each = var.image_pull_secrets + + content { + name = image_pull_secrets.value["name"] + } + } + } + } + } + depends_on = [ + resource.kubernetes_job.migration // dependency should only be here if migration is enabled + ] +} \ No newline at end of file diff --git a/k8s/example/main.tf b/k8s/example/main.tf new file mode 100644 index 0000000..79534cc --- /dev/null +++ b/k8s/example/main.tf @@ -0,0 +1,324 @@ +module "fleet" { + source = "git::https://github.com/fleetdm/fleet-terraform//k8s?depth=1&ref=tf-mod-k8s-v1.0.0" + + namespace = "fleet" + hostname = "fleet.localhost.local" + replicas = "3" + image_repository = "fleetdm/fleet" + image_tag = "v4.66.0" + /* + Example: + image_pull_secrets = [ + { name = "docker_pull_secret" }, + { name = "docker_pull_secret_two"} + ] + */ + image_pull_secrets = [{}] + pod_annotations = {} + service_annotations = {} + service_account_annotations = {} + resources = { + limits = { + cpu = "1" + memory = "4Gi" + } + requests = { + cpu = "0.1" + memory = "50Mi" + } + } + + vuln_processing = { + ttl_seconds_after_finished = 100 + restart_policy = "Never" + dedicated = false + schedule = "0 * * * *" + resources = { + limits = { + cpu = "1" + memory = "4Gi" + } + requests = { + cpu = "0.1" + memory = "50Mi" + } + } + } + + node_selector = {} + /* + EXAMPLE: + tolerations = [ + { key = "", operator = "", value = "", effect = "" } + ] + */ + tolerations = [] + + /* + affinity_rules = { + required_during_scheduling_ignored_during_execution = [ + label_selector = { + match_expressions = [ + { + key = "disktype" + operator = "In" + values = ["ssd"] + } + ] + } + topology_key = "kubernetes.io/hostname" + } + ] + preferred_during_scheduling_ignored_during_execution = [ + { + weight = 1 + preference = { + label_selector = { + match_expressions = [ + { + key = "another-label" + operator = "In" + values = ["value1", "value2"] + } + ] + } + topology_key = "kubernetes.io/hostname" + } + } + ] + } + anti_affinity_rules = { + required_during_scheduling_ignored_during_execution = [ + label_selector = { + match_expressions = [ + { + key = "disktype" + operator = "In" + values = ["ssd"] + } + ] + } + topology_key = "kubernetes.io/hostname" + } + ] + preferred_during_scheduling_ignored_during_execution = [ + { + weight = 1 + preference = { + label_selector = { + match_expressions = [ + { + key = "another-label" + operator = "In" + values = ["value1", "value2"] + } + ] + } + topology_key = "kubernetes.io/hostname" + } + } + ] + } + */ + affinity_rules = {} + anti_affinity_rules = {} + + ingress = { + enabled = false + class_name = "nginx" + annotations = {} + labels = {} + hosts = [{ + name = "fleet.example.com" + paths = [{ + path = "/" + path_type = "ImplementationSpecific" + }] + }] + tls = { + secret_name = "fleet-tls" + hosts = [ + "fleet.example.com" + ] + } + } + + fleet = { + listen_port = "8080" + secret_name = "fleet" + migrations = { + auto_apply_sql_migrations = true + migration_job_annotations = {} + parallelism = 1 + completions = 1 + active_deadline_seconds = 900 + backoff_limit = 6 + ttl_seconds_after_finished = 100 + manual_selector = false + restart_policy = "Never" + } + tls = { + enabled = false + unique_tls_secret = false + secret_name = "fleet-tls" + compatibility = "modern" + cert_secret_key = "server.cert" + key_secret_key = "server.key" + } + auth = { + b_crypto_cost = "12" + salt_key_size = "24" + } + app = { + token_key_size = "24" + invite_token_validity_period = "120h" + } + session = { + key_size = 64 + duration = "2160h" + } + logging = { + debug = false + json = false + disable_banner = false + } + carving = { + s3 = { + bucket_name = "" + prefix = "" + access_key_id = "" + secret_key = "s3-bucket" + sts_assume_role_arn = "" + } + } + license = { + secret_name = "" + license_key = "license-key" + } + extra_volumes = [] + extra_volume_mounts = [] + security_context = { + run_as_user = 3333 + run_as_group = 3333 + } + } + + osquery = { + secret_name = "osquery" + node_key_size = 24 + label_update_interval = "30m" + detail_update_interval = "30m" + + logging = { + status_plugin = "filesystem" + result_plugin = "filesystem" + + filesystem = { + status_log_file = "osquery_status" + result_log_file = "osquery_result" + enable_rotation = false + enable_compression = false + volume_size = "20Gi" + } + + firehose = { + region = "" + access_key_id = "" + secret_key = "firehose" + sts_assume_role_arn = "" + status_stream = "" + result_stream = "" + } + + kinesis = { + region = "" + access_key_id = "" + secret_key = "kinesis" + sts_assume_role_arn = "" + status_stream = "" + result_stream = "" + } + + lambda = { + region = "" + access_key_id = "" + secret_key = "lambda" + sts_assume_role_arn = "" + status_function = "" + result_function = "" + } + + pubsub = { + project = "" + status_topic = "" + result_topic = "" + } + } + } + + database = { + enabled = false + secret_name = "password" + address = "mysql:3306" + database = "fleet" + username = "root" + password_key = "mysql-password" + max_open_conns = 50 + max_idle_conns = 50 + conn_max_lifetime = 0 + + tls = { + enabled = false + config = "" + server_name = "" + ca_cert_key = "" + cert_key = "" + key_key = "" + } + } + + cache = { + enabled = false + address = "redis:6379" + database = "0" + use_password = false + secret_name = "redis-password" + password_key = "redis" + } + + gke = { + cloud_sql = { + enable_proxy = false + image_repository = "gcr.io/cloudsql-docker/gce-proxy" + image_tag = "1.17-alpine" + verbose = true + instance_name = "" + } + ingress = { + use_managed_certificate = false + use_gke_ingress = false + node_port = 0 + hostnames = ["example.com","example2.com"] + } + workload_identity_email = "" + } + + environment_variables = [ + { name = "FLEET_SERVER_PRIVATE_KEY", value = "" } + ] + /* + EXAMPLE: + environment_from_config_maps = [ + { name = "CONFIG_MAP_NAME" } + ] + */ + environment_from_config_maps = [] + + /* + EXAMPLE: + environment_from_secrets = [ + { name = "K8S_SECRET_NAME" } + ] + */ + environment_from_secrets = [] +} diff --git a/k8s/example/provider.tf b/k8s/example/provider.tf new file mode 100644 index 0000000..99d584c --- /dev/null +++ b/k8s/example/provider.tf @@ -0,0 +1,18 @@ +terraform { + required_providers { + kubernetes = { + source = "hashicorp/kubernetes" + version = "2.30.0" + } + } +} + +/* + To support deployments to your cloud provider's platform, + the provider will need to be modified for access, accordingly. + https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/guides/getting-started.html +*/ +provider "kubernetes" { + # config_path = "/path/to/kubeconfig" + config_path = "" +} \ No newline at end of file diff --git a/k8s/ingress.tf b/k8s/ingress.tf new file mode 100644 index 0000000..2c128e6 --- /dev/null +++ b/k8s/ingress.tf @@ -0,0 +1,48 @@ +resource "kubernetes_ingress_v1" "fleet-ingress"{ + count = local.ingress.enabled ? 1 : 0 + metadata { + name = "fleet" + namespace = data.kubernetes_namespace.fleet.metadata[0].name + labels = local.ingress.labels + annotations = local.ingress.annotations + } + spec { + ingress_class_name = local.ingress.class_name + + dynamic "tls" { + for_each = local.ingress.tls.hosts + + content { + hosts = [tls.value] + secret_name = local.ingress.tls.secret_name + } + } + + dynamic "rule" { + for_each = local.ingress.hosts + + content { + host = rule.value.name + + http { + dynamic "path" { + for_each = rule.value.paths + + content { + path = path.value.path + + backend { + service { + name = resource.kubernetes_service.fleet-service.metadata[0].name + port { + number = local.fleet.listen_port + } + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/k8s/job.tf b/k8s/job.tf new file mode 100644 index 0000000..04a492d --- /dev/null +++ b/k8s/job.tf @@ -0,0 +1,335 @@ +resource "kubernetes_job" "migration" { + metadata{ + name = "fleet-migration" + namespace = data.kubernetes_namespace.fleet.metadata[0].name + labels = { + app = "fleet" + } + annotations = local.pod_annotations + } + spec { + parallelism = local.fleet.migrations.parallelism + completions = local.fleet.migrations.completions + active_deadline_seconds = local.fleet.migrations.active_deadline_seconds + backoff_limit = local.fleet.migrations.backoff_limit + ttl_seconds_after_finished = local.fleet.migrations.ttl_seconds_after_finished + + manual_selector = local.fleet.migrations.manual_selector + + template { + metadata { + name = "fleet-migration" + labels = { + app = "fleet" + } + annotations = local.pod_annotations + } + + spec { + service_account_name = resource.kubernetes_service_account.fleet-sa.metadata[0].name + share_process_namespace = "true" + restart_policy = local.fleet.migrations.restart_policy + + container { + name = "fleet-migration" + image = "${local.image_repository}:${local.image_tag}" + + command = ["/bin/sh", "-c"] + args = local.gke.cloud_sql.enable_proxy ? [ + "/usr/bin/fleet prepare db --no-prompt; sql_proxy_pid=$(pgrep cloud_sql_proxy) && kill -INT $sql_proxy_pid;" + ] : [ + "/usr/bin/fleet prepare db --no-prompt;" + ] + + dynamic "env" { + for_each = [ + { name = "FLEET_SERVER_ADDRESS", value = "0.0.0.0:${local.fleet.listen_port}" }, + { name = "FLEET_AUTH_BCRYPT_COST", value = local.fleet.auth.b_crypto_cost }, + { name = "FLEET_AUTH_SALT_KEY_SIZE", value = local.fleet.auth.salt_key_size }, + { name = "FLEET_APP_TOKEN_KEY_SIZE", value = local.fleet.app.token_key_size }, + { name = "FLEET_APP_TOKEN_VALIDITY_PERIOD", value = local.fleet.app.invite_token_validity_period }, + { name = "FLEET_SESSION_KEY_SIZE", value = local.fleet.session.key_size }, + { name = "FLEET_SESSION_DURATION", value = local.fleet.session.duration }, + { name = "FLEET_LOGGING_DEBUG", value = local.fleet.logging.debug }, + { name = "FLEET_LOGGING_JSON", value = local.fleet.logging.json }, + { name = "FLEET_LOGGING_DISABLE_BANNER", value = local.fleet.logging.disable_banner }, + { name = "FLEET_SERVER_TLS", value = local.fleet.tls.enabled } + ] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = local.fleet.tls.enabled ? [ + { name = "FLEET_SERVER_TLS_COMPATIBILITY", value = local.fleet.tls.compatibility }, + { name = "FLEET_SERVER_CERT", value = local.fleet.tls.cert_secret_key }, + { name = "FLEET_SERVER_KEY", value = local.fleet.tls.key_secret_key } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + dynamic "env" { + for_each = [ + { name = "FLEET_MYSQL_ADDRESS", value = local.database.address }, + { name = "FLEET_MYSQL_DATABASE", value = local.database.database }, + { name = "FLEET_MYSQL_USERNAME", value = local.database.username }, + { name = "FLEET_MYSQL_MAX_OPEN_CONNS", value = local.database.max_open_conns }, + { name = "FLEET_MYSQL_MAX_IDLE_CONNS", value = local.database.max_idle_conns }, + { name = "FLEET_MYSQL_CONN_MAX_LIFETIME", value = local.database.conn_max_lifetime } + ] + + content { + name = env.value.name + value = env.value.value + } + } + + env { + name = "FLEET_MYSQL_PASSWORD" + value_from { + secret_key_ref { + key = local.database.secret_name + name = local.database.password_key + } + } + } + + dynamic "env" { + for_each = local.database.tls.enabled ? [ + { name = "FLEET_MYSQL_TLS_CA", value = "/secrets/mysql/${local.database.tls.ca_cert_key}" }, + { name = "FLEET_MYSQL_TLS_CERT", value = "/secrets/mysql/${local.database.tls.cert_secret_key}" }, + { name = "FLEET_MYSQL_TLS_KEY", value = "/secrets/mysql/${local.database.tls.key_key}" }, + { name = "FLEET_MYSQL_TLS_CONFIG", value = local.database.tls.config }, + { name = "FLEET_MYSQL_TLS_SERVER_NAME", value = local.database.tls.server_name } + ] : [] + + content { + name = env.value.name + value = env.value.value + } + } + + security_context { + run_as_user = local.fleet.security_context.run_as_user + run_as_group = local.fleet.security_context.run_as_group + run_as_non_root = "true" + read_only_root_filesystem = "true" + privileged = "false" + allow_privilege_escalation = "false" + + dynamic "capabilities" { + for_each = local.gke.cloud_sql.enable_proxy ? [ + { name = "add", values = ["SYS_PTRACE"] } + ] : [ + { name = "drop", values = ["ALL"] } + ] + + content { + add = capabilities.value.name == "add" ? capabilities.value.values : [] + drop = capabilities.value.name == "drop" ? capabilities.value.values : [] + } + } + } + + resources { + limits = { + cpu = local.resources.limits.cpu + memory = local.resources.limits.memory + } + requests = { + cpu = local.resources.requests.cpu + memory = local.resources.requests.memory + } + } + + dynamic "volume_mount" { + for_each = local.database.tls.enabled ? [ + { name = "mysql-tls", read_only = true, mount_path = "/secrets/mysql" } + ] : [] + + content { + name = volume_mount.value.name + read_only = volume_mount.value.read_only + mount_path = volume_mount.value.mount_path + } + } + } + + dynamic "container" { + for_each = local.gke.cloud_sql.enable_proxy ? [ + { + name = "cloudql-proxy", + image = "${local.gke.cloud_sql.image_repository}:${local.gke.cloud_sql.image_tag}", + command = ["/cloud_sql_proxy", "-verbose=${local.gke.cloud_sql.verbose}", "-instances=${local.gke.cloud_sql.instance_name}=tcp:3306"] + resources = { + limits = { + cpu = "0.5", + memory = "150Mi" + }, + requests = { + cpu = "0.1", + memory = "50Mi" + } + } + security_context = { + allow_privilege_escalation = false, + capabilities = { + drop = ["ALL"] + }, + privileged = false, + read_only_root_filesystem = true, + run_as_group = local.fleet.security_context.run_as_group, + run_as_user = local.fleet.security_context.run_as_user, + run_as_non_root = true + } + } + ] : [] + + content { + name = container.value.name + image = container.value.image + command = container.value.command + resources { + limits = { + cpu = container.value.resources.limits.cpu + memory = container.value.resources.limits.memory + } + requests = { + cpu = container.value.resources.requests.cpu + memory = container.value.resources.requests.memory + } + } + security_context { + allow_privilege_escalation = container.value.security_context.allow_privilege_escalation + capabilities { + drop = container.value.security_context.capabilities.drop + } + privileged = container.value.security_context.privileged + read_only_root_filesystem = container.value.security_context.read_only_root_filesystem + run_as_group = container.value.security_context.run_as_group + run_as_user = container.value.security_context.run_as_user + run_as_non_root = container.value.security_context.run_as_non_root + } + } + } + + dynamic "volume" { + for_each = local.database.tls.enabled ? [ + { + name = "mysql-tls", + secret_name = local.database.tls.secret_name + } + ] : [] + + content { + name = volume.value.name + secret { + secret_name = volume.value.secret_name + } + } + } + + dynamic "affinity" { + for_each = local.affinity_rules.required_during_scheduling_ignored_during_execution != null ? local.affinity_rules.required_during_scheduling_ignored_during_execution : null + + content { + pod_affinity { + required_during_scheduling_ignored_during_execution { + label_selector { + match_expressions { + key = affinity.value.label_selector.match_expressions[*].key + operator = affinity.value.label_selector.match_expressions[*].operator + values = affinity.value.label_selector.match_expressions[*].values + } + } + topology_key = affinity.value.topology_key + } + } + } + } + + dynamic "affinity" { + for_each = local.affinity_rules.preferred_during_scheduling_ignored_during_execution != null ? local.affinity_rules.preferred_during_scheduling_ignored_during_execution : null + + content { + pod_affinity { + preferred_during_scheduling_ignored_during_execution { + pod_affinity_term { + preference = affinity.value.preference + } + topology_key = affinity.value.topology_key + } + } + } + } + + + dynamic "affinity" { + for_each = local.anti_affinity_rules.required_during_scheduling_ignored_during_execution != null ? local.affinity_rules.required_during_scheduling_ignored_during_execution : null + + content { + pod_anti_affinity { + required_during_scheduling_ignored_during_execution { + label_selector { + match_expressions { + key = affinity.value.label_selector.match_expressions[*].key + operator = affinity.value.label_selector.match_expressions[*].operator + values = affinity.value.label_selector.match_expressions[*].values + } + } + topology_key = affinity.value.topology_key + } + } + } + } + + dynamic "affinity" { + for_each = local.anti_affinity_rules.preferred_during_scheduling_ignored_during_execution != null ? local.affinity_rules.preferred_during_scheduling_ignored_during_execution : null + + content { + pod_anti_affinity { + preferred_during_scheduling_ignored_during_execution { + pod_affinity_term { + label_selector = affinity.value.label_selector.label_selector + } + topology_key = affinity.value.topology_key + } + } + } + } + + dynamic "toleration" { + for_each = local.tolerations + + content { + key = toleration.env.key + operator = toleration.env.operator + value = toleration.env.value + effect = toleration.env.effect + } + } + + node_selector = local.node_selector + + dynamic "image_pull_secrets" { + for_each = var.image_pull_secrets + + content { + name = image_pull_secrets.value["name"] + } + } + } + } + } + wait_for_completion = true + timeouts { + create = "30m" + } +} \ No newline at end of file diff --git a/k8s/locals.tf b/k8s/locals.tf new file mode 100644 index 0000000..1f01882 --- /dev/null +++ b/k8s/locals.tf @@ -0,0 +1,26 @@ +locals { + namespace = var.namespace + hostname = var.hostname + replicas = var.replicas + image_repository = var.image_repository + image_tag = var.image_tag + image_pull_secrets = var.image_pull_secrets + pod_annotations = var.pod_annotations + service_annotations = var.service_annotations + service_account_annotations = var.service_account_annotations + resources = var.resources + vuln_processing = var.vuln_processing + node_selector = var.node_selector + tolerations = var.tolerations + affinity_rules = var.affinity_rules + anti_affinity_rules = var.anti_affinity_rules + ingress = var.ingress + fleet = var.fleet + osquery = var.osquery + database = var.database + cache = var.cache + gke = var.gke + environment_variables = var.environment_variables + environment_from_config_maps = var.environment_from_config_maps + environment_from_secrets = var.environment_from_secrets +} \ No newline at end of file diff --git a/k8s/managedcert.tf b/k8s/managedcert.tf new file mode 100644 index 0000000..1acdc71 --- /dev/null +++ b/k8s/managedcert.tf @@ -0,0 +1,4 @@ +/* + TERRAFORM KUBERNETES PROVIDER DOES NOT SUPPORT + MANAGED CERTIFICATES +*/ \ No newline at end of file diff --git a/k8s/ns.tf b/k8s/ns.tf new file mode 100644 index 0000000..9ff84ce --- /dev/null +++ b/k8s/ns.tf @@ -0,0 +1,5 @@ +data "kubernetes_namespace" "fleet" { + metadata { + name = local.namespace + } +} \ No newline at end of file diff --git a/k8s/sa.tf b/k8s/sa.tf new file mode 100644 index 0000000..bc0ba75 --- /dev/null +++ b/k8s/sa.tf @@ -0,0 +1,55 @@ +resource "kubernetes_service_account" "fleet-sa" { + metadata { + name = "fleet" + namespace = data.kubernetes_namespace.fleet.metadata[0].name + + labels = { + app = "fleet" + } + annotations = local.gke.workload_identity_email != "" ? merge(local.service_account_annotations, { "iam.gke.io/gcp-service-account" = local.gke.workload_identity_email}) : local.service_account_annotations + } +} + +resource "kubernetes_role" "fleet-role" { + metadata { + name = "fleet" + namespace = data.kubernetes_namespace.fleet.metadata[0].name + } + + rule { + api_groups = ["core"] + resources = ["secrets"] + resource_names = tolist([ + local.database.secret_name != "" ? local.database.secret_name : "", + local.cache.secret_name != "" ? local.cache.secret_name : "", + local.fleet.secret_name != "" ? local.fleet.secret_name : "", + local.osquery.secret_name != "" ? local.osquery.secret_name : "" + ]) + verbs = ["get"] + } + depends_on = [ + resource.kubernetes_service_account.fleet-sa + ] +} + +resource "kubernetes_role_binding" "fleet-role-binding" { + metadata { + name = "fleet" + namespace = data.kubernetes_namespace.fleet.metadata[0].name + } + + role_ref { + api_group = "rbac.authorization.k8s.io" + kind = "Role" + name = resource.kubernetes_role.fleet-role.metadata[0].name + } + + subject { + kind = "ServiceAccount" + name = resource.kubernetes_service_account.fleet-sa.metadata[0].name + namespace = data.kubernetes_namespace.fleet.metadata[0].name + } + depends_on = [ + resource.kubernetes_role.fleet-role + ] +} \ No newline at end of file diff --git a/k8s/svc.tf b/k8s/svc.tf new file mode 100644 index 0000000..8b65b16 --- /dev/null +++ b/k8s/svc.tf @@ -0,0 +1,34 @@ +resource "kubernetes_service" "fleet-service" { + metadata { + name = "fleet" + namespace = data.kubernetes_namespace.fleet.metadata[0].name + annotations = local.service_annotations + } + + spec { + selector = { + app = "fleet" + } + + dynamic "port" { + for_each = local.gke.ingress.use_gke_ingress && local.gke.ingress.node_port != "" ? [ + { name = "fleet", port = local.fleet.listen_port, target_port = local.fleet.listen_port, protocol = "TCP", node_port = local.gke.ingress.node_port } + ] : [ + { name = "fleet", port = local.fleet.listen_port, target_port = local.fleet.listen_port, protocol = "TCP", node_port = null } + ] + + content { + name = port.value.name + port = port.value.port + protocol = port.value.protocol + target_port = port.value.target_port + node_port = port.value.node_port + } + } + + type = local.gke.ingress.use_gke_ingress ? "NodePort" : "ClusterIP" + } + depends_on = [ + resource.kubernetes_deployment.fleet + ] +} \ No newline at end of file diff --git a/k8s/variables.tf b/k8s/variables.tf new file mode 100644 index 0000000..5f7b51e --- /dev/null +++ b/k8s/variables.tf @@ -0,0 +1,357 @@ +variable "namespace" { + type = string + default = "fleet" + description = "The value for this variable will be used as the name of the namespace that fleet will be deployed to." +} + +variable "hostname" { + type = string + default = "fleet.localhost" + description = "Used as the hostname that you will access fleet on." +} + +variable "replicas" { + type = number + default = 3 + description = "Used to drive the number of fleet deployment replicas." +} + +variable "image_repository" { + type = string + default = "fleetdm/fleet" + description = "Used to populate the image repository for fleet." +} + +variable "image_tag" { + type = string + default = "v4.66.0" + description = "Used to populate the fleet version that will be deployed." +} + +variable "image_pull_secrets" { + type = list(object({ + name = string + })) + default = [] + description = "Used to inject image pull secrets for access to a private container registry." +} + +variable "pod_annotations" { + type = map + default = {} + description = "Used to populate the annotations for pods." +} + +variable "service_annotations" { + type = map + default = {} + description = "Used to populate the annotations for the fleet service." +} + +variable "service_account_annotations" { + type = map + default = {} + description = "Used to populate the annotations for the fleet service account." +} + +variable "resources" { + type = object({ + limits = optional(object({ + cpu = optional(string, "1") + memory = optional(string, "4Gi") + }),{ + cpu = "1" + memory = "4Gi" + }) + requests = optional(object({ + cpu = optional(string, "0.1") + memory = optional(string, "50Mi") + }),{ + cpu = "0.1" + memory = "50Mi" + }) + }) + description = "Used to populate resource values for the fleet deployment and migration job." +} + +variable "node_selector" { + type = map + default = {} + description = "Used to populate node selector values." +} + +variable "tolerations" { + type = list(any) + default = [] + description = "Used to configure tolerations." +} + +variable "environment_variables" { + type = list(map(string)) + default = [] + description = "Used to configure additional environment variables for the fleet deployment and vuln-processing cron job." +} + +variable "environment_from_config_maps" { + type = list(map(string)) + default = [] + description = "Used to configure additional environment variables from a config map for the fleet deployment and vuln-processing cron job." +} + +variable "environment_from_secrets" { + type = list(map(string)) + default = [] + description = "Used to configure additional environment variables from a secret for the fleet deployment and vuln-processing cron job." +} + +/* + affinity +*/ + + +variable "affinity_rules" { + type = object({ + required_during_scheduling_ignored_during_execution = optional(list(any), []) + preferred_during_scheduling_ignored_during_execution = optional(list(any), []) + }) + description = "Used to configure affinity rules for the fleet deployment, migration job, and vuln-processing cron job." +} + +variable "anti_affinity_rules" { + type = object({ + required_during_scheduling_ignored_during_execution = optional(list(any), []) + preferred_during_scheduling_ignored_during_execution = optional(list(any), + [ + { + weight = 100 + label_selector = { + match_expressions = [ + { + key = "app" + operator = "In" + values = ["fleet"] + } + ] + } + topology_key = "kubernetes.io/hostname" + } + ]) + }) + description = "Used to configure anti-affinity rules for the fleet deployment, migration job, and vuln-processing cron job." +} + +/* + vuln_processing +*/ +variable "vuln_processing" { + type = object({ + ttl_seconds_after_finished = optional(number, 100) + restart_policy = optional(string, "Never") + dedicated = optional(bool, false) + schedule = optional(string, "0 * * * *") + resources = object({ + limits = optional(object({ + cpu = optional(string, "1") + memory = optional(string, "4Gi") + }),{ + cpu = "1" + memory = "4Gi" + }) + requests = optional(object({ + cpu = optional(string, "0.1") + memory = optional(string, "50Mi") + }),{ + cpu = "0.1" + memory = "50Mi" + }) + }) + }) + description = "Used to configure the values for the vuln-processing cron job." +} + +/* + ingress +*/ +variable "ingress" { + type = object({ + enabled = optional(bool, false) + class_name = optional(string, "nginx") + labels = optional(map(string), {}) + annotations = optional(map(string), {}) + hosts = optional(list(any), []) + tls = object({ + secret_name = optional(string, "") + hosts = optional(list(string),[]) + }) + }) + description = "Used to configure values for ingress." +} + +variable "fleet" { + type = object({ + listen_port = optional(number, 8080) + secret_name = optional(string, "fleet") + migrations = object({ + auto_apply_sql_migrations = optional(bool, true) + migration_job_annotations = optional(map(string), {}) + parallelism = optional(number, 1) + completions = optional(number, 1) + active_deadline_seconds = optional(number, 900) + backoff_limit = optional(number, 6) + ttl_seconds_after_finished = optional(number, 100) + manual_selector = optional(bool, false) + restart_policy = optional(string, "Never") + }) + tls = object({ + enabled = optional(bool, false) + unique_tls_secret = optional(bool, false) + secret_name = optional(string, "fleet-tls") + compatibility = optional(string, "modern") + cert_secret_key = optional(string, "server.cert") + key_secret_key = optional(string, "server.key") + }) + auth = object({ + b_crypto_cost = optional(number, 12) + salt_key_size = optional(number, 24) + }) + app = object({ + token_key_size = optional(number, 24) + invite_token_validity_period = optional(string, "120h") + }) + session = object({ + key_size = optional(number, 64) + duration = optional(string, "2160h") + }) + logging = object({ + debug = optional(bool, false) + json = optional(bool, false) + disable_banner = optional(bool, false) + }) + carving = object({ + s3 = object({ + bucket_name = optional(string, "") + prefix = optional(string, "") + access_key_id = optional(string, "") + secret_key = optional(string, "s3-bucket") + sts_assume_role_arn = optional(string, "") + }) + }) + license = object({ + secret_name = optional(string, "") + license_key = optional(string, "license-key") + }) + extra_volumes = optional(list(any), []) + extra_volume_mounts = optional(list(any), []) + security_context = object({ + run_as_user = optional(number, 3333) + run_as_group = optional(number, 3333) + }) + }) + description = "Used to configure Fleet specific values for use in the Fleet deployment, migration job, and vuln-processing cron job." +} + +variable "osquery" { + type = object({ + secret_name = optional(string, "osquery") + node_key_size = optional(number, 24) + label_update_interval = optional(string, "30m") + detail_update_interval = optional(string, "30m") + logging = object({ + status_plugin = optional(string, "filesystem") + result_plugin = optional(string, "filesystem") + filesystem = object({ + status_log_file = optional(string, "osquery_status") + result_log_file = optional(string, "osquery_result") + enable_rotation = optional(bool, false) + enable_compression = optional(bool, false) + volume_size = optional(string, "20Gi") + }) + firehose = object({ + region = optional(string, "") + access_key_id = optional(string, "") + secret_key = optional(string, "firehose") + sts_assume_role_arn = optional(string, "") + status_stream = optional(string, "") + result_stream = optional(string, "") + }) + kinesis = object({ + region = optional(string, "") + access_key_id = optional(string, "") + secret_key = optional(string, "kinesis") + sts_assume_role_arn = optional(string, "") + status_stream = optional(string, "") + result_stream = optional(string, "") + }) + lambda = object({ + region = optional(string, "") + access_key_id = optional(string, "") + secret_key = optional(string, "lambda") + sts_assume_role_arn = optional(string, "") + status_stream = optional(string, "") + result_stream = optional(string, "") + }) + pubsub = object({ + project = optional(string, "") + status_topic = optional(string, "") + result_topic = optional(string, "") + }) + }) + }) + description = "Used to configure osquery specific values for use in the Fleet deployment, migration job, and vuln-processing cron job." +} + +variable "database" { + type = object({ + enabled = optional(bool, false) + secret_name = optional(string, "password") + address = optional(string, "mysql:3306") + database = optional(string, "fleet") + username = optional(string, "fleet") + password_key = optional(string, "mysql-password") + max_open_conns = optional(number, 50) + max_idle_conns = optional(number, 50) + conn_max_lifetime = optional(number, 0) + + tls = object({ + enabled = optional(bool, false) + config = optional(string, "") + server_name = optional(string, "") + ca_cert_key = optional(string, "") + cert_key = optional(string, "") + key_key = optional(string, "") + }) + }) + description = "Used to configure database specific values for use in the Fleet deployment, migration job, and vuln-processing cron job." +} + +variable "cache" { + type = object({ + enabled = optional(bool, false) + address = optional(string, "redis:6379") + database = optional(number, 0) + use_password = optional(bool, false) + secret_name = optional(string, "redis-password") + password_key = optional(string, "redis") + }) + description = "Used to configure redis specific values for use in the Fleet deployment, migration job, and vuln-processing cron job." +} + +variable "gke" { + type = object({ + workload_identity_email = optional(string, "") + cloud_sql = object({ + enable_proxy = optional(bool, false) + image_repository = optional(string, "gcr.io/cloudsql-docker/gce-proxy") + image_tag = optional(string, "1.17-alpine") + verbose = optional(bool, true) + instance_name = optional(string, "") + }) + ingress = object({ + use_managed_certificate = optional(bool, false) + use_gke_ingress = optional(bool, false) + node_port = optional(number, 0) + hostnames = optional(list(string), [""]) + }) + }) + description = "Used to configure gke specific values for use in the Fleet deployment, migration job, and vuln-processing cron job." +} \ No newline at end of file