Sunday 12 November 2017

Creating infra with Terraform and VSphere


Terraform used to created infra from many providers, let us one example with VSphere

we will export the path for terraform log file as per given commands

Step1) export TF_LOG_PATH=./terraform.log
export TF_LOG=TRACE

Creating tf file which has following contents

Step 2) create myfirst.tf file with following contents.

# Configure the VMware vSphere Provider
provider “vsphere” {
user           = “${var.vsphere_user}”
 password       = “${var.vsphere_password}”
vsphere_server = “${var.vsphere_server}”
allow_unverified_ssl = “true”
}
# Create a folder
resource “vsphere_folder” “Backend” {
path = “VirtualMachines”
datacenter = “datacenter1”
}

resource “vsphere_virtual_machine” “My_Vm” {
name   = “My_Vm”
vcpu   = 1
memory = 1024
datacenter = “datacenter1″
resource_pool = “mypool”
folder = “${vsphere_folder.backend.path}”
 network_interface {
label = “VM Network”
 }

disk {
datastore = “datastore1”
vmdk = “/test2/test2”   
 }
}
First section defines provider with credentials, based on your understanding you can seperate this file, like writing provider.tf file, but now write only one file.
Second section creates one folder “VMs” under “datacenter1”.
Third section actually creates a VM. resource_pool defines from where resources like cpu and memory should be assigned.  Network interface is the existing network.
Fourth section defines vmdk or template path ( use any one of ).

Step 3) Create variables.tf file , to define variables
————————————————————
variable “vsphere_user” {}
variable “vsphere_password” {}
variable “vsphere_server” {}

————————————————————
Here, variables are defined that are being used in myfirst.tf file.


Step 4) Create terraform.tfvars file where you have placed values for the variables.
—————————————————————-
vsphere_user = “root”
vsphere_password = “mypswd”
vsphere_server = “IpAddress”
—————————————————————-
In this file, provide the values for the defined variables. “terraform.tfvars”  is the default name for variables file. If you used any other file name, then you need to pass it while applying the terraform.

Step 5) Run from that directory where all these files are placed.

$ terraform plan
$ terraform apply
$ terraform show