vsphere_virtual_machine creation

In a previous blog we looked at how to identify an existing vSphere virtual machine and add it as a data element so that it can be referenced. In this blog we will dive a little deeper and look at how to define a similar instance as a template then use that template to create a new virtual machine using the resource command.

It is important to note that we are talking about three different constructs within Terraform in the previous paragraph.

  • data declaration – defining an existing resource to reference it as an element. This element is considered to be static and can not be modified or destroyed but it does not exist, terraform will complain that the declaration failed since the element does not exist. More specifically, data vsphere_virtual_machine is the type for existing vms.
  • template declaration – this is more of a vSphere and not necessarily a Terraform definition. This defines how vSphere copies or replicates an existing instance to create a new one as a clone and not necessarily from scratch
  • resource declaration – defining a resource that you want to manage. You can create, modify, and destroy the resource as needed or desired with the proper commands. More specifically, resource vsphere_virtual_machine is the type for new or managed vms.

We earlier looked at how to generate the basic requirements to connect to a vSphere server and how to pull in the $TF_VAR_<variable> label to connect. With this we were able to define the vspher_server, vsphere_user, and vspher_password variable types using a script. If we use the PowerCLI module we can actually connect using this script using the format

Connect-VIServer -Server $TF_VAR_vsphere_server -User $TF_VAR_vsphere_user -Password $TF_VAR_vsphere_password

This is possible because if the values do not exist then they are assigned in the script file. From this we can fill in the following data

  • vsphere_datacenter from Get-Datacenter
  • vsphere_virtual_machine (templates) from Get-Template
  • vsphere_host from Get-Datacenter | Get-VMHost
  • vsphere_datastore from Get-Datastore

The vsphere_datacenter assignment is relatively simple

$connect = Connect-VIServer -Server $TF_VAR_vsphere_server -User $TF_VAR_vsphere_user -Password $TF_VAR_vsphere_password

$dc = Get-Datacenter
Write-Host ‘# vsphere_datacenter definition’
Write-Host ‘ ‘
Write-Host -Separator “” ‘data “vsphere_datacenter” “dc” {
name = “‘$dc.Name'”‘
‘}’
Write-Host ‘ ‘

This results in an output that looks like…

# vsphere_datacenter definition

data “vsphere_datacenter” “dc” {
name = “Home-lab”
}

This is the format that we want for our parameter.tf file. We can do something similar for the vm templates

Write-Host ‘# vsphere_virtual_machine (template) definition’
Write-Host ‘ ‘
$Template_Name = @()
$Template_Name = Get-Template

foreach ($item in $Template_Name) {
Write-Host -Separator “” ‘data “vsphere_virtual_machine” “‘$item'”‘ ‘ {
name = “‘$item'”‘
‘ datacenter_id = data.vsphere_datacenter.dc.id
}’
Write-Host ‘ ‘
}
Write-Host ‘ ‘

This results in the following output…

#vsphere_virtual_machine (template) definition

data “vsphere_virtual_machine” “win_10_template” {
name = “win_10_template”
datacenter_id = data.vsphere_datacenter.dc.id
}

data “vsphere_virtual_machine” “win-2019-template” {
name = “win-2019-template”
datacenter_id = data.vsphere_datacenter.dc.id
}

We can do similar actions for vsphere_host using

$Host_name = @()
$Host_name = Get-Datacenter | Get-VMHost

as well as vsphere_datastore using

$Datastore_name = @()
$Datastore_name = Get-Datastore

The resulting output is a terraform ready parameter file that represents the current state of our environment. The datacenter, host, and datastores should not change from run to run. We might define new templates so these might be added or removed but this script should be good for generating the basis of our existing infrastructure and give us the foundation to build a new vsphere_virtual_machine.

To create a vsphere_virtual_machine we need the following elements

  • name
  • resource_pool_id
  • disk
    • label
  • network_interface
    • network_id

These are the minimum requirements required by the documentation and will allows you to pass the terraform init but the apply will fail. Additional values that are needed

  • host_system_id – host to run the virtual machine on
  • guest_id – identifier for operating system type (windows, linux, etc)
  • disk.size – size of disk
  • clone.template_uuid – id of template to clone to create the instance.

The main.tf file that works to create our instance looks like

data “vsphere_virtual_machine” “test_minimal” {
name = “esxi6.7”
datacenter_id = data.vsphere_datacenter.dc.id
}

resource “vsphere_virtual_machine” “vm” {
name = “terraform-test”
resource_pool_id = data.vsphere_resource_pool.Resources-10_0_0_92.id
host_system_id = data.vsphere_host.Host-10_0_0_92.id
guest_id = “windows9_64Guest”
network_interface {
network_id = data.vsphere_network.VMNetwork.id
}
disk {
label = “Disk0”
size = 40
}
clone {
template_uuid = data.vsphere_virtual_machine.win_10_template.id
}
}

The Resources-10_0_0_92, Host-10_0_0_92, and win_10_template were all generated by our script and we pulled them from the variables.tf file after it was generated. The first vm “test_minimal” shows how to identify an existing virtual_machine. The second “vm” shows how to create a new virtual machine from a template.

The files of interest in the git repository are

  • connect.ps1 – script to generate variables.tf file
  • main.tf – terraform file to show example of how to declare virtual_machine using data and resource (aka create new from template)
  • variables.tf – file generated from connect.ps1 script after pointing to my lab servers

All of these files are located on https://github.com/patshuff/terraform-learning. In summary, we can generate our variables.tf file by executing a connext.ps1 script. This script generates the variables.tf file (test.yy initially but you can change that) and you can pull the server, resource_pool, templates, and datastore information from this config file. It typically only needs to be run once or when you create a new template if you want it automatically created. For my simple test system it took about 10 minutes to create the virtual machine and assign it a new IP address to show terraform that the clone worked. We could release earlier but we won’t get the IP address of the new virtual instance.

116 thoughts on “vsphere_virtual_machine creation”

  1. Привет друзья!

    Есть такой интересный сайт https://ruposters.ru/

    Из последних новостей шоу бизнеса узнал, что:Знаменитости из России Лобода и Константин Меладзе поселились в Латвии, а детей пристроили в элитные школы.

    А певец Николай Басков впервые высказался по политической теме, осудив бежавших звезд из России.

    Рэпер Тимати посетил военный госпиталь, и привез около полусотни средств реабилитации для раненных военнослужащих, чтобы те быстрее возвращались к обычной жизни.

    Хорошего дня!

  2. My wife and i have been so happy Peter managed to finish up his reports with the precious recommendations he obtained from your own site. It is now and again perplexing just to be giving freely hints that many other folks have been selling. We fully grasp we need the website owner to give thanks to because of that. The specific illustrations you made, the simple site menu, the relationships your site aid to create – it is all amazing, and it’s helping our son in addition to our family reckon that the article is exciting, and that is especially essential. Many thanks for all!

  3. Thanks for all of the work on this web site. My mum takes pleasure in setting aside time for research and it is easy to see why. Most people notice all relating to the powerful method you create valuable suggestions via this web blog and in addition improve contribution from other individuals on the content plus my daughter is now understanding a lot. Take pleasure in the rest of the new year. You are always performing a superb job.

  4. Приветствую Вас господа!
    Есть такой замечательный сайт https://dengi-do-zarplaty.ru/
    Первое, что приходит в голову – это обратиться в банк. Но здесь есть нюансы. Чтобы оформить деньги в кредит в банке, понадобиться время, которого иногда нет. Или к примеру, если человек имеет плохую кредитную историю, банк однозначно не одобрит ему запрашиваемые средства. Получить желаемую сумму будет также сложно тем, кто не имеет официальной работы и постоянного дохода.Если в Ваши планы входит взять деньги в долг без банков и поручителей, в таком случае единственным выходом из ситуации будет – оформление микрозайма в МФО. Все выше перечисленные категории заемщиков, которые считаются максимально рискованными для банковского сектора, в МФО получают положительное решение по выдачи средств.

  5. Привет уважаемые!
    Есть такой замечательный сайт https://dengi-do-zarplaty.ru/
    Первое, что приходит в голову – это обратиться в банк. Но здесь есть нюансы. Чтобы оформить деньги в кредит в банке, понадобиться время, которого иногда нет. Или к примеру, если человек имеет плохую кредитную историю, банк однозначно не одобрит ему запрашиваемые средства. Получить желаемую сумму будет также сложно тем, кто не имеет официальной работы и постоянного дохода.Если в Ваши планы входит взять деньги в долг без банков и поручителей, в таком случае единственным выходом из ситуации будет – оформление микрозайма в МФО. Все выше перечисленные категории заемщиков, которые считаются максимально рискованными для банковского сектора, в МФО получают положительное решение по выдачи средств.

  6. I wanted to develop a simple message to thank you for these lovely points you are writing at this site. My time intensive internet look up has at the end of the day been honored with awesome tips to go over with my partners. I ‘d say that we visitors are unquestionably blessed to dwell in a notable place with very many awesome individuals with great methods. I feel extremely blessed to have seen your webpage and look forward to some more fabulous moments reading here. Thanks once more for everything.

  7. I have to convey my passion for your generosity for those individuals that actually need help with this particular niche. Your very own commitment to passing the message up and down has been especially powerful and has regularly allowed others like me to achieve their aims. Your new helpful information implies a lot to me and extremely more to my office workers. Regards; from all of us.

  8. Thanks so much for providing individuals with an extraordinarily splendid possiblity to check tips from this web site. It is often very nice and also full of a great time for me personally and my office co-workers to visit your web site nearly three times a week to find out the latest secrets you will have. Not to mention, I am just actually amazed for the surprising information served by you. Selected 1 tips in this article are without a doubt the finest I have ever had.

  9. I in addition to my buddies have been looking at the excellent techniques from your web page and immediately got a terrible feeling I had not thanked the blog owner for those tips. These people came consequently stimulated to see all of them and have now absolutely been using these things. Thanks for actually being quite kind as well as for having certain useful guides millions of individuals are really wanting to understand about. My sincere regret for not expressing appreciation to you sooner.

  10. I as well as my pals were found to be checking out the good guidelines found on your web blog and immediately got a terrible feeling I had not expressed respect to the web site owner for those techniques. All of the guys were definitely as a result very interested to read through all of them and have now undoubtedly been tapping into those things. Thanks for turning out to be well considerate and then for making a choice on this sort of beneficial resources millions of individuals are really desirous to learn about. Our own sincere regret for not saying thanks to you earlier.

  11. My husband and i have been really comfortable Ervin could round up his preliminary research via the ideas he was given out of the web site. It’s not at all simplistic to just be handing out guidance that many others may have been making money from. Therefore we figure out we have the blog owner to give thanks to for that. All of the explanations you’ve made, the easy website menu, the friendships you can give support to foster – it’s got most superb, and it’s letting our son and us believe that that content is cool, and that’s very fundamental. Thanks for the whole lot!

  12. I wanted to post you that bit of remark just to give many thanks once again for these wonderful opinions you have provided on this site. It’s so shockingly open-handed of people like you in giving freely all that most of us would have advertised for an e-book to generate some profit on their own, mostly now that you could possibly have done it in case you desired. These tricks additionally acted to become fantastic way to recognize that many people have the same dreams similar to my personal own to know somewhat more pertaining to this issue. I’m sure there are numerous more enjoyable opportunities ahead for those who look over your blog post.

  13. I in addition to my pals have been reviewing the great ideas located on your site and then all of the sudden I had an awful suspicion I had not thanked the website owner for those strategies. Those people were happy to study all of them and have now seriously been having fun with these things. We appreciate you genuinely indeed accommodating and also for opting for some beneficial ideas most people are really desirous to discover. My very own sincere regret for not expressing appreciation to sooner.

  14. I in addition to my guys appeared to be taking note of the great thoughts on your site then unexpectedly I had an awful feeling I had not expressed respect to the website owner for those secrets. These men became as a consequence thrilled to see all of them and have in effect in fact been using them. Thanks for indeed being well kind and then for finding variety of exceptional things most people are really desperate to learn about. My sincere apologies for not expressing appreciation to you earlier.

  15. I wish to express my love for your kind-heartedness for men and women that have the need for assistance with this one matter. Your special commitment to getting the message up and down had been pretty insightful and has enabled people just like me to arrive at their endeavors. This insightful report indicates this much a person like me and far more to my fellow workers. Regards; from each one of us.

  16. I wish to express my appreciation to you for rescuing me from such a difficulty. As a result of browsing through the search engines and obtaining things which are not powerful, I figured my entire life was done. Existing without the solutions to the issues you’ve solved as a result of the guideline is a critical case, as well as ones that would have in a negative way damaged my entire career if I hadn’t discovered the blog. Your primary expertise and kindness in maneuvering all the pieces was important. I am not sure what I would’ve done if I had not come upon such a solution like this. I can at this time look forward to my future. Thanks so much for the specialized and sensible help. I will not be reluctant to suggest your web sites to any individual who should receive direction on this subject matter.

  17. I needed to create you that little note to finally say thank you yet again for your personal amazing tactics you’ve shown in this article. It is pretty generous of you to deliver freely precisely what many of us would have marketed for an ebook to earn some bucks for their own end, primarily considering the fact that you might well have done it in case you considered necessary. Those things in addition acted to be a fantastic way to be sure that other people online have the same keenness just like my own to find out more in respect of this problem. I am sure there are many more pleasant opportunities in the future for people who browse through your website.

  18. I simply desired to appreciate you yet again. I’m not certain the things that I would’ve followed without the entire tips revealed by you directly on such a topic. It was before the hard crisis in my position, but encountering your professional form you treated it made me to leap over happiness. I’m thankful for the information and then expect you are aware of an amazing job you happen to be undertaking educating others through the use of your blog post. Most likely you’ve never met any of us.

Leave a Reply

Your email address will not be published. Required fields are marked *