This page describes how to create a new VM by using Terraform or OpenTofu.
Pre-requisites
The following pre-requisites must be satisfied.
- Have read and followed the EWC - IaC via Terraform and OpenTofu page.
 - The Terraform or OpenTofu CLI installed.
 - Application credentials to access the Openstack cloud project
 
There is a set of mandatory inputs required to create a new VM which are:
- image_name : the Virtual Machine image (see EWC - VM images and default users )
 - flavor_name : the resources (CPU, RAM, Disk) configuration for the VM (see as reference EWC VM plans )
 - key_pair : configured SSH key which is needed to connect to the VM (see EWC - OpenStack Command-Line client for how to import it )
 - security_groups : security groups are sets of applied IP filter rules which define networking access to the instance
 - network : the network to be attached to the VM : external-internet: access to the Internet with public IP ; private-<tenant>: local private network within the tenant.
 
Create a directory for your configuration and change directory into it: Create the main configuration file to define the infrastructure: Open the  Replace the following fields as desired: For instance for ECMWF can be : Initialize the directory : Terraform OpenTofu Review the required changes:  Apply the changes to create the VM : Terraform OpenTofu Status can be then seen via: Terraform OpenTofu The created VM can be then destroyed by simply running: Terraform OpenTofu
The available selectable options could also be checked using the Opnstack CLI commands :$ openstack keypair list
 
$ openstack image list
 
$ openstack flavor list 
 
$ openstack network list
Write configuration files
$ mkdir example-create-vm
$ cd example-create-vm
$ touch main.tf
main.tf file in a text editor and fill it as needed like in the following example :# Define required providers
terraform {
  required_providers {
    openstack = {
      source  = "terraform-provider-openstack/openstack"
    }
  }
}
# Configure the OpenStack Provider
provider "openstack" {
  # ...
}
resource "openstack_compute_instance_v2" "server-name" {
  name            = "server-name"
  image_name      = "image-name"
  flavor_name     = "flavor-name"
  key_pair        = "key-name"
  security_groups = ["secgroup-name-1", "secgroup-name-2", ...]
  network {
    name = "network-name"
  }
}
resource "openstack_compute_instance_v2" "test-server" {
  name            = "test-server"
  image_name      = "Rocky-9.4-20240717094419"
  flavor_name     = "2cpu-2gbmem-30gbdisk"
  key_pair        = "mykey"
  security_groups = ["default", "ssh"]
  network {
    name = "private-cci1-ewcloud-ms-nmhs-project"
  }
}
Run Terraform or OpenTofu to create a VM
$ terraform init
$ tofu init
$ terraform plan
$ terraform apply
$ tofu apply
$ terraform show
$ tofu show
Destroy the VM
$ terraform destroy
$ tofu destroy