How can I run the commnads in Linux vm after creation with vmware_guest

Hi All,

I am deploying vms using vmware_guest module in vcenter.

I need to run some commands after the creation of the vms either Windows or Linux. I am able run the commands in Windows with runonce.

Now I blocked to know how to run the commands in Linux after creation.

Can anyone guide me on this?

Thanks,
Phani Akkina

Hi phani akkina,

With the help of vmware_vm_shell module(https://docs.ansible.com/ansible/latest/modules/vmware_vm_shell_module.html) you can execute command inside linux vm.

Thanks & Regards,
Aravind Balaji S

Hi Arvind,

Thanks for your reply.

I need to run the commands in Linux after the creation of the vm by vmware_guest. And these commands also need to run only once. Is that possible with vmware_vm_shell? If yes do you have any example?

Thanks,
Phani Akkina

Hi Phani Akkina

Here is the example:

  • name: Create a virtual machine on given ESXi hostname
    vmware_guest:
    hostname: “{{ vcenter_hostname }}”
    username: “{{ vcenter_username }}”
    password: “{{ vcenter_password }}”
    validate_certs: no
    folder: /DC1/vm/
    name: test_vm_0001
    state: poweredon
    guest_id: centos64Guest

This is hostname of particular ESXi server on which user wants VM to be deployed

esxi_hostname: “{{ esxi_hostname }}”
disk:

  • size_gb: 10
    type: thin
    datastore: datastore1
    hardware:
    memory_mb: 512
    num_cpus: 4
    scsi: paravirtual
    networks:

  • name: VM Network
    mac: aa:bb:dd:aa:00:14
    ip: 10.10.10.100
    netmask: 255.255.255.0
    device_type: vmxnet3
    wait_for_ip_address: yes
    delegate_to: localhost
    register: deploy_vm

  • name: Change hostname of guest machine
    vmware_vm_shell:
    hostname: “{{ vcenter_hostname }}”
    username: “{{ vcenter_username }}”
    password: “{{ vcenter_password }}”
    validate_certs: no
    datacenter: “DC1”
    folder: “/DC1/vm”
    vm_id: “{{ vm_name }}”
    vm_username: testUser
    vm_password: SuperSecretPassword
    vm_shell: “/usr/bin/hostnamectl”
    vm_shell_args: “set-hostname new_hostname > /tmp/$$.txt 2>&1”
    delegate_to: localhost

Hi Aravind,

This will execute the commands on the vm whenever I run the playbook. But I want to run the commands when vm is created only.

Thanks,
Phani Akkina

Hi Phani Akkina,

In the response of vmware_guest module you can find whether VM is created or not while executing vmware_guest module.

Use the response of vmware_guest module and execute vmware_vm_shell module.

Thanks & Regards,
Aravind Balaii S