本文整理汇总了Golang中github.com/rackspace/gophercloud/openstack/compute/v2/servers.Create函数的典型用法代码示例。如果您正苦于以下问题:Golang Create函数的具体用法?Golang Create怎么用?Golang Create使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Create函数的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: CreateInstance
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
}
开发者ID:robertjustjones,项目名称:machine,代码行数:27,代码来源:client.go
示例2: CreateInstance
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
}
开发者ID:rhendric,项目名称:machine,代码行数:27,代码来源:client.go
示例3: createServerInGroup
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
}
开发者ID:RomainVabre,项目名称:origin,代码行数:30,代码来源:servergroup_test.go
示例4: createNetworkServer
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
}
开发者ID:RomainVabre,项目名称:origin,代码行数:30,代码来源:tenantnetworks_test.go
示例5: createServer
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
}
开发者ID:chenzhen411,项目名称:kubernetes,代码行数:55,代码来源:servers_test.go
示例6: TestCreateServerWithKeyPair
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)
}
开发者ID:cdosso,项目名称:machine,代码行数:55,代码来源:keypairs_test.go
示例7: findServer
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
}
开发者ID:RomainVabre,项目名称:origin,代码行数:45,代码来源:secgroup_test.go
示例8: resourceComputeInstanceV2Create
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 {
//.........这里部分代码省略.........
开发者ID:MattiasGees,项目名称:terraform,代码行数:101,代码来源:resource_openstack_compute_instance_v2.go
示例9: main
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)
//.........这里部分代码省略.........
开发者ID:Tesora,项目名称:tesora-api-site,代码行数:101,代码来源:getting_started.go
示例10: Run
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
}
开发者ID:rodm,项目名称:packer,代码行数:73,代码来源:step_run_source_server.go
示例11: Create
// 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)
}
开发者ID:hortonworks,项目名称:kubernetes-yarn,代码行数:4,代码来源:delegate.go
示例12: resourceComputeInstanceV2Create
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",
//.........这里部分代码省略.........
开发者ID:semarj,项目名称:terraform,代码行数:101,代码来源:resource_openstack_compute_instance_v2.go
注:本文中的github.com/rackspace/gophercloud/openstack/compute/v2/servers.Create函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论