├── .gitignore ├── kubevirt-provisioner ├── cloud-config.yaml.tftpl └── main.tf ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | ### Terraform ### 2 | # Local .terraform directories 3 | **/.terraform/* 4 | 5 | # .tfstate files 6 | *.tfstate 7 | *.tfstate.* 8 | 9 | # Crash log files 10 | crash.log 11 | crash.*.log 12 | 13 | # Exclude all .tfvars files, which are likely to contain sensitive data, such as 14 | # password, private keys, and other secrets. These should not be part of version 15 | # control as they are data points which are potentially sensitive and subject 16 | # to change depending on the environment. 17 | *.tfvars 18 | *.tfvars.json 19 | 20 | # Ignore override files as they are usually used to override resources locally and so 21 | # are not checked in 22 | override.tf 23 | override.tf.json 24 | *_override.tf 25 | *_override.tf.json 26 | 27 | # Include override files you do wish to add to version control using negated pattern 28 | # !example_override.tf 29 | 30 | # Include tfplan files to ignore the plan output of command: terraform plan -out=tfplan 31 | # example: *tfplan* 32 | 33 | # Ignore CLI configuration files 34 | .terraformrc 35 | terraform.rc 36 | 37 | # Ignore local terraform file -- don't add this in your gitignore 38 | .terraform.lock.hcl -------------------------------------------------------------------------------- /kubevirt-provisioner/cloud-config.yaml.tftpl: -------------------------------------------------------------------------------- 1 | #cloud-config 2 | local-hostname: ${hostname} 3 | hostname: ${hostname} 4 | fqdn: ${hostname}.coder.company 5 | users: 6 | - name: ${username} 7 | passwd: $y$j9T$7rB9aUNSRJTEzm8t7qjdd1$klhw8gB81nd.6Q/T2EXu/bgiMjxPRWSHf1u8ZXloYf3 8 | lock_passwd: false 9 | sudo: ["ALL=(ALL) NOPASSWD:ALL"] 10 | groups: sudo 11 | shell: /bin/bash 12 | packages: 13 | - git 14 | write_files: 15 | - path: /opt/coder/init 16 | permissions: "0755" 17 | encoding: b64 18 | content: ${init_script} 19 | - path: /etc/systemd/system/coder-agent.service 20 | permissions: "0644" 21 | content: | 22 | [Unit] 23 | Description=Coder Agent 24 | After=network-online.target 25 | Wants=network-online.target 26 | 27 | [Service] 28 | User=${username} 29 | ExecStart=/opt/coder/init 30 | EnvironmentFile=/var/run/secrets/.coder-agent-token 31 | Restart=always 32 | RestartSec=10 33 | TimeoutStopSec=90 34 | KillMode=process 35 | 36 | OOMScoreAdjust=-900 37 | SyslogIdentifier=coder-agent 38 | 39 | [Install] 40 | WantedBy=multi-user.target 41 | bootcmd: 42 | - mkdir -p /var/run/secrets 43 | - echo CODER_AGENT_TOKEN=${coder_agent_token} > /var/run/secrets/.coder-agent-token 44 | runcmd: 45 | - systemctl enable coder-agent 46 | - systemctl start coder-agent -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Coder Kubevirt Template 3 | [![Apache 2.0 License](https://img.shields.io/badge/License-Apache%202.0-green.svg)](https://choosealicense.com/licenses/apache-2.0/) 4 | 5 | This project is a template to create reproducible dev environments in [Coder](https://github.com/coder/coder) using [Kubevirt](https://github.com/kubevirt/kubevirt) running on a Kubernetes cluster. 6 | 7 | Coder enables organizations to set up development environments in their public or private cloud infrastructure. Cloud development environments are defined with Terraform, connected through a secure high-speed Wireguard® tunnel, and are automatically shut down when not in use to save on costs. Coder gives engineering teams the flexibility to use the cloud for workloads that are most beneficial to them. 8 | 9 | KubeVirt is a virtual machine management add-on for Kubernetes. The aim is to provide a common ground for virtualization solutions on top of Kubernetes. 10 | 11 | Read below for motive. 12 | 13 | ## Pre-requisites 14 | - A running kubernetes cluster with Kubevirt deployed. See Kubevirt [installation guide](https://kubevirt.io/user-guide/operations/installation). 15 | - Containerized Data Importer (CDI) should be installed in the kubernetes cluster for PVC management. See CDI [installation guide](https://kubevirt.io/user-guide/operations/containerized_data_importer/). 16 | - Default storage class configured in the kubernetes cluster. 17 | - Bare-metal kubernetes cluster preferred. For kubernetes clusters running on top of VMs, nested-virtualization support is required. 18 | 19 | #### Kubernetes API Access Pre-requisite 20 | If the Coder host is running outside the Kubernetes cluster (where workspace VMs will be deployed), a valid "~/.kube/config" must be present on the Coder host. 21 | 22 | If Coder host is deployed on the same Kubernetes cluster (where workspace VMs will be deployed), a service account provisioned by coder will be used for workspace deployments. 23 | 24 | In both cases, the service-account/user(in the kubeconfig) should have bindings for following roles: 25 | 26 | | type | apiGroups | resources | verbs | namespace | 27 | |------------- |---------------------- |--------------------------- |------------------ |------------------------------------------------ | 28 | | clusterrole | apiextensions.k8s.io | customresourcedefinitions | get, list, watch | - | 29 | | clusterrole | kubevirt.io | virtualmachines | * | - | 30 | | clusterrole | cdi.kubevirt.io | datavolumes | * | - | 31 | | role | "" | secrets | * | namespace where workspace VMs will be deployed | 32 | | role | "" | services | * | namespace where workspace VMs will be deployed | 33 | 34 | Permission to access secret in the namespace where VMs are deployed is required to store cloud-init configs. This secret is then mount to workspace VMs as a cloud-init drive. Kubevirt only supports 2048 byte cloud-init config if set as string. To overcome this limit, Kubernetes secrets are used. 35 | 36 | Permission to access service in the namespace where VMs are deployed is required to add DNS entry of VMs in the Kubernetes cluster. This way a VM created by this template can be accessed by another VM in the same cluster very easily. This can be done without DNS entry, and service as well, by referring to the "pod" IP address of the VM directly. This template runs VM network in `masquerade` mode. This means that the network VM will be is different than the k8s pod network. Network traffic is NAT'ed from VM network to pod network in `masquerade` mode. The VMs won't be accessible from other VMs by using the internal VM IP address. One has to use the "pod" IP address to access the VM. Since getting the pod IP address can only be done by someone who has access to the cluster, DNS entry is added to the k8s cluster instead. This way, anyone who uses coder and does not have access to the underlying k8s cluster will be able to access other VMs. 37 | 38 | VMs created by this template can be accessed in the following format: 39 | `coder--..svc.cluster.local` 40 | 41 | ## Features 42 | 43 | - Provision KVM Virtual Machines as dev workspaces 44 | - Persists whole root filesystem instead of just home directory 45 | - Persists software installs in the OS 46 | - Code server is enabled by default 47 | - SSH is configured 48 | - VMs can be started/stopped/restarted from Coder webapp without losing data 49 | - Major Linux distributions are pre-configured 50 | - Ubuntu 22.04 51 | - Debian 12 52 | - Fedora 39 53 | - Arch Linux 54 | - AlmaLinux 9 55 | - CentOS Stream 9 56 | - Rocky Linux 9 57 | - Automatically downloads OS drives from cloud to create disk PVCs 58 | 59 | ## Installation 60 | This installation assumes you have a Coder deployment running and CLI authenticated. 61 | 62 | - Clone this repository 63 | ```sh 64 | git clone https://github.com/sulo1337/coder-kubevirt-template.git && cd coder-kubevirt-template/kubevirt-provisioner 65 | ``` 66 | - Push the template 67 | ```sh 68 | coder templates push . 69 | ``` 70 | 71 | ## Defaults 72 | These are the default values configured in the template. These values can be changed based on the requirements 73 | 74 | - CPU - 2 cores 75 | - Memory - 4Gi 76 | - Disk Size - 16Gi 77 | - Network configured in masquerade mode. See [kubevirt networking documentation](https://kubevirt.io/user-guide/virtual_machines/interfaces_and_networks/) for more details 78 | 79 | ## Roadmap 80 | - Enable sourcing disk PVC creations from another PVC. Currently disk PVC data is sourced from qcow2 cloud images of various OS. This feature will allow a cluster administrator to pre-configure bootable image of an OS as PVC and use that PVC as a source to create new VM disk. 81 | - Windows OS as VMs 82 | - VNC 83 | - Multi-disk VMs 84 | - Shared disks as PVC attached to VMs allowing dev workspaces to share files. 85 | 86 | ## Notes 87 | - Management of Kubevirt is out of scope of this repository 88 | - VolumeSnapshot and PVC backups of VM disks is out of scope of this repository 89 | 90 | 91 | ## Motive 92 | I created this template because of three reasons. 93 | - To safely allow container runtimes to run inside coder workspace 94 | - To utilize existing Kubernetes cluster to provision workspaces capable of running native container workloads 95 | - To use existing bare-metal infrastructure for provisioning coder workspaces instead of using cloud providers (AWS, Azure etc) 96 | 97 | There are other benefits to using Virtual Machine vs Containers for dev environments which is out of scope for this documentation. 98 | 99 | 100 | Workspaces provisioned by Coder in Kubernetes are container environments in a pod. Most modern software development requires use of containerization technologies like Docker as a part of development workflow. According to [Coder Docs](https://coder.com/docs/v2/latest/templates/docker-in-workspaces), there are multiple ways to run container environments inside pods provisioned by Coder: 101 | - Sysbox container runtime (needs specific infrastructure configuration, and enterprise license for [more features](https://github.com/nestybox/sysbox/blob/master/docs/figures/sysbox-features.png)) 102 | - Envbox* 103 | - Rootless podman* 104 | - Privileged docker sidecar* 105 | 106 | *All of these methods either will make you create a privileged pod inside your cluster or have some privileged wrapper around your workspace (except rootless podman). Limitations of using rootless podman is out of scope for this documentation. 107 | 108 | I created this template to extend Coder's functionality to provision VMs on existing Kubernetes clusters. KVM machines being used as coder workspaces unlocks these functionalities: 109 | - docker inside coder workspaces 110 | - systemd 111 | - mini kubernetes environments inside coder workspaces using [minikube](https://github.com/kubernetes/minikube) or [kind](https://github.com/kubernetes-sigs/kind) 112 | - access to raw devices (needs configuration) 113 | - nested virtualization inside coder workspace (needs configuration) 114 | - more isolation from host compared to pods 115 | and many more... 116 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /kubevirt-provisioner/main.tf: -------------------------------------------------------------------------------- 1 | terraform { 2 | required_providers { 3 | coder = { 4 | source = "coder/coder" 5 | version = "0.13.0" 6 | } 7 | kubernetes = { 8 | source = "hashicorp/kubernetes" 9 | version = "2.25.2" 10 | } 11 | } 12 | } 13 | 14 | variable "namespace" { 15 | description = <<-EOF 16 | Kubernetes namespace to deploy the workspace VM into 17 | 18 | EOF 19 | default = "coder" 20 | } 21 | 22 | variable "use_kubeconfig" { 23 | type = bool 24 | description = <<-EOF 25 | Use host kubeconfig? (true/false) 26 | 27 | Set this to false if the Coder host is itself running as a Pod on the same 28 | Kubernetes cluster as you are deploying workspaces to. 29 | 30 | Set this to true if the Coder host is running outside the Kubernetes cluster 31 | for workspaces. A valid "~/.kube/config" must be present on the Coder host. 32 | EOF 33 | default = false 34 | } 35 | 36 | provider "coder" { 37 | } 38 | 39 | provider "kubernetes" { 40 | config_path = var.use_kubeconfig == true ? "~/.kube/config" : null 41 | } 42 | 43 | data "coder_workspace" "me" { 44 | 45 | } 46 | 47 | data "coder_parameter" "os_image" { 48 | name = "os_image" 49 | display_name = "OS Image" 50 | description = "OS Image type should your workspace use?" 51 | default = "https://cloud-images.ubuntu.com/jammy/current/jammy-server-cloudimg-amd64-disk-kvm.img" 52 | mutable = false 53 | option { 54 | name = "Ubuntu 22.04" 55 | value = "https://cloud-images.ubuntu.com/jammy/current/jammy-server-cloudimg-amd64-disk-kvm.img" 56 | icon = "/icon/ubuntu.svg" 57 | } 58 | option { 59 | name = "Fedora 39" 60 | value = "https://download.fedoraproject.org/pub/fedora/linux/releases/39/Cloud/x86_64/images/Fedora-Cloud-Base-39-1.5.x86_64.qcow2" 61 | icon = "/icon/fedora.svg" 62 | } 63 | option { 64 | name = "Debian 12" 65 | value = "https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-genericcloud-amd64.qcow2" 66 | icon = "/icon/debian.svg" 67 | } 68 | option { 69 | name = "Arch Linux" 70 | value = "https://geo.mirror.pkgbuild.com/images/latest/Arch-Linux-x86_64-cloudimg.qcow2" 71 | icon = "https://cdn0.iconfinder.com/data/icons/flat-round-system/512/archlinux-512.png" 72 | } 73 | option { 74 | name = "AlmaLinux 9" 75 | value = "https://repo.almalinux.org/almalinux/9/cloud/x86_64/images/AlmaLinux-9-GenericCloud-latest.x86_64.qcow2" 76 | icon = "/icon/almalinux.svg" 77 | } 78 | option { 79 | name = "CentOS Stream 9" 80 | value = "https://cloud.centos.org/centos/9-stream/x86_64/images/CentOS-Stream-GenericCloud-9-latest.x86_64.qcow2" 81 | icon = "/icon/centos.svg" 82 | } 83 | option { 84 | name = "Rocky Linux 9" 85 | value = "https://download.rockylinux.org/pub/rocky/9/images/x86_64/Rocky-9-GenericCloud.latest.x86_64.qcow2" 86 | icon = "/icon/rockylinux.svg" 87 | } 88 | } 89 | 90 | data "coder_parameter" "linux_user" { 91 | name = "Linux username" 92 | type = "string" 93 | description = "Username for default coder workspace linux user" 94 | validation { 95 | regex = "^[a-z_][a-z0-9_-]{0,31}$" 96 | error = "Username must satisfy regex /^[a-z_][a-z0-9_-]{0,31}$/" 97 | } 98 | default = "coder" 99 | } 100 | 101 | data "coder_parameter" "cpu" { 102 | name = "CPU cores" 103 | type = "number" 104 | description = "Number of CPU Cores" 105 | icon = "https://png.pngtree.com/png-clipart/20191122/original/pngtree-processor-icon-png-image_5165793.jpg" 106 | validation { 107 | min = 1 108 | max = 4 109 | } 110 | mutable = true 111 | default = 2 112 | order = 1 113 | } 114 | 115 | data "coder_parameter" "memory" { 116 | name = "Memory (__ MB)" 117 | type = "number" 118 | description = "" 119 | icon = "https://www.vhv.rs/dpng/d/33-338595_random-access-memory-logo-hd-png-download.png" 120 | validation { 121 | min = 1024 122 | max = 8192 123 | } 124 | mutable = true 125 | default = 4096 126 | order = 2 127 | } 128 | 129 | data "coder_parameter" "disk_size" { 130 | name = "PVC (your rootfs) storage size" 131 | type = "number" 132 | description = "Number of GB of storage" 133 | icon = "https://www.pngall.com/wp-content/uploads/5/Database-Storage-PNG-Clipart.png" 134 | validation { 135 | min = 4 136 | max = 64 137 | monotonic = "increasing" 138 | } 139 | mutable = false 140 | default = 16 141 | order = 3 142 | } 143 | 144 | resource "coder_agent" "dev" { 145 | count = data.coder_workspace.me.start_count 146 | arch = "amd64" 147 | auth = "token" 148 | dir = "/home/${data.coder_parameter.linux_user.value}" 149 | os = "linux" 150 | startup_script_timeout = 300 151 | startup_script = </tmp/code-server.log 2>&1 & 157 | EOT 158 | 159 | metadata { 160 | key = "cpu" 161 | display_name = "CPU Usage" 162 | interval = 5 163 | timeout = 5 164 | script = "coder stat cpu" 165 | } 166 | metadata { 167 | key = "memory" 168 | display_name = "Memory Usage" 169 | interval = 5 170 | timeout = 5 171 | script = "coder stat mem" 172 | } 173 | metadata { 174 | key = "disk" 175 | display_name = "Disk Usage" 176 | interval = 600 # every 10 minutes 177 | timeout = 30 # df can take a while on large filesystems 178 | script = "coder stat disk --path /" 179 | } 180 | display_apps { 181 | vscode = true 182 | vscode_insiders = false 183 | web_terminal = true 184 | ssh_helper = true 185 | port_forwarding_helper = true 186 | } 187 | } 188 | 189 | resource "coder_app" "code-server" { 190 | agent_id = try(coder_agent.dev[0].id, "") 191 | slug = "code-server-${data.coder_workspace.me.owner}-${data.coder_workspace.me.name}" 192 | display_name = "code-server" 193 | icon = "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Visual_Studio_Code_1.35_icon.svg/2560px-Visual_Studio_Code_1.35_icon.svg.png" 194 | url = "http://localhost:13337/?folder=/home/${data.coder_parameter.linux_user.value}" 195 | 196 | healthcheck { 197 | url = "http://localhost:13337/healthz" 198 | interval = 3 199 | threshold = 10 200 | } 201 | } 202 | 203 | # cloud init user data and coder agent api token is stored in secret 204 | # secret is destroyed on stopping workspace and re-created on starting a workspace 205 | resource "kubernetes_secret" "cloudinit-secret" { 206 | count = data.coder_workspace.me.transition == "start" ? 1 : 0 207 | metadata { 208 | name = "coder-${data.coder_workspace.me.owner}-${data.coder_workspace.me.name}-cloudinit" 209 | namespace = var.namespace 210 | } 211 | data = { 212 | userdata = templatefile("cloud-config.yaml.tftpl", { 213 | hostname = lower(data.coder_workspace.me.name) 214 | username = lower(data.coder_parameter.linux_user.value) 215 | init_script = base64encode(try(coder_agent.dev[0].init_script, "")) 216 | coder_agent_token = try(coder_agent.dev[0].token, "") 217 | }) 218 | } 219 | } 220 | 221 | resource "kubernetes_manifest" "virtualmachine" { 222 | count = data.coder_workspace.me.transition == "start" ? 1 : 0 223 | manifest = { 224 | "apiVersion" = "kubevirt.io/v1" 225 | "kind" = "VirtualMachine" 226 | "metadata" = { 227 | "labels" = { 228 | "kubevirt.io/vm" = "coder-${data.coder_workspace.me.owner}-${data.coder_workspace.me.name}" 229 | } 230 | "name" = "coder-${data.coder_workspace.me.owner}-${data.coder_workspace.me.name}" 231 | "namespace" = "${var.namespace}" 232 | } 233 | "spec" = { 234 | "running" = true 235 | "template" = { 236 | "metadata" = { 237 | "creationTimestamp" = null 238 | "labels" = { 239 | "kubevirt.io/vm" = "coder-${data.coder_workspace.me.owner}-${data.coder_workspace.me.name}" 240 | } 241 | } 242 | "spec" = { 243 | "domain" = { 244 | "devices" = { 245 | "disks" = [ 246 | { 247 | "disk" = { 248 | "bus" = "virtio" 249 | } 250 | "name" = "coder-${data.coder_workspace.me.owner}-${data.coder_workspace.me.name}-rootfs" 251 | }, 252 | { 253 | "disk" = { 254 | "bus" = "virtio" 255 | } 256 | "name" = "cloudinitdisk" 257 | } 258 | ] 259 | "interfaces" = [ 260 | { 261 | "masquerade" = {} 262 | "name" = "default" 263 | }, 264 | ] 265 | } 266 | "resources" = { 267 | "requests" = { 268 | "cpu" = "${data.coder_parameter.cpu.value}" 269 | "memory" = "${data.coder_parameter.memory.value}M" 270 | } 271 | } 272 | } 273 | "networks" = [ 274 | { 275 | "name" = "default" 276 | "pod" = {} 277 | }, 278 | ] 279 | "terminationGracePeriodSeconds" = 300 280 | "volumes" = [ 281 | { 282 | "dataVolume" = { 283 | "name" = "coder-${data.coder_workspace.me.owner}-${data.coder_workspace.me.name}-rootfs" 284 | } 285 | "name" = "coder-${data.coder_workspace.me.owner}-${data.coder_workspace.me.name}-rootfs" 286 | }, 287 | { 288 | "cloudInitNoCloud" = { 289 | "networkData" = <<-EOT 290 | #cloud-config 291 | network: 292 | version: 2 293 | ethernets: 294 | enp1s0: 295 | dhcp4: true 296 | EOT 297 | "secretRef" = { 298 | name = "coder-${data.coder_workspace.me.owner}-${data.coder_workspace.me.name}-cloudinit" 299 | } 300 | } 301 | "name" = "cloudinitdisk" 302 | } 303 | ] 304 | } 305 | } 306 | } 307 | } 308 | } 309 | 310 | resource "kubernetes_manifest" "datavolume" { 311 | manifest = { 312 | "apiVersion" = "cdi.kubevirt.io/v1beta1" 313 | "kind" = "DataVolume" 314 | "metadata" = { 315 | "name" = "coder-${data.coder_workspace.me.owner}-${data.coder_workspace.me.name}-rootfs" 316 | "namespace" = "${var.namespace}" 317 | } 318 | "spec" = { 319 | "pvc" = { 320 | "accessModes" = [ 321 | "ReadWriteOnce", 322 | ] 323 | "resources" = { 324 | "requests" = { 325 | "storage" = "${data.coder_parameter.disk_size.value}G" 326 | } 327 | } 328 | } 329 | "source" = { 330 | "http" = { 331 | "url" = "${data.coder_parameter.os_image.value}" 332 | } 333 | } 334 | } 335 | } 336 | } 337 | 338 | # expose the vm via kubernetes service 339 | # exposed in the following format coder--..svc.cluster.local 340 | resource "kubernetes_manifest" "service" { 341 | manifest = { 342 | "apiVersion" = "v1" 343 | "kind" = "Service" 344 | "metadata" = { 345 | "name" = "coder-${data.coder_workspace.me.owner}-${data.coder_workspace.me.name}" 346 | "namespace" = "${var.namespace}" 347 | } 348 | "spec" = { 349 | "clusterIP" = "None" 350 | "selector" = { 351 | "kubevirt.io/vm" = "coder-${data.coder_workspace.me.owner}-${data.coder_workspace.me.name}" 352 | } 353 | } 354 | } 355 | } --------------------------------------------------------------------------------