blob: 3e12d6b3cd43fde38b435828e873e2aa07ac508a [file] [log] [blame]
Jon Perritt5fdb7222014-11-17 14:41:54 -07001// +build acceptance
2
3package v2
4
5import (
6 "crypto/rand"
7 "crypto/rsa"
8 "testing"
9
10 "github.com/rackspace/gophercloud/acceptance/tools"
11 "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs"
12 "github.com/rackspace/gophercloud/openstack/compute/v2/servers"
13 th "github.com/rackspace/gophercloud/testhelper"
14
15 "code.google.com/p/go.crypto/ssh"
16)
17
Jon Perrittd1e861a2014-11-18 08:10:13 -070018const keyName = "gophercloud_test_key_pair"
19
Jon Perritt5fdb7222014-11-17 14:41:54 -070020func TestCreateServerWithKeyPair(t *testing.T) {
21 client, err := newClient()
22 th.AssertNoErr(t, err)
23
24 if testing.Short() {
25 t.Skip("Skipping test that requires server creation in short mode.")
26 }
27
Jon Perritt29611662014-11-17 17:47:33 -070028 privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
Jon Perritt5fdb7222014-11-17 14:41:54 -070029 publicKey := privateKey.PublicKey
30 pub, err := ssh.NewPublicKey(&publicKey)
31 th.AssertNoErr(t, err)
32 pubBytes := ssh.MarshalAuthorizedKey(pub)
33 pk := string(pubBytes)
34
35 kp, err := keypairs.Create(client, keypairs.CreateOpts{
Jon Perrittd1e861a2014-11-18 08:10:13 -070036 Name: keyName,
Jon Perritt5fdb7222014-11-17 14:41:54 -070037 PublicKey: pk,
38 }).Extract()
39 th.AssertNoErr(t, err)
40 t.Logf("Created key pair: %s\n", kp)
41
42 choices, err := ComputeChoicesFromEnv()
43 th.AssertNoErr(t, err)
44
45 name := tools.RandomString("Gophercloud-", 8)
46 t.Logf("Creating server [%s] with key pair.", name)
47
48 serverCreateOpts := servers.CreateOpts{
49 Name: name,
50 FlavorRef: choices.FlavorID,
51 ImageRef: choices.ImageID,
52 }
53
54 server, err := servers.Create(client, keypairs.CreateOptsExt{
55 serverCreateOpts,
Jon Perrittd1e861a2014-11-18 08:10:13 -070056 keyName,
Jon Perritt5fdb7222014-11-17 14:41:54 -070057 }).Extract()
58 th.AssertNoErr(t, err)
59 defer servers.Delete(client, server.ID)
Jon Perrittd1e861a2014-11-18 08:10:13 -070060 if err = waitForStatus(client, server, "ACTIVE"); err != nil {
61 t.Fatalf("Unable to wait for server: %v", err)
62 }
63
64 server, err = servers.Get(client, server.ID).Extract()
Jon Perritt5fdb7222014-11-17 14:41:54 -070065 t.Logf("Created server: %+v\n", server)
Jon Perrittd1e861a2014-11-18 08:10:13 -070066 th.AssertNoErr(t, err)
67 th.AssertEquals(t, server.KeyName, keyName)
Jon Perritt5fdb7222014-11-17 14:41:54 -070068
69 t.Logf("Deleting key pair [%s]...", kp.Name)
Jon Perrittd1e861a2014-11-18 08:10:13 -070070 err = keypairs.Delete(client, keyName).ExtractErr()
Jon Perritt5fdb7222014-11-17 14:41:54 -070071 th.AssertNoErr(t, err)
72
73 t.Logf("Deleting server [%s]...", name)
74}