func dataSourceCloudstackInstanceRead()

in cloudstack/data_source_cloudstack_instance.go [96:145]


func dataSourceCloudstackInstanceRead(d *schema.ResourceData, meta interface{}) error {
	log.Printf("Instance Data Source Read Started")

	cs := meta.(*cloudstack.CloudStackClient)
	p := cs.VirtualMachine.NewListVirtualMachinesParams()
	csInstances, err := cs.VirtualMachine.ListVirtualMachines(p)

	if err != nil {
		return fmt.Errorf("Failed to list instances: %s", err)
	}

	filters := d.Get("filter")
	nic := d.Get("nic").([]interface{})
	var instances []*cloudstack.VirtualMachine

	//the if-else block to check whether to filter the data source by an IP address
	// or by any other exported attributes
	if len(nic) != 0 {
		ip_address := nic[0].(map[string]interface{})["ip_address"]
		for _, i := range csInstances.VirtualMachines {
			if ip_address == i.Nic[0].Ipaddress {
				instances = append(instances, i)
			}
		}
	} else {
		for _, i := range csInstances.VirtualMachines {
			match, err := applyInstanceFilters(i, filters.(*schema.Set))
			if err != nil {
				return err
			}

			if match {
				instances = append(instances, i)
			}
		}
	}

	if len(instances) == 0 {
		return fmt.Errorf("No instance is matching with the specified regex")
	}
	//return the latest instance from the list of filtered instances according
	//to its creation date
	instance, err := latestInstance(instances)
	if err != nil {
		return err
	}
	log.Printf("[DEBUG] Selected instances: %s\n", instance.Displayname)

	return instanceDescriptionAttributes(d, instance)
}