in Devops, Openstack, Terraform

Provision an OpenStack instance with Terraform


A quick way to create an instance on OpenStack is to use Terraform, an open-source Infrastructure-as-Code (IaC) tool developed by HashiCorp.
Here is my environment, quickly drawn 😉 :

This instance will be provisioned with Linux CirrOS.
The Terraform plan that i used :

# Creating an SSH key pair resource
resource "openstack_compute_keypair_v2" "MaCle2" {
  provider   = openstack.hello # Provider name declared in provider.tf
  name       = "MaCle2" # Name of the SSH key to use for creation
  public_key = file("~/.ssh/id_rsa.pub") # Path to your previously generated SSH key
}

# Creating the instance
resource "openstack_compute_instance_v2" "create_an_instance" {
  name        = "MonInstance2" #Instance name
  provider    = openstack.hello  # Provider name
  image_name  = "cirros-0.5.2-x86_64-disk" # Image name
  flavor_name = "m1.nano" # Instance type name
  key_pair    = openstack_compute_keypair_v2.MaCle2.name
  security_groups = ["default"]
  network {
    name      = "Shared" # Adds the network component to reach your instance
  }
}

The provider to use to interact with OpenStack is terraform-provider-openstack :

# Define providers and set versions
terraform {
required_version    = ">= 0.14.0" 
  required_providers {
    openstack = {
      source  = "terraform-provider-openstack/openstack"
      version = "~> 1.42.0"
    }
  }
}

# Configure the OpenStack provider 
provider "openstack" {
  auth_url    = "http://10.0.2.15/identity" # Authentication URL
  domain_name = "default" 
  alias       = "hello" 
}

The documentation for terraform-provider-openstack can be found here :
https://registry.terraform.io/providers/terraform-provider-openstack/openstack/latest/docs

Commands to run :
1) terraform validate : to validate/verify the configuration

2) terraform plan : to preview the changes

3) terraform apply : to actually apply/run the actions

4) terraform destroy : to destroy everything and return to the initial state. In this case, that means both the instance and the key will be deleted.

This is part of the output after running the “terraform apply” instruction :

Of course, the OpenStack environment variables need to be set first :

source admin-openrc.sh