Exemplo n.º 1
0
func (c *GenericClient) CreateInstance(d *Driver) (string, error) {
	serverOpts := servers.CreateOpts{
		Name:             d.MachineName,
		FlavorRef:        d.FlavorId,
		ImageRef:         d.ImageId,
		SecurityGroups:   d.SecurityGroups,
		AvailabilityZone: d.AvailabilityZone,
	}
	if len(d.NetworkIds) > 0 {
		networks := make([]servers.Network, len(d.NetworkIds))
		for i, networkId := range d.NetworkIds {
			networks[i] = servers.Network{UUID: networkId}
		}
		serverOpts.Networks = networks
	}

	log.Info("Creating machine...")

	server, err := servers.Create(c.Compute, keypairs.CreateOptsExt{
		serverOpts,
		d.KeyPairName,
	}).Extract()
	if err != nil {
		return "", err
	}
	return server.ID, nil
}
Exemplo n.º 2
0
func (c *GenericClient) CreateInstance(d *Driver) (string, error) {
	serverOpts := servers.CreateOpts{
		Name:             d.MachineName,
		FlavorRef:        d.FlavorId,
		ImageRef:         d.ImageId,
		SecurityGroups:   d.SecurityGroups,
		AvailabilityZone: d.AvailabilityZone,
	}
	if d.NetworkId != "" {
		serverOpts.Networks = []servers.Network{
			{
				UUID: d.NetworkId,
			},
		}
	}

	log.Info("Creating machine...")

	server, err := servers.Create(c.Compute, keypairs.CreateOptsExt{
		serverOpts,
		d.KeyPairName,
	}).Extract()
	if err != nil {
		return "", err
	}
	return server.ID, nil
}
Exemplo n.º 3
0
func createServerInGroup(t *testing.T, computeClient *gophercloud.ServiceClient, choices *ComputeChoices, serverGroup *servergroups.ServerGroup) (*servers.Server, error) {
	if testing.Short() {
		t.Skip("Skipping test that requires server creation in short mode.")
	}

	name := tools.RandomString("ACPTTEST", 16)
	t.Logf("Attempting to create server: %s\n", name)

	pwd := tools.MakeNewPassword("")

	serverCreateOpts := servers.CreateOpts{
		Name:      name,
		FlavorRef: choices.FlavorID,
		ImageRef:  choices.ImageID,
		AdminPass: pwd,
	}
	server, err := servers.Create(computeClient, schedulerhints.CreateOptsExt{
		serverCreateOpts,
		schedulerhints.SchedulerHints{
			Group: serverGroup.ID,
		},
	}).Extract()
	if err != nil {
		t.Fatalf("Unable to create server: %v", err)
	}

	th.AssertEquals(t, pwd, server.AdminPass)

	return server, err
}
Exemplo n.º 4
0
func createNetworkServer(t *testing.T, client *gophercloud.ServiceClient, choices *ComputeChoices, networkID string) (*servers.Server, error) {
	if testing.Short() {
		t.Skip("Skipping test that requires server creation in short mode.")
	}

	name := tools.RandomString("ACPTTEST", 16)
	t.Logf("Attempting to create server: %s\n", name)

	pwd := tools.MakeNewPassword("")

	networks := make([]servers.Network, 1)
	networks[0] = servers.Network{
		UUID: networkID,
	}

	server, err := servers.Create(client, servers.CreateOpts{
		Name:      name,
		FlavorRef: choices.FlavorID,
		ImageRef:  choices.ImageID,
		AdminPass: pwd,
		Networks:  networks,
	}).Extract()
	if err != nil {
		t.Fatalf("Unable to create server: %v", err)
	}

	th.AssertEquals(t, pwd, server.AdminPass)

	return server, err
}
Exemplo n.º 5
0
func createServer(t *testing.T, client *gophercloud.ServiceClient, choices *ComputeChoices) (*servers.Server, error) {
	if testing.Short() {
		t.Skip("Skipping test that requires server creation in short mode.")
	}

	var network networks.Network

	networkingClient, err := networkingClient()
	if err != nil {
		t.Fatalf("Unable to create a networking client: %v", err)
	}

	pager := networks.List(networkingClient, networks.ListOpts{
		Name:  choices.NetworkName,
		Limit: 1,
	})
	pager.EachPage(func(page pagination.Page) (bool, error) {
		networks, err := networks.ExtractNetworks(page)
		if err != nil {
			t.Errorf("Failed to extract networks: %v", err)
			return false, err
		}

		if len(networks) == 0 {
			t.Fatalf("No networks to attach to server")
			return false, err
		}

		network = networks[0]

		return false, nil
	})

	name := tools.RandomString("ACPTTEST", 16)
	t.Logf("Attempting to create server: %s\n", name)

	pwd := tools.MakeNewPassword("")

	server, err := servers.Create(client, servers.CreateOpts{
		Name:      name,
		FlavorRef: choices.FlavorID,
		ImageRef:  choices.ImageID,
		Networks: []servers.Network{
			servers.Network{UUID: network.ID},
		},
		AdminPass: pwd,
	}).Extract()
	if err != nil {
		t.Fatalf("Unable to create server: %v", err)
	}

	th.AssertEquals(t, pwd, server.AdminPass)

	return server, err
}
Exemplo n.º 6
0
func TestCreateServerWithKeyPair(t *testing.T) {
	client, err := newClient()
	th.AssertNoErr(t, err)

	if testing.Short() {
		t.Skip("Skipping test that requires server creation in short mode.")
	}

	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	publicKey := privateKey.PublicKey
	pub, err := ssh.NewPublicKey(&publicKey)
	th.AssertNoErr(t, err)
	pubBytes := ssh.MarshalAuthorizedKey(pub)
	pk := string(pubBytes)

	kp, err := keypairs.Create(client, keypairs.CreateOpts{
		Name:      keyName,
		PublicKey: pk,
	}).Extract()
	th.AssertNoErr(t, err)
	t.Logf("Created key pair: %s\n", kp)

	choices, err := ComputeChoicesFromEnv()
	th.AssertNoErr(t, err)

	name := tools.RandomString("Gophercloud-", 8)
	t.Logf("Creating server [%s] with key pair.", name)

	serverCreateOpts := servers.CreateOpts{
		Name:      name,
		FlavorRef: choices.FlavorID,
		ImageRef:  choices.ImageID,
	}

	server, err := servers.Create(client, keypairs.CreateOptsExt{
		serverCreateOpts,
		keyName,
	}).Extract()
	th.AssertNoErr(t, err)
	defer servers.Delete(client, server.ID)
	if err = waitForStatus(client, server, "ACTIVE"); err != nil {
		t.Fatalf("Unable to wait for server: %v", err)
	}

	server, err = servers.Get(client, server.ID).Extract()
	t.Logf("Created server: %+v\n", server)
	th.AssertNoErr(t, err)
	th.AssertEquals(t, server.KeyName, keyName)

	t.Logf("Deleting key pair [%s]...", kp.Name)
	err = keypairs.Delete(client, keyName).ExtractErr()
	th.AssertNoErr(t, err)

	t.Logf("Deleting server [%s]...", name)
}
Exemplo n.º 7
0
func findServer(t *testing.T, client *gophercloud.ServiceClient) (string, bool) {
	var serverID string
	var needsDeletion bool

	err := servers.List(client, nil).EachPage(func(page pagination.Page) (bool, error) {
		sList, err := servers.ExtractServers(page)
		th.AssertNoErr(t, err)

		for _, s := range sList {
			serverID = s.ID
			needsDeletion = false

			t.Logf("Found an existing server: ID [%s]", serverID)
			break
		}

		return true, nil
	})
	th.AssertNoErr(t, err)

	if serverID == "" {
		t.Log("No server found, creating one")

		choices, err := ComputeChoicesFromEnv()
		th.AssertNoErr(t, err)

		opts := &servers.CreateOpts{
			Name:      tools.RandomString("secgroup_test_", 5),
			ImageRef:  choices.ImageID,
			FlavorRef: choices.FlavorID,
		}

		s, err := servers.Create(client, opts).Extract()
		th.AssertNoErr(t, err)
		serverID = s.ID

		t.Logf("Created server %s, waiting for it to build", s.ID)
		err = servers.WaitForStatus(client, serverID, "ACTIVE", 300)
		th.AssertNoErr(t, err)

		needsDeletion = true
	}

	return serverID, needsDeletion
}
func resourceComputeInstanceV2Create(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	computeClient, err := config.computeV2Client(d.Get("region").(string))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack compute client: %s", err)
	}

	var createOpts servers.CreateOptsBuilder

	// Determines the Image ID using the following rules:
	// If a bootable block_device was specified, ignore the image altogether.
	// If an image_id was specified, use it.
	// If an image_name was specified, look up the image ID, report if error.
	imageId, err := getImageIDFromConfig(computeClient, d)
	if err != nil {
		return err
	}

	flavorId, err := getFlavorID(computeClient, d)
	if err != nil {
		return err
	}

	// determine if volume/block_device configuration is correct
	// this includes ensuring volume_ids are set
	// and if only one block_device was specified.
	if err := checkVolumeConfig(d); err != nil {
		return err
	}

	// check if floating IP configuration is correct
	if err := checkInstanceFloatingIPs(d); err != nil {
		return err
	}

	// Build a list of networks with the information given upon creation.
	// Error out if an invalid network configuration was used.
	networkDetails, err := getInstanceNetworks(computeClient, d)
	if err != nil {
		return err
	}

	networks := make([]servers.Network, len(networkDetails))
	for i, net := range networkDetails {
		networks[i] = servers.Network{
			UUID:    net["uuid"].(string),
			Port:    net["port"].(string),
			FixedIP: net["fixed_ip_v4"].(string),
		}
	}

	createOpts = &servers.CreateOpts{
		Name:             d.Get("name").(string),
		ImageRef:         imageId,
		FlavorRef:        flavorId,
		SecurityGroups:   resourceInstanceSecGroupsV2(d),
		AvailabilityZone: d.Get("availability_zone").(string),
		Networks:         networks,
		Metadata:         resourceInstanceMetadataV2(d),
		ConfigDrive:      d.Get("config_drive").(bool),
		AdminPass:        d.Get("admin_pass").(string),
		UserData:         []byte(d.Get("user_data").(string)),
		Personality:      resourceInstancePersonalityV2(d),
	}

	if keyName, ok := d.Get("key_pair").(string); ok && keyName != "" {
		createOpts = &keypairs.CreateOptsExt{
			createOpts,
			keyName,
		}
	}

	if vL, ok := d.GetOk("block_device"); ok {
		for _, v := range vL.([]interface{}) {
			blockDeviceRaw := v.(map[string]interface{})
			blockDevice := resourceInstanceBlockDeviceV2(d, blockDeviceRaw)
			createOpts = &bootfromvolume.CreateOptsExt{
				createOpts,
				blockDevice,
			}
			log.Printf("[DEBUG] Create BFV Options: %+v", createOpts)
		}
	}

	schedulerHintsRaw := d.Get("scheduler_hints").(*schema.Set).List()
	if len(schedulerHintsRaw) > 0 {
		log.Printf("[DEBUG] schedulerhints: %+v", schedulerHintsRaw)
		schedulerHints := resourceInstanceSchedulerHintsV2(d, schedulerHintsRaw[0].(map[string]interface{}))
		createOpts = &schedulerhints.CreateOptsExt{
			createOpts,
			schedulerHints,
		}
	}

	log.Printf("[DEBUG] Create Options: %#v", createOpts)

	// If a block_device is used, use the bootfromvolume.Create function as it allows an empty ImageRef.
	// Otherwise, use the normal servers.Create function.
	var server *servers.Server
	if _, ok := d.GetOk("block_device"); ok {
		server, err = bootfromvolume.Create(computeClient, createOpts).Extract()
	} else {
		server, err = servers.Create(computeClient, createOpts).Extract()
	}

	if err != nil {
		return fmt.Errorf("Error creating OpenStack server: %s", err)
	}
	log.Printf("[INFO] Instance ID: %s", server.ID)

	// Store the ID now
	d.SetId(server.ID)

	// Wait for the instance to become running so we can get some attributes
	// that aren't available until later.
	log.Printf(
		"[DEBUG] Waiting for instance (%s) to become running",
		server.ID)

	stateConf := &resource.StateChangeConf{
		Pending:    []string{"BUILD"},
		Target:     []string{"ACTIVE"},
		Refresh:    ServerV2StateRefreshFunc(computeClient, server.ID),
		Timeout:    30 * time.Minute,
		Delay:      10 * time.Second,
		MinTimeout: 3 * time.Second,
	}

	_, err = stateConf.WaitForState()
	if err != nil {
		return fmt.Errorf(
			"Error waiting for instance (%s) to become ready: %s",
			server.ID, err)
	}

	// Now that the instance has been created, we need to do an early read on the
	// networks in order to associate floating IPs
	_, err = getInstanceNetworksAndAddresses(computeClient, d)

	// If floating IPs were specified, associate them after the instance has launched.
	err = associateFloatingIPsToInstance(computeClient, d)
	if err != nil {
		return err
	}

	// if volumes were specified, attach them after the instance has launched.
	if v, ok := d.GetOk("volume"); ok {
		vols := v.(*schema.Set).List()
		if blockClient, err := config.blockStorageV1Client(d.Get("region").(string)); err != nil {
			return fmt.Errorf("Error creating OpenStack block storage client: %s", err)
		} else {
			if err := attachVolumesToInstance(computeClient, blockClient, d.Id(), vols); err != nil {
				return err
			}
		}
	}

	return resourceComputeInstanceV2Read(d, meta)
}
Exemplo n.º 9
0
func main() {
	// step-1
	var authUsername string = "your_auth_username"
	var authPassword string = "your_auth_password"
	var authUrl string = "http://controller:5000"
	var projectName string = "your_project_id"
	var regionName string = "your_region_name"

	authOpts := gophercloud.AuthOptions{
		IdentityEndpoint: authUrl,
		Username:         authUsername,
		Password:         authPassword,
		TenantID:         projectName,
	}
	provider, _ := openstack.AuthenticatedClient(authOpts)
	client, _ := openstack.NewComputeV2(provider, gophercloud.EndpointOpts{
		Region: regionName,
	})

	// step-2
	pager := images.ListDetail(client, images.ListOpts{})
	page, _ := pager.AllPages()
	imageList, _ := images.ExtractImages(page)
	fmt.Println(imageList)

	// step-3
	pager = flavors.ListDetail(client, flavors.ListOpts{})
	page, _ = pager.AllPages()
	flavorList, _ := flavors.ExtractFlavors(page)
	fmt.Println(flavorList)

	// step-4
	imageID := "74e6d1ec-9a08-444c-8518-4f232446386d"
	image, _ := images.Get(client, imageID).Extract()
	fmt.Println(image)

	// step-5
	flavorID := "1"
	flavor, _ := flavors.Get(client, flavorID).Extract()
	fmt.Println(flavor)

	// step-6
	instanceName := "testing"
	testingInstance, _ := servers.Create(client, servers.CreateOpts{
		Name:      instanceName,
		ImageRef:  imageID,
		FlavorRef: flavorID,
	}).Extract()
	fmt.Println(testingInstance)

	// step-7
	pager = servers.List(client, servers.ListOpts{})
	page, _ = pager.AllPages()
	serverList, _ := servers.ExtractServers(page)
	fmt.Println(serverList)

	// step-8
	servers.Delete(client, testingInstance.ID)

	// step-9
	fmt.Println("Checking for existing SSH key pair...")
	keyPairName := "demokey"
	pubKeyFile := "~/.ssh/id_rsa.pub"
	keyPairExists := false

	pager = keypairs.List(client)
	page, _ = pager.AllPages()
	keypairList, _ := keypairs.ExtractKeyPairs(page)
	for _, k := range keypairList {
		if k.Name == keyPairName {
			keyPairExists = true
			break
		}
	}

	if keyPairExists {
		fmt.Println("Keypair " + keyPairName + " already exists. Skipping import.")
	} else {
		fmt.Println("adding keypair...")
		bs, _ := ioutil.ReadFile(pubKeyFile)
		keypairs.Create(client, keypairs.CreateOpts{
			Name:      keyPairName,
			PublicKey: string(bs),
		}).Extract()
	}

	pager = keypairs.List(client)
	page, _ = pager.AllPages()
	keypairList, _ = keypairs.ExtractKeyPairs(page)
	fmt.Println(keypairList)

	// step-10
	fmt.Println("Checking for existing security group...")
	var allInOneSecurityGroup secgroups.SecurityGroup
	securityGroupName := "all-in-one"
	securityGroupExists := false

	pager = secgroups.List(client)
	page, _ = pager.AllPages()
	secgroupList, _ := secgroups.ExtractSecurityGroups(page)
	for _, secGroup := range secgroupList {
		if secGroup.Name == securityGroupName {
			allInOneSecurityGroup = secGroup
			securityGroupExists = true
			break
		}
	}

	if securityGroupExists {
		fmt.Println("Security Group " + allInOneSecurityGroup.Name + " already exists. Skipping creation.")
	} else {
		allInOneSecurityGroup, _ := secgroups.Create(client, secgroups.CreateOpts{
			Name:        securityGroupName,
			Description: "network access for all-in-one application.",
		}).Extract()
		secgroups.CreateRule(client, secgroups.CreateRuleOpts{
			ParentGroupID: allInOneSecurityGroup.ID,
			FromPort:      80,
			ToPort:        80,
			IPProtocol:    "TCP",
			CIDR:          "0.0.0.0/0",
		}).Extract()
		secgroups.CreateRule(client, secgroups.CreateRuleOpts{
			ParentGroupID: allInOneSecurityGroup.ID,
			FromPort:      22,
			ToPort:        22,
			IPProtocol:    "TCP",
			CIDR:          "0.0.0.0/0",
		}).Extract()
	}

	pager = secgroups.List(client)
	page, _ = pager.AllPages()
	secgroupList, _ = secgroups.ExtractSecurityGroups(page)
	fmt.Println(secgroupList)

	// step-11
	userData := `#!/usr/bin/env bash
curl -L -s https://git.openstack.org/cgit/openstack/faafo/plain/contrib/install.sh | bash -s -- \
    -i faafo -i messaging -r api -r worker -r demo
`

	// step-12
	fmt.Println("Checking for existing instance...")
	instanceName = "all-in-one"
	instanceExists := false

	pager = servers.List(client, servers.ListOpts{})
	page, _ = pager.AllPages()
	serverList, _ = servers.ExtractServers(page)
	for _, s := range serverList {
		if s.Name == instanceName {
			testingInstance = &s
			instanceExists = true
			break
		}
	}

	if instanceExists {
		fmt.Println("Instance " + testingInstance.Name + " already exists. Skipping creation.")
	} else {
		opts := servers.CreateOpts{
			Name:           instanceName,
			ImageRef:       image.ID,
			FlavorRef:      flavor.ID,
			SecurityGroups: []string{securityGroupName},
			UserData:       []byte(userData),
		}
		testingInstance, _ = servers.Create(client, keypairs.CreateOptsExt{
			CreateOptsBuilder: opts,
			KeyName:           keyPairName,
		}).Extract()
	}
	servers.WaitForStatus(client, testingInstance.ID, "ACTIVE", 300)

	pager = servers.List(client, servers.ListOpts{})
	page, _ = pager.AllPages()
	serverList, _ = servers.ExtractServers(page)
	fmt.Println(serverList)

	// step-13
	var privateIP string
	for t, addrs := range testingInstance.Addresses {
		if t != "private" || len(privateIP) != 0 {
			continue
		}
		addrs, ok := addrs.([]interface{})
		if !ok {
			continue
		}
		for _, addr := range addrs {
			a, ok := addr.(map[string]interface{})
			if !ok || a["version"].(float64) != 4 {
				continue
			}
			ip, ok := a["addr"].(string)
			if ok && len(ip) != 0 {
				privateIP = ip
				fmt.Println("Private IP found: " + privateIP)
				break
			}
		}
	}

	// step-14
	var publicIP string
	for t, addrs := range testingInstance.Addresses {
		if t != "public" || len(publicIP) != 0 {
			continue
		}
		addrs, ok := addrs.([]interface{})
		if !ok {
			continue
		}
		for _, addr := range addrs {
			a, ok := addr.(map[string]interface{})
			if !ok || a["version"].(float64) != 4 {
				continue
			}
			ip, ok := a["addr"].(string)
			if ok && len(ip) != 0 {
				publicIP = ip
				fmt.Println("Public IP found: " + publicIP)
				break
			}
		}
	}

	// step-15
	fmt.Println("Checking for unused Floating IP...")
	var unusedFloatingIP string
	pager = floatingip.List(client)
	page, _ = pager.AllPages()
	floatingIPList, _ := floatingip.ExtractFloatingIPs(page)
	for _, ip := range floatingIPList {
		if ip.InstanceID == "" {
			unusedFloatingIP = ip.IP
			break
		}
	}

	networkClient, _ := openstack.NewNetworkV2(provider, gophercloud.EndpointOpts{
		Region: regionName,
	})

	pager = networks.List(networkClient, networks.ListOpts{})
	page, _ = pager.AllPages()
	poolList, _ := external.ExtractList(page)
	for _, pool := range poolList {
		if len(unusedFloatingIP) != 0 || !pool.External {
			continue
		}
		fmt.Println("Allocating new Floating IP from pool: " + pool.Name)
		f, _ := floatingip.Create(client, floatingip.CreateOpts{Pool: pool.Name}).Extract()
		unusedFloatingIP = f.IP
	}

	// step-16
	if len(publicIP) != 0 {
		fmt.Println("Instance " + testingInstance.Name + " already has a public ip. Skipping attachment.")
	} else {
		floatingip.Associate(client, testingInstance.ID, unusedFloatingIP)
	}

	// step-17
	var actualIPAddress string
	if len(publicIP) != 0 {
		actualIPAddress = publicIP
	} else if len(unusedFloatingIP) != 0 {
		actualIPAddress = unusedFloatingIP
	} else {
		actualIPAddress = privateIP
	}

	fmt.Println("The Fractals app will be deployed to http://" + actualIPAddress)
}
Exemplo n.º 10
0
func (s *StepRunSourceServer) Run(state multistep.StateBag) multistep.StepAction {
	config := state.Get("config").(Config)
	flavor := state.Get("flavor_id").(string)
	keyName := state.Get("keyPair").(string)
	ui := state.Get("ui").(packer.Ui)

	// We need the v2 compute client
	computeClient, err := config.computeV2Client()
	if err != nil {
		err = fmt.Errorf("Error initializing compute client: %s", err)
		state.Put("error", err)
		return multistep.ActionHalt
	}

	networks := make([]servers.Network, len(s.Networks))
	for i, networkUuid := range s.Networks {
		networks[i].UUID = networkUuid
	}

	userData := []byte(s.UserData)
	if s.UserDataFile != "" {
		userData, err = ioutil.ReadFile(s.UserDataFile)
		if err != nil {
			err = fmt.Errorf("Error reading user data file: %s", err)
			state.Put("error", err)
			return multistep.ActionHalt
		}
	}

	ui.Say("Launching server...")
	s.server, err = servers.Create(computeClient, keypairs.CreateOptsExt{
		CreateOptsBuilder: servers.CreateOpts{
			Name:             s.Name,
			ImageRef:         s.SourceImage,
			FlavorRef:        flavor,
			SecurityGroups:   s.SecurityGroups,
			Networks:         networks,
			AvailabilityZone: s.AvailabilityZone,
			UserData:         userData,
		},

		KeyName: keyName,
	}).Extract()
	if err != nil {
		err := fmt.Errorf("Error launching source server: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	ui.Message(fmt.Sprintf("Server ID: %s", s.server.ID))
	log.Printf("server id: %s", s.server.ID)

	ui.Say("Waiting for server to become ready...")
	stateChange := StateChangeConf{
		Pending:   []string{"BUILD"},
		Target:    []string{"ACTIVE"},
		Refresh:   ServerStateRefreshFunc(computeClient, s.server),
		StepState: state,
	}
	latestServer, err := WaitForState(&stateChange)
	if err != nil {
		err := fmt.Errorf("Error waiting for server (%s) to become ready: %s", s.server.ID, err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	s.server = latestServer.(*servers.Server)
	state.Put("server", s.server)

	return multistep.ActionContinue
}
Exemplo n.º 11
0
// Create requests a server to be provisioned to the user in the current tenant.
func Create(client *gophercloud.ServiceClient, opts os.CreateOptsBuilder) os.CreateResult {
	return os.Create(client, opts)
}
func resourceComputeInstanceV2Create(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	computeClient, err := config.computeV2Client(d.Get("region").(string))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack compute client: %s", err)
	}

	var createOpts servers.CreateOptsBuilder

	imageId, err := getImageID(computeClient, d)
	if err != nil {
		return err
	}

	flavorId, err := getFlavorID(computeClient, d)
	if err != nil {
		return err
	}

	networkDetails, err := resourceInstanceNetworks(computeClient, d)
	if err != nil {
		return err
	}

	networks := make([]servers.Network, len(networkDetails))
	for i, net := range networkDetails {
		networks[i] = servers.Network{
			UUID:    net["uuid"].(string),
			Port:    net["port"].(string),
			FixedIP: net["fixed_ip_v4"].(string),
		}
	}

	createOpts = &servers.CreateOpts{
		Name:             d.Get("name").(string),
		ImageRef:         imageId,
		FlavorRef:        flavorId,
		SecurityGroups:   resourceInstanceSecGroupsV2(d),
		AvailabilityZone: d.Get("availability_zone").(string),
		Networks:         networks,
		Metadata:         resourceInstanceMetadataV2(d),
		ConfigDrive:      d.Get("config_drive").(bool),
		AdminPass:        d.Get("admin_pass").(string),
		UserData:         []byte(d.Get("user_data").(string)),
	}

	if keyName, ok := d.Get("key_pair").(string); ok && keyName != "" {
		createOpts = &keypairs.CreateOptsExt{
			createOpts,
			keyName,
		}
	}

	if blockDeviceRaw, ok := d.Get("block_device").(map[string]interface{}); ok && blockDeviceRaw != nil {
		blockDevice := resourceInstanceBlockDeviceV2(d, blockDeviceRaw)
		createOpts = &bootfromvolume.CreateOptsExt{
			createOpts,
			blockDevice,
		}
	}

	schedulerHintsRaw := d.Get("scheduler_hints").(*schema.Set).List()
	if len(schedulerHintsRaw) > 0 {
		log.Printf("[DEBUG] schedulerhints: %+v", schedulerHintsRaw)
		schedulerHints := resourceInstanceSchedulerHintsV2(d, schedulerHintsRaw[0].(map[string]interface{}))
		createOpts = &schedulerhints.CreateOptsExt{
			createOpts,
			schedulerHints,
		}
	}

	log.Printf("[DEBUG] Create Options: %#v", createOpts)
	server, err := servers.Create(computeClient, createOpts).Extract()
	if err != nil {
		return fmt.Errorf("Error creating OpenStack server: %s", err)
	}
	log.Printf("[INFO] Instance ID: %s", server.ID)

	// Store the ID now
	d.SetId(server.ID)

	// Wait for the instance to become running so we can get some attributes
	// that aren't available until later.
	log.Printf(
		"[DEBUG] Waiting for instance (%s) to become running",
		server.ID)

	stateConf := &resource.StateChangeConf{
		Pending:    []string{"BUILD"},
		Target:     "ACTIVE",
		Refresh:    ServerV2StateRefreshFunc(computeClient, server.ID),
		Timeout:    10 * time.Minute,
		Delay:      10 * time.Second,
		MinTimeout: 3 * time.Second,
	}

	_, err = stateConf.WaitForState()
	if err != nil {
		return fmt.Errorf(
			"Error waiting for instance (%s) to become ready: %s",
			server.ID, err)
	}
	floatingIP := d.Get("floating_ip").(string)
	if floatingIP != "" {
		if err := floatingip.Associate(computeClient, server.ID, floatingIP).ExtractErr(); err != nil {
			return fmt.Errorf("Error associating floating IP: %s", err)
		}
	}

	// were volume attachments specified?
	if v := d.Get("volume"); v != nil {
		vols := v.(*schema.Set).List()
		if len(vols) > 0 {
			if blockClient, err := config.blockStorageV1Client(d.Get("region").(string)); err != nil {
				return fmt.Errorf("Error creating OpenStack block storage client: %s", err)
			} else {
				if err := attachVolumesToInstance(computeClient, blockClient, d.Id(), vols); err != nil {
					return err
				}
			}
		}
	}

	return resourceComputeInstanceV2Read(d, meta)
}