13 Replies Latest reply on Dec 11, 2017 7:55 PM by xialingming

    how to run a script when i create a virtual machine successfully?

    xialingming Novice

      Hi all, i have a command like "curl -F "name=daniel;type=text/foo" example.com" to run 

      after my virtual machine deployed successfully.

      i have seen that the api from vCenter :POST https://{server}/rest/vcenter/vm

      have no paramete to set about the customize script to run after my deoloyment.

      can someone help me about the problem.

        • 1. Re: how to run a script when i create a virtual machine successfully?
          jasnyder Hot Shot

          Using the vSphere Automation Rest API (which is not yet fully featured), I don't believe it is possible to do guest customization or guest operations functions (like interacting with processes inside the guest).  You can do those things through the full web services API, which is SOAP/XML based and not easy to consume from curl. 

           

          If you're OK with using PowerCLI, you could create the VM and then call Invoke-VMScript to run something inside the guest.  I am assuming since your example is using curl that you're on Linux, so you would need to look into using PowerCLI on Linux.

          You may also be able to use the vmrun utility from the VIX library to execute commands - https://www.vmware.com/support/developer/vix-api/

          • 2. Re: how to run a script when i create a virtual machine successfully?
            xialingming Novice

            So glad with your kindness apply.

            I am fresh new to Vmware vsphere and i confused about "create a virtual machine" by vSphere Automation Rest API JUST return a vm ID, does that means there is no operation system on my new created virtual machine after my invoke of the create api?

            if i want my virtual machine work properly, i should mount ISO to my new created virtual machine by call the Mount Api and power the vm on by Power on API, then my virtual machine boot from the ISO, then i should Unmount the ISO, am i right?

            PowerCLI may not support my demand, i have to manager the virtual machines by python.

             

            one more question..

            When can i get the IP address of the virtual machine? does any api support my demand?

             

            wish your words..

             

            best regard.

            • 3. Re: how to run a script when i create a virtual machine successfully?
              jasnyder Hot Shot

              If you're good with Python, take a look at pyvmomi - GitHub - vmware/pyvmomi: VMware vSphere API Python Bindings

               

              Make sure to grab the samples project as well - https://github.com/vmware/pyvmomi-community-samples/tarball/master

               

              Those bindings use the vSphere Web Services API, which is SOAP/XML based, but is fully featured.  It's not intuitive so be prepared for some learning curve.  You can find the API reference here - https://code.vmware.com/apis/196/vsphere

               

              If you're looking to automate the build of a virtual machine via the API, the easiest way to do it is with a machine clone operation, with OS customization included as part of the clone spec.  With this approach, you build the template VM by hand to the way you want it before, shut it down, and mark it as a template in vCenter.  Then you call a vm.CloneVM_Task() on the template using the API, and specify a customization spec in the clone spec as part of the operation.  After cloning you can use the vm.ReconfigVM_Task() API call to reconfigure the hardware to the way you want it (memory, CPU, etc.).  Last, call vm.PowerOnVM_Task() to power it on.

               

              Not that any API call that ends in "_Task" returns a reference to a Task managed object.  This means it simply goes to vCenter and initiates a task and then returns.  In order to track the task you need to check on it in subsequent calls and wait for it to complete or fail.

               

              After completion of the steps above, use GuestProcessManager.StartProgramInGuest to kick off a process within the guest VM (i.e. script).

               

              Review the pyvmomi samples for examples on how to interact with various things.  The clone_vm.py has an example for cloning a VM from template.  The execute_program_in_vm.py example shows how to execute a program in a guest VM.  I did not see any examples in the sample project that show adding guest customization to the VM clone process or reconfiguring a VM, so you'll have to explore to get those going.

              • 4. Re: how to run a script when i create a virtual machine successfully?
                xialingming Novice

                That is a great help.

                "machine clone operation" sounds perfect for my demand.

                As you have mentioned, i can specify OS customization as part of the clone spec. 

                And i found CustomizationOptions(which has linux operations) parameter to CustomizationSpec may works, yes sound intuitive...and i found no sample usage about the CustomizationOptions( it is blank)

                I have a few question more.

                1.After my clone operation does the vm have operation system run on it?

                2.To manage virtual machines, do i have to has a datacenter 、cluster and folder first?

                 

                I am approaching the answer, so kind of you.

                 

                Best Regard.

                 

                 

                 

                • 5. Re: how to run a script when i create a virtual machine successfully?
                  jasnyder Hot Shot

                  1.After my clone operation does the vm have operation system run on it?

                  Yes the clone operation will make an exact copy of the template virtual machine.  First you build the template with the operating system and any software you want to include on it as well as all configurations and settings.  If you have multiple operating system builds you want to be able to clone, you would make multiple templates.  Each one would be the baseline for the configuration you want to be able to automate.

                   

                  After the clone operation, you will have created a second virtual machine that is an exact copy of the first.  If you include a guest customizaton specification, it will make the build unique.  In a Windows environment, this will run sysprep.  In both Windows and Linux, it will apply a hostname, DNS settings, and IP configuration according to the customization specification settings in the clone operation.  This effectively makes the copy unique from the template machine.

                   

                  At this point you will have a new virtual machine with the same operating system and software, users, configuration settings, etc. as the template.  You can further customize it by running the scripts and commands that you wanted to run.  There is no need to automate the installation of the OS because it will already be loaded.

                   

                  2.To manage virtual machines, do i have to has a datacenter 、cluster and folder first?

                  For vCenter to work, you will have to have created the first datacenter, added at least one host to the datacenter, have a vSwitch and port group, and a datastore.  You don't need a cluster, but you do need either a standalone ESXi host managed by vCenter or a cluster.

                   

                  You can also point the API directly at standalone ESXi host.  In that case you don't need vCenter.  It is not recommended to go straight to an ESXi host that is already managed by vCenter (as inventories will get out of sync on the two); although it is possible to do so.

                   

                  As far as folders go - a datacenter in vCenter (or a host if you are using standalone ESXi without vCenter) will have a root VM Folder called vm.  It will also have 3 other root folders - network, host, datastore.  These are the branches of the tree to hold the different types of objects in the inventory.  A standalone host also has these 4 folders.  Any host or cluster that is added to vCenter will show up in the host tree; any datastore added will show up in the datastore tree; any vSwitch, port group, dvSwitch, or dvPort group will show up in the network folder.  Each branch of the tree can have child folders and each object type in each branch can show up at any level in the tree (i.e. does not have to be at the root level).

                   

                  When specifying a clone operation, you would need to provide the target VM folder, which can be the datacenter's or host's root VM folder 'vm' or any folder in the vm branch of the tree.

                   

                  Hope that answers your questions.  Let me know if you have any more.

                  • 6. Re: how to run a script when i create a virtual machine successfully?
                    xialingming Novice

                    That‘s pretty detailed of your answers, thank you so much.

                    Before i kick off, the last question about authorization to be conformed.

                    I will have to get token from vSphere serve first by SmartConnect Api in python, and use that token in my sequent operations?

                    like one piece of code in clone_vm.py the sample you mentioned before show:

                    ```

                    si = SmartConnect(

                            host=args.host,

                            user=args.user,

                            pwd=args.password,

                            port=args.port)

                          atexit.register(Disconnect, si)

                     

                        content = si.RetrieveContent()

                        template = None

                     

                        template = get_obj(content, [vim.VirtualMachine], args.template)

                     

                        if template:

                            clone_vm(

                               content, template, args.vm_name, si,

                                args.datacenter_name, args.vm_folder,

                                args.datastore_name, args.cluster_name,

                                args.resource_pool, args.power_on, args.datastorecluster_name)

                    ```

                    content act as the rule of token, right?

                    jasnyder, thanks for your help.

                    • 7. Re: how to run a script when i create a virtual machine successfully?
                      jasnyder Hot Shot

                      SI = Service Instance (AKA an instantiation of the API endpoint; represents the root of the vCenter inventory)

                      Content = Service Content - describes the content of the instance and contains references to all the various manager objects that manage all kinds of things on the server.

                       

                      See here - Online Documentation - vSphere Web Services API Reference - VMware {code}

                       

                      The following picture from that page should should help explain it:

                      ServiceInstance UML

                       

                       

                      Here is another good picture from the ServiceInstance page - Online Documentation - vSphere Web Services API Reference - VMware {code}

                       

                      vCenter ServiceInstance Hierarchy

                      1 person found this helpful
                      • 8. Re: how to run a script when i create a virtual machine successfully?
                        xialingming Novice

                        I see.

                        Thanks for your great help.

                        Your explanation helps me a lot.

                        • 9. Re: how to run a script when i create a virtual machine successfully?
                          xialingming Novice

                          hi, jasnyder still there?

                          I have one question about IP setting, How can i specify a VLAN for my virtual machine so that can assign ip from it?

                          Did the virtual switch has dhcp ability?

                          Can i config the virtual machine to NAT、Bridge?

                          I confused once more.

                          • 10. Re: how to run a script when i create a virtual machine successfully?
                            jasnyder Hot Shot

                            The VLAN the machine is on is set using the VLAN ID on the port group or distributed virtual port group to which the machine's NIC(s) is/are attached.

                             

                            So when you clone the machine, if you do not change the network connected to the NIC(s) on the machine, it will retain the same network connection it had on the original VM.  If you need to attach it to a different VLAN, you need to specify that change in the location part of the clone spec.  I.e.

                            CloneSpec.location.deviceChange[0].device.backing.port would point to a dvPortGroup.

                             

                            deviceChange is an array of deviceSpecs that define what devices are changing.  In this case you need to provide an array of VirtualEthernetCard objects that match the key of each NIC that is getting changed.  Then set the backing to the appropriate type of VirtualEthernetCardBacking which is different for a standard port group or a dvPort group.

                             

                            It's kind of confusing, but I hope that makes some sense.

                             

                            Once you get the machine connected to the VLAN, the IP settings are either made statically (which can be passed in via the customization specification) or with DHCP.  If you use DHCP, the DHCP server needs to be configured external to vSphere - there is no DHCP capability on the vSwitches or dvSwitches.  Normal rules for handling DHCP forwarding between VLANs apply in this case (i.e. iphelper rules might need to be configured in the switch to forward DHCP traffic from the source VLAN to a target VLAN where a DHCP server is located).

                            • 11. Re: how to run a script when i create a virtual machine successfully?
                              xialingming Novice

                              I did not get your word. Did you mean if i have no DHCP server i have to pass IP address to the VM i cloned manually? or VM will have no ip address after clone?

                              That's really confused me.

                              Assume that i have a vlan 192.168.23.0/24 which have been set on distributed virtual port group. I want every cloned VM configured to an unique unused ip automatically in the VLAN 192.168.23.0/24. what should i do? I have to deploy a DHCP server and config the DHCP server with the vlan info?

                              when i create or clone a virtual machine and specify the NIC to port group(vlan on it ) BUT no DHCP  there will no ip set on the VM?

                              I am doing investigation on vsphere.

                              Waiting for your answer, Master jasnyder

                              • 12. Re: how to run a script when i create a virtual machine successfully?
                                jasnyder Hot Shot

                                I did not get your word. Did you mean if i have no DHCP server i have to pass IP address to the VM i cloned manually? or VM will have no ip address after clone?

                                When you clone a VM, you can either customize it or not.

                                • If you do not customize the VM -
                                  • The VM will retain all settings, including IP, from the original.  This would be an exact clone of the original.
                                • If you do customize the VM -
                                  • You can set DHCP in the cusotmization spec - The VM will get its IP address from a DHCP server on the network.  This function is not provided by vSphere.  If you have NSX, NSX Edge appliances can provide DHCP, but this is not part of the core vSphere product.
                                  • Or - you can specify the IP address manually - this sets the VM adapter settings in static IP configuration, and you need to provide what those settings are (DNS, NTP, suffix, address, mask, gateway, etc.) in the customization spec.

                                Assume that i have a vlan 192.168.23.0/24 which have been set on distributed virtual port group. I want every cloned VM configured to an unique unused ip automatically in the VLAN 192.168.23.0/24. what should i do? I have to deploy a DHCP server and config the DHCP server with the vlan info?

                                You should establish a DHCP server with appropriate scope to hand out IP addresses in that VLAN.  You will have to build this server manually if it does not already exist.

                                 

                                If the DHCP server is not in the same VLAN as the machines you're cloning, then you will need to ensure that your networking equipment is configured to forward DHCP packets to the VLAN where the DHCP server is located.

                                 

                                If it is on the same VLAN, then the packets will make it to the DHCP server because they occupy the same broadcast domain. 

                                 

                                 

                                when i create or clone a virtual machine and specify the NIC to port group(vlan on it ) BUT no DHCP  there will no ip set on the VM?

                                 

                                If you specify DHCP in the customization spec and there is no DHCP server available to answer the request - the adapter will either auto-configure itself with an APIPA address (i.e. 169.254.x.x) or it will get no settings.

                                 

                                If you specify manual/static IP configuration, then the server will get whatever configuration you specify in the customization specification.

                                 

                                You can test all of this manually in the vSphere client by right-clicking a VM or template, and clicking Clone --> Clone to Virtual Machine...:

                                After setting the name, target folder, target host, and target datastore, you can choose to customize it or not:

                                In order to do this, you must have already created a customization specificartion from within Home --> Policies and Profiles --> Customization Specification Manager

                                 

                                You can see the list of my available specs, and I have one set for DHCP as well as ones set that take static IP:

                                 

                                Depending on how you configured the customization specification, you will be prompted for some values to enter for the customization.  In this case, it is prompting for static IP settings.  If the customization specification was set for DHCP, it would not ask for the networking properties.

                                 

                                Note that guest customization requires interfacing with VMware Tools on the VM, so you should make sure you have installed VMware tools on Windows machines or the appropriate open-vm-tools package on Linux machines to ensure proper functionality.  Linux machines also rely on Perl being present/installed, so make sure these are on your template VM when you build it.

                                 

                                • 13. Re: how to run a script when i create a virtual machine successfully?
                                  xialingming Novice

                                  Thanks a lot.

                                  I see what you mean.