├── .bintray.json ├── .editorconfig ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── main.go └── softlayer ├── config.go ├── provider.go ├── provider_test.go ├── resource_softlayer_ssh_key.go ├── resource_softlayer_ssh_key_test.go ├── resource_softlayer_virtualserver.go └── resource_softlayer_virtualserver_test.go /.bintray.json: -------------------------------------------------------------------------------- 1 | { 2 | "package": { 3 | "name": "terraform-provider-softlayer", 4 | "repo": "terraform-provider-softlayer", 5 | "subject": "finn-no", 6 | "desc": "A Terraform provider for SoftLayer", 7 | "website_url": "https://github.com/finn-no/terraform-provider-softlayer", 8 | "issue_tracker_url": "https://github.com/finn-no/terraform-provider-softlayer/issues", 9 | "vcs_url": "https://github.com/finn-no/terraform-provider-softlayer.git", 10 | "licenses": ["Apache-2.0"], 11 | "labels": ["terraform", "softlayer", "cloud", "infrastructure", "deployment"], 12 | "public_download_numbers": true, 13 | "public_stats": true 14 | }, 15 | 16 | "version": { 17 | "name": "0.2", 18 | "desc": "This is the 0.2 release.", 19 | "released": "2015-11-12", 20 | "vcs_tag": "0.2", 21 | "gpgSign": false 22 | }, 23 | 24 | "files": [{ 25 | "includePattern": "\.\/(terraform-provider-softlayer_.*)", 26 | "uploadPattern": "$1" 27 | }], 28 | "publish": true 29 | } 30 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [Makefile] 2 | indent_style = tab 3 | indent_size = 4 4 | end_of_line = lf 5 | 6 | [*.go] 7 | indent_style = tab 8 | indent_size = 4 9 | end_of_line = lf 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.5 5 | 6 | install: 7 | - go get github.com/mitchellh/gox 8 | - go get 9 | - gox 10 | - find . 11 | - go test ./... 12 | 13 | deploy: 14 | provider: bintray 15 | file: ".bintray.json" 16 | user: "eirslett" 17 | key: 18 | secure: "EFpQJHmwMt5xM0F2s2egetQMI90Mmg2YU5ZIcr6PufkptUQ+ifD1GmgAqySnRirspUpLeqD2nGgYgBKF8ePlYfJ4a9vgHnbZ1oOom0G0ey2LUInBwrRb/twmQnK5a2nfcAEcGB0++Qoq0BK7yJc1rs07M1YvstsXU0ymOJ+4ZY4XCRB82Vv+pfJqdBRlYqpYyCbNV2EVnUcDvRtpJxGypdvtdNpjvVHU6uyAFyXAzwl5hggLtnmTYNQWefvXKSoInUl0uqCH3JCCdEGWVTuCKqCI8dvswF5kL4W6OpMXhY0dAWkOpAiADp79VtPjPOQSSPd9BoqKDwW9KvwLOrA3LUw7iNuVgcQNvlfsf59J17Df+R9kNIUh0p9wXCkvY99AGy+uvjVonwybo3K6GOGG8v7mcj/0CrITBrGRYcUJCbwmxlBrjYpIg3jV6Vmjtt+FlRbAuh2pff3krCPR2NrH/kt8UA/MhbSAiVNClaBTmbu6LrCmyZ+XDlULahJK41j3DG6TNRG0L7VxThfEY13H6Xnc+2fZ37PzRHzdof3h5eK9iIC7jJtcSR1ml3cPgtLmO9ixDkjEaVorjH9iRbLn5SHcVKwmsL6MZI4uS9bcnO8VAb2PSS0rfXGE3DURRAD3xf9SEdyZJKtKnZ5h6DRtWi8jccVR4Z71DCCsP/K6xII=" 19 | on: 20 | tags: true 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Terraform provider for SoftLayer 2 | 3 | This is a terraform provider that lets you provision 4 | servers on SoftLayer via [Terraform](https://terraform.io/). 5 | 6 | Build status: [![Build Status](https://travis-ci.org/finn-no/terraform-provider-softlayer.svg?branch=master)](https://travis-ci.org/finn-no/terraform-provider-softlayer) 7 | 8 | 9 | ## Installing 10 | 11 | Binaries are published on Bintray: [ ![Download](https://api.bintray.com/packages/finn-no/terraform-provider-softlayer/terraform-provider-softlayer/images/download.svg) ](https://bintray.com/finn-no/terraform-provider-softlayer/terraform-provider-softlayer/_latestVersion) 12 | 13 | [Copied from the Terraform documentation](https://www.terraform.io/docs/plugins/basics.html): 14 | > To install a plugin, put the binary somewhere on your filesystem, then configure Terraform to be able to find it. The configuration where plugins are defined is ~/.terraformrc for Unix-like systems and %APPDATA%/terraform.rc for Windows. 15 | 16 | The binary should be renamed to terraform-provider-softlayer 17 | 18 | You should update your .terraformrc and refer to the binary: 19 | 20 | ```hcl 21 | providers { 22 | softlayer = "/path/to/terraform-provider-softlayer" 23 | } 24 | ``` 25 | 26 | ## A note about SSH keys 27 | 28 | SoftLayer provisions SSH keys to new virtual servers **only once during the creation of the virtual server**. You can provision new SSH keys and assign them to the virtual server during the creation process, assign existing SSH keys by ID, or assign a combination of existing and newly provisioned SSH keys. Changing SSH keys assigned to a virtual server is not possible after it has already been created. It will need to be re-created. If you attempt to create a new SSH key using the ```softlayer_ssh_key``` resource type, and that key is already in the SoftLayer system, you will get an error stating that the key already exists. If this happens, use the Id of the existing SSH key as in the example below. 29 | 30 | *To get a list of existing SSH key Id's from SoftLayer, I recommend using the [SoftLayer API Python Client]. Once the client is setup, you can run the following command and get the existing SSH key Id's from the output:* 31 | ``` 32 | [user@example.com ~]# slcli sshkey list 33 | ............ 34 | :........:...........:.................................................:..........................: 35 | : id : label : fingerprint : notes : 36 | :........:...........:.................................................:..........................: 37 | : 123456 : test1-dev : xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx : Test Key 1 : 38 | : 789101 : test2-dev : xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx : Test Key 2 : 39 | :........:...........:.................................................:..........................: 40 | ``` 41 | 42 | [SoftLayer API Python CLient]: http://softlayer-api-python-client.readthedocs.org/en/latest/install/ 43 | ## Using the provider 44 | 45 | Here is an example that will setup the following: 46 | + An SSH key resource. 47 | + A virtual server resource that uses an existing SSH key. 48 | + A virtual server resource using an existing SSH key and a Terraform managed SSH key (created as "test_key_1" in the example below). 49 | 50 | (create this as sl.tf and run terraform commands from this directory): 51 | ```hcl 52 | provider "softlayer" { 53 | username = "" 54 | api_key = "" 55 | } 56 | 57 | # This will create a new SSH key that will show up under the \ 58 | # Devices>Manage>SSH Keys in the SoftLayer console. 59 | resource "softlayer_ssh_key" "test_key_1" { 60 | name = "test_key_1" 61 | public_key = "${file(\"~/.ssh/id_rsa_test_key_1.pub\")}" 62 | # Windows Example: 63 | # public_key = "${file(\"C:\ssh\keys\path\id_rsa_test_key_1.pub\")}" 64 | } 65 | 66 | # Virtual Server created with existing SSH Key already in SoftLayer \ 67 | # inventory and not created using this Terraform template. 68 | resource "softlayer_virtualserver" "myserver1" { 69 | name = "my_server_1" 70 | domain = "example.com" 71 | ssh_keys = ["123456"] 72 | image_type = "os_code" 73 | image = "DEBIAN_7_64" 74 | region = "ams01" 75 | public_network_speed = 10 76 | cpu = 1 77 | ram = 1024 78 | } 79 | 80 | # Virtual Server created with a mix of previously existing and \ 81 | # Terraform created/managed resources. 82 | resource "softlayer_virtualserver" "myserver2" { 83 | name = "my_server_2" 84 | domain = "example.com" 85 | ssh_keys = ["123456", "${softlayer_ssh_key.test_key_1.id}"] 86 | image_type = "template_id" 87 | image = "dacf4db1-69a8-4bc8-bade-f51bd286c4df" 88 | region = "ams01" 89 | public_network_speed = 10 90 | cpu = 1 91 | ram = 1024 92 | } 93 | ``` 94 | 95 | You'll need to provide your SoftLayer username and API key, 96 | so that Terraform can connect. If you don't want to put 97 | credentials in your configuration file, you can leave them 98 | out: 99 | 100 | ``` 101 | provider "softlayer" {} 102 | ``` 103 | 104 | ...and instead set these environment variables: 105 | 106 | - **SOFTLAYER_USERNAME**: Your SoftLayer username 107 | - **SOFTLAYER_API_KEY**: Your API key 108 | 109 | ## Building from source 110 | 111 | 1. [Install Go](https://golang.org/doc/install) on your machine 112 | 2. [Set up Gopath](https://golang.org/doc/code.html) 113 | 3. `git clone` this repository into `$GOPATH/src/github.com/finn-no/terraform-provider-softlayer` 114 | 4. Run `go get` to get dependencies 115 | 5. Run `go install` to build the binary. You will now find the 116 | binary at `$GOPATH/bin/terraform-provider-softlayer`. 117 | 118 | ## Releasing 119 | 120 | 1. Update `.bintray.json` with the new version to be released (e.g. 0.1337), and the release date. 121 | 2. Tag the release: `git tag 0.1337` 122 | 3. Push the tag: `git push --tags` 123 | 4. Travis CI will build and release the binaries. 124 | 125 | ## Running 126 | 0. You must create a new key not already added to softlayer (ssh-keygen). We will assume that is id_rsa. 127 | 1. create the example file sl.tf in your working directory 128 | 2. terraform plan 129 | 3. terraform apply 130 | 4. look up the public ip in the softlayer dashboard 131 | 5. ssh -i ~/.ssh/id_rsa.pub root@ 132 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/finn-no/terraform-provider-softlayer/softlayer" 5 | "github.com/hashicorp/terraform/plugin" 6 | ) 7 | 8 | func main() { 9 | plugin.Serve(&plugin.ServeOpts{ 10 | ProviderFunc: softlayer.Provider, 11 | }) 12 | } 13 | -------------------------------------------------------------------------------- /softlayer/config.go: -------------------------------------------------------------------------------- 1 | package softlayer 2 | 3 | import ( 4 | "log" 5 | 6 | slclient "github.com/maximilien/softlayer-go/client" 7 | softlayer "github.com/maximilien/softlayer-go/softlayer" 8 | ) 9 | 10 | type Config struct { 11 | Username string 12 | ApiKey string 13 | } 14 | 15 | type Client struct { 16 | virtualGuestService softlayer.SoftLayer_Virtual_Guest_Service 17 | sshKeyService softlayer.SoftLayer_Security_Ssh_Key_Service 18 | } 19 | 20 | func (c *Config) Client() (*Client, error) { 21 | slc := slclient.NewSoftLayerClient(c.Username, c.ApiKey) 22 | virtualGuestService, err := slc.GetSoftLayer_Virtual_Guest_Service() 23 | 24 | if err != nil { 25 | return nil, err 26 | } 27 | 28 | sshKeyService, err := slc.GetSoftLayer_Security_Ssh_Key_Service() 29 | 30 | client := &Client { 31 | virtualGuestService: virtualGuestService, 32 | sshKeyService: sshKeyService, 33 | } 34 | 35 | log.Println("[INFO] Created SoftLayer client") 36 | 37 | return client, nil 38 | } 39 | -------------------------------------------------------------------------------- /softlayer/provider.go: -------------------------------------------------------------------------------- 1 | package softlayer 2 | 3 | import ( 4 | "github.com/hashicorp/terraform/helper/schema" 5 | "github.com/hashicorp/terraform/terraform" 6 | ) 7 | 8 | func Provider() terraform.ResourceProvider { 9 | return &schema.Provider{ 10 | Schema: map[string]*schema.Schema{ 11 | "username": &schema.Schema{ 12 | Type: schema.TypeString, 13 | Required: true, 14 | DefaultFunc: schema.EnvDefaultFunc("SOFTLAYER_USERNAME", nil), 15 | Description: "The user name for SoftLayer API operations.", 16 | }, 17 | "api_key": &schema.Schema{ 18 | Type: schema.TypeString, 19 | Required: true, 20 | DefaultFunc: schema.EnvDefaultFunc("SOFTLAYER_API_KEY", nil), 21 | Description: "The API key for SoftLayer API operations.", 22 | }, 23 | }, 24 | 25 | ResourcesMap: map[string]*schema.Resource{ 26 | "softlayer_virtualserver": resourceSoftLayerVirtualserver(), 27 | "softlayer_ssh_key": resourceSoftLayerSSHKey(), 28 | }, 29 | 30 | ConfigureFunc: providerConfigure, 31 | } 32 | } 33 | 34 | func providerConfigure(d *schema.ResourceData) (interface{}, error) { 35 | config := Config{ 36 | Username: d.Get("username").(string), 37 | ApiKey: d.Get("api_key").(string), 38 | 39 | } 40 | 41 | return config.Client() 42 | } 43 | -------------------------------------------------------------------------------- /softlayer/provider_test.go: -------------------------------------------------------------------------------- 1 | package softlayer 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | 7 | "github.com/hashicorp/terraform/helper/schema" 8 | "github.com/hashicorp/terraform/terraform" 9 | ) 10 | 11 | var testAccProviders map[string]terraform.ResourceProvider 12 | var testAccProvider *schema.Provider 13 | 14 | func init() { 15 | testAccProvider = Provider().(*schema.Provider) 16 | testAccProviders = map[string]terraform.ResourceProvider{ 17 | "softlayer": testAccProvider, 18 | } 19 | } 20 | 21 | func TestProvider(t *testing.T) { 22 | if err := Provider().(*schema.Provider).InternalValidate(); err != nil { 23 | t.Fatalf("err: %s", err) 24 | } 25 | } 26 | 27 | func TestProvider_impl(t *testing.T) { 28 | var _ terraform.ResourceProvider = Provider() 29 | } 30 | 31 | func testAccPreCheck(t *testing.T) { 32 | if v := os.Getenv("SOFTLAYER_USERNAME"); v == "" { 33 | t.Fatal("SOFTLAYER_USERNAME must be set for acceptance tests") 34 | } 35 | if v := os.Getenv("SOFTLAYER_API_KEY"); v == "" { 36 | t.Fatal("SOFTLAYER_API_KEY must be set for acceptance tests") 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /softlayer/resource_softlayer_ssh_key.go: -------------------------------------------------------------------------------- 1 | package softlayer 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "strconv" 7 | "strings" 8 | 9 | "github.com/hashicorp/terraform/helper/schema" 10 | datatypes "github.com/maximilien/softlayer-go/data_types" 11 | ) 12 | 13 | func resourceSoftLayerSSHKey() *schema.Resource { 14 | return &schema.Resource{ 15 | Create: resourceSoftLayerSSHKeyCreate, 16 | Read: resourceSoftLayerSSHKeyRead, 17 | Update: resourceSoftLayerSSHKeyUpdate, 18 | Delete: resourceSoftLayerSSHKeyDelete, 19 | 20 | Schema: map[string]*schema.Schema{ 21 | "id": &schema.Schema{ 22 | Type: schema.TypeInt, 23 | Computed: true, 24 | }, 25 | 26 | "name": &schema.Schema{ 27 | Type: schema.TypeString, 28 | Required: true, 29 | }, 30 | 31 | "public_key": &schema.Schema{ 32 | Type: schema.TypeString, 33 | Required: true, 34 | ForceNew: true, 35 | }, 36 | 37 | "fingerprint": &schema.Schema{ 38 | Type: schema.TypeString, 39 | Computed: true, 40 | }, 41 | }, 42 | } 43 | } 44 | 45 | func resourceSoftLayerSSHKeyCreate(d *schema.ResourceData, meta interface{}) error { 46 | client := meta.(*Client).sshKeyService 47 | 48 | // Build up our creation options 49 | opts := datatypes.SoftLayer_Security_Ssh_Key{ 50 | Label: d.Get("name").(string), 51 | Key: d.Get("public_key").(string), 52 | } 53 | 54 | res, err := client.CreateObject(opts) 55 | if err != nil { 56 | return fmt.Errorf("Error creating SSH Key: %s", err) 57 | } 58 | 59 | d.SetId(strconv.Itoa(res.Id)) 60 | log.Printf("[INFO] SSH Key: %d", res.Id) 61 | 62 | return resourceSoftLayerSSHKeyRead(d, meta) 63 | } 64 | 65 | func resourceSoftLayerSSHKeyRead(d *schema.ResourceData, meta interface{}) error { 66 | client := meta.(*Client).sshKeyService 67 | 68 | keyId, _ := strconv.Atoi(d.Id()) 69 | 70 | key, err := client.GetObject(keyId) 71 | if err != nil { 72 | // If the key is somehow already destroyed, mark as 73 | // succesfully gone 74 | if strings.Contains(err.Error(), "404 Not Found") { 75 | d.SetId("") 76 | return nil 77 | } 78 | 79 | return fmt.Errorf("Error retrieving SSH key: %s", err) 80 | } 81 | 82 | d.Set("id", key.Id) 83 | d.Set("name", key.Label) 84 | d.Set("public_key", strings.TrimSpace(key.Key)) 85 | d.Set("fingerprint", key.Fingerprint) 86 | 87 | return nil 88 | } 89 | 90 | func resourceSoftLayerSSHKeyUpdate(d *schema.ResourceData, meta interface{}) error { 91 | client := meta.(*Client).sshKeyService 92 | 93 | keyId, _ := strconv.Atoi(d.Id()) 94 | 95 | key, err := client.GetObject(keyId) 96 | if err != nil { 97 | return fmt.Errorf("Error retrieving SSH key: %s", err) 98 | } 99 | 100 | key.Label = d.Get("name").(string) 101 | 102 | _, err = client.EditObject(keyId, key) 103 | if err != nil { 104 | return fmt.Errorf("Error editing SSH key: %s", err) 105 | } 106 | return nil 107 | } 108 | 109 | func resourceSoftLayerSSHKeyDelete(d *schema.ResourceData, meta interface{}) error { 110 | client := meta.(*Client).sshKeyService 111 | 112 | id, err := strconv.Atoi(d.Id()) 113 | if err != nil { 114 | return fmt.Errorf("Error deleting SSH Key: %s", err) 115 | } 116 | 117 | log.Printf("[INFO] Deleting SSH key: %d", id) 118 | _, err = client.DeleteObject(id) 119 | if err != nil { 120 | return fmt.Errorf("Error deleting SSH key: %s", err) 121 | } 122 | 123 | d.SetId("") 124 | return nil 125 | } 126 | -------------------------------------------------------------------------------- /softlayer/resource_softlayer_ssh_key_test.go: -------------------------------------------------------------------------------- 1 | package softlayer 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | "strings" 7 | "testing" 8 | 9 | "github.com/hashicorp/terraform/helper/resource" 10 | "github.com/hashicorp/terraform/terraform" 11 | datatypes "github.com/maximilien/softlayer-go/data_types" 12 | ) 13 | 14 | func TestAccSoftLayerSSHKey_Basic(t *testing.T) { 15 | var key datatypes.SoftLayer_Security_Ssh_Key 16 | 17 | resource.Test(t, resource.TestCase{ 18 | PreCheck: func() { testAccPreCheck(t) }, 19 | Providers: testAccProviders, 20 | CheckDestroy: testAccCheckSoftLayerSSHKeyDestroy, 21 | Steps: []resource.TestStep{ 22 | resource.TestStep{ 23 | Config: testAccCheckSoftLayerSSHKeyConfig_basic, 24 | Check: resource.ComposeTestCheckFunc( 25 | testAccCheckSoftLayerSSHKeyExists("softlayer_ssh_key.testacc_foobar", &key), 26 | testAccCheckSoftLayerSSHKeyAttributes(&key), 27 | resource.TestCheckResourceAttr( 28 | "softlayer_ssh_key.testacc_foobar", "name", "testacc_foobar"), 29 | resource.TestCheckResourceAttr( 30 | "softlayer_ssh_key.testacc_foobar", "public_key", testAccValidPublicKey), 31 | ), 32 | }, 33 | }, 34 | }) 35 | } 36 | 37 | func testAccCheckSoftLayerSSHKeyDestroy(s *terraform.State) error { 38 | client := testAccProvider.Meta().(*Client).sshKeyService 39 | 40 | for _, rs := range s.RootModule().Resources { 41 | if rs.Type != "softlayer_ssh_key" { 42 | continue 43 | } 44 | 45 | keyId, _ := strconv.Atoi(rs.Primary.ID) 46 | 47 | // Try to find the key 48 | _, err := client.GetObject(keyId) 49 | 50 | if err == nil { 51 | fmt.Errorf("SSH key still exists") 52 | } 53 | } 54 | 55 | return nil 56 | } 57 | 58 | func testAccCheckSoftLayerSSHKeyAttributes(key *datatypes.SoftLayer_Security_Ssh_Key) resource.TestCheckFunc { 59 | return func(s *terraform.State) error { 60 | 61 | if key.Label != "testacc_foobar" { 62 | return fmt.Errorf("Bad name: %s", key.Label) 63 | } 64 | 65 | return nil 66 | } 67 | } 68 | 69 | func testAccCheckSoftLayerSSHKeyExists(n string, key *datatypes.SoftLayer_Security_Ssh_Key) resource.TestCheckFunc { 70 | return func(s *terraform.State) error { 71 | rs, ok := s.RootModule().Resources[n] 72 | 73 | if !ok { 74 | return fmt.Errorf("Not found: %s", n) 75 | } 76 | 77 | if rs.Primary.ID == "" { 78 | return fmt.Errorf("No Record ID is set") 79 | } 80 | 81 | keyId, _ := strconv.Atoi(rs.Primary.ID) 82 | 83 | client := testAccProvider.Meta().(*Client).sshKeyService 84 | foundKey, err := client.GetObject(keyId) 85 | 86 | if err != nil { 87 | return err 88 | } 89 | 90 | if strconv.Itoa(int(foundKey.Id)) != rs.Primary.ID { 91 | return fmt.Errorf("Record not found") 92 | } 93 | 94 | *key = foundKey 95 | 96 | return nil 97 | } 98 | } 99 | 100 | var testAccCheckSoftLayerSSHKeyConfig_basic = fmt.Sprintf(` 101 | resource "softlayer_ssh_key" "testacc_foobar" { 102 | name = "testacc_foobar" 103 | public_key = "%s" 104 | }`, testAccValidPublicKey) 105 | 106 | var testAccValidPublicKey = strings.TrimSpace(` 107 | ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCKVmnMOlHKcZK8tpt3MP1lqOLAcqcJzhsvJcjscgVERRN7/9484SOBJ3HSKxxNG5JN8owAjy5f9yYwcUg+JaUVuytn5Pv3aeYROHGGg+5G346xaq3DAwX6Y5ykr2fvjObgncQBnuU5KHWCECO/4h8uWuwh/kfniXPVjFToc+gnkqA+3RKpAecZhFXwfalQ9mMuYGFxn+fwn8cYEApsJbsEmb0iJwPiZ5hjFC8wREuiTlhPHDgkBLOiycd20op2nXzDbHfCHInquEe/gYxEitALONxm0swBOwJZwlTDOB7C6y2dzlrtxr1L59m7pCkWI4EtTRLvleehBoj3u7jB4usR 108 | `) 109 | -------------------------------------------------------------------------------- /softlayer/resource_softlayer_virtualserver.go: -------------------------------------------------------------------------------- 1 | package softlayer 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "log" 7 | "strconv" 8 | "time" 9 | 10 | "github.com/hashicorp/terraform/helper/resource" 11 | "github.com/hashicorp/terraform/helper/schema" 12 | datatypes "github.com/maximilien/softlayer-go/data_types" 13 | ) 14 | 15 | func resourceSoftLayerVirtualserver() *schema.Resource { 16 | return &schema.Resource{ 17 | Create: resourceSoftLayerVirtualserverCreate, 18 | Read: resourceSoftLayerVirtualserverRead, 19 | Update: resourceSoftLayerVirtualserverUpdate, 20 | Delete: resourceSoftLayerVirtualserverDelete, 21 | Schema: map[string]*schema.Schema{ 22 | "name": &schema.Schema{ 23 | Type: schema.TypeString, 24 | Required: true, 25 | }, 26 | 27 | "domain": &schema.Schema{ 28 | Type: schema.TypeString, 29 | Required: true, 30 | }, 31 | 32 | "image": &schema.Schema{ 33 | Type: schema.TypeString, 34 | Required: true, 35 | ForceNew: true, 36 | }, 37 | 38 | "image_type": &schema.Schema{ 39 | Type: schema.TypeString, 40 | Optional: true, 41 | ForceNew: true, 42 | Default: "os_code", 43 | ValidateFunc: validateImageType, 44 | }, 45 | 46 | "region": &schema.Schema{ 47 | Type: schema.TypeString, 48 | Required: true, 49 | ForceNew: true, 50 | }, 51 | 52 | "cpu": &schema.Schema{ 53 | Type: schema.TypeInt, 54 | Required: true, 55 | }, 56 | 57 | "ram": &schema.Schema{ 58 | Type: schema.TypeInt, 59 | Required: true, 60 | }, 61 | 62 | "disks": &schema.Schema{ 63 | Type: schema.TypeList, 64 | Optional: true, 65 | Elem: &schema.Schema{Type: schema.TypeInt}, 66 | }, 67 | 68 | "public_network_speed": &schema.Schema{ 69 | Type: schema.TypeInt, 70 | Optional: true, 71 | Default: 1000, 72 | }, 73 | 74 | "ipv4_address": &schema.Schema{ 75 | Type: schema.TypeString, 76 | Computed: true, 77 | }, 78 | 79 | "ipv4_address_private": &schema.Schema{ 80 | Type: schema.TypeString, 81 | Computed: true, 82 | }, 83 | 84 | "ssh_keys": &schema.Schema{ 85 | Type: schema.TypeList, 86 | Optional: true, 87 | Elem: &schema.Schema{Type: schema.TypeInt}, 88 | }, 89 | 90 | "user_data": &schema.Schema{ 91 | Type: schema.TypeString, 92 | Optional: true, 93 | }, 94 | }, 95 | } 96 | } 97 | 98 | // this fellow validates image_type 99 | func validateImageType(value interface{}, key string) ([]string, []error) { 100 | // image_type can be only either 'os_code' or 'template_id' 101 | if value != "os_code" && value != "template_id" { 102 | return nil, []error{ 103 | errors.New(fmt.Sprintf("%s must be either 'os_code' or 'template_id'", key)), 104 | } 105 | } 106 | return nil, nil 107 | } 108 | 109 | func getNameForBlockDevice(i int) string { 110 | // skip 1, which is reserved for the swap disk. 111 | // so we get 0, 2, 3, 4, 5 ... 112 | if i == 0 { 113 | return "0" 114 | } else { 115 | return strconv.Itoa(i + 1) 116 | } 117 | } 118 | 119 | func getBlockDevices(d *schema.ResourceData) []datatypes.BlockDevice { 120 | numBlocks := d.Get("disks.#").(int) 121 | if numBlocks == 0 { 122 | return nil 123 | } else { 124 | blocks := make([]datatypes.BlockDevice, 0, numBlocks) 125 | for i := 0; i < numBlocks; i++ { 126 | blockRef := fmt.Sprintf("disks.%d", i) 127 | name := getNameForBlockDevice(i) 128 | capacity := d.Get(blockRef).(int) 129 | block := datatypes.BlockDevice{ 130 | Device: name, 131 | DiskImage: datatypes.DiskImage{ 132 | Capacity: capacity, 133 | }, 134 | } 135 | blocks = append(blocks, block) 136 | } 137 | return blocks 138 | } 139 | } 140 | 141 | func resourceSoftLayerVirtualserverCreate(d *schema.ResourceData, meta interface{}) error { 142 | client := meta.(*Client).virtualGuestService 143 | if client == nil { 144 | return fmt.Errorf("The client was nil.") 145 | } 146 | 147 | dc := datatypes.Datacenter{ 148 | Name: d.Get("region").(string), 149 | } 150 | 151 | networkComponent := datatypes.NetworkComponents{ 152 | MaxSpeed: d.Get("public_network_speed").(int), 153 | } 154 | 155 | // Options to be passed to Softlayer API 156 | opts := datatypes.SoftLayer_Virtual_Guest_Template{ 157 | Hostname: d.Get("name").(string), 158 | Domain: d.Get("domain").(string), 159 | HourlyBillingFlag: true, 160 | Datacenter: dc, 161 | StartCpus: d.Get("cpu").(int), 162 | MaxMemory: d.Get("ram").(int), 163 | NetworkComponents: []datatypes.NetworkComponents{networkComponent}, 164 | BlockDevices: getBlockDevices(d), 165 | } 166 | 167 | // get image type before doing anything 168 | image_type := d.Get("image_type").(string) 169 | 170 | // get the image ID 171 | image := d.Get("image").(string) 172 | 173 | // 'image' value is interpreted depending on the 174 | // value set on 'image_type' 175 | if image_type == "template_id" { 176 | // Set ID of the base image template to be used (if any) 177 | base_image := datatypes.BlockDeviceTemplateGroup{image} 178 | opts.BlockDeviceTemplateGroup = &base_image 179 | } else { 180 | // Use a stock OS instead for this resource 181 | opts.OperatingSystemReferenceCode = image 182 | } 183 | 184 | userData := d.Get("user_data").(string) 185 | if userData != "" { 186 | opts.UserData = []datatypes.UserData{ 187 | datatypes.UserData{ 188 | Value: userData, 189 | }, 190 | } 191 | } 192 | 193 | // Get configured ssh_keys 194 | ssh_keys := d.Get("ssh_keys.#").(int) 195 | if ssh_keys > 0 { 196 | opts.SshKeys = make([]datatypes.SshKey, 0, ssh_keys) 197 | for i := 0; i < ssh_keys; i++ { 198 | key := fmt.Sprintf("ssh_keys.%d", i) 199 | id := d.Get(key).(int) 200 | sshKey := datatypes.SshKey{ 201 | Id: id, 202 | } 203 | opts.SshKeys = append(opts.SshKeys, sshKey) 204 | } 205 | } 206 | 207 | log.Printf("[INFO] Creating virtual machine") 208 | 209 | guest, err := client.CreateObject(opts) 210 | 211 | if err != nil { 212 | return fmt.Errorf("Error creating virtual server: %s", err) 213 | } 214 | 215 | d.SetId(fmt.Sprintf("%d", guest.Id)) 216 | 217 | log.Printf("[INFO] Virtual Machine ID: %s", d.Id()) 218 | 219 | // wait for machine availability 220 | _, err = WaitForNoActiveTransactions(d, meta) 221 | 222 | if err != nil { 223 | return fmt.Errorf( 224 | "Error waiting for virtual machine (%s) to become ready: %s", d.Id(), err) 225 | } 226 | 227 | _, err = WaitForPublicIpAvailable(d, meta) 228 | if err != nil { 229 | return fmt.Errorf( 230 | "Error waiting for virtual machine (%s) to become ready: %s", d.Id(), err) 231 | } 232 | 233 | return resourceSoftLayerVirtualserverRead(d, meta) 234 | } 235 | 236 | func resourceSoftLayerVirtualserverRead(d *schema.ResourceData, meta interface{}) error { 237 | client := meta.(*Client).virtualGuestService 238 | id, err := strconv.Atoi(d.Id()) 239 | if err != nil { 240 | return fmt.Errorf("Not a valid ID, must be an integer: %s", err) 241 | } 242 | result, err := client.GetObject(id) 243 | if err != nil { 244 | return fmt.Errorf("Error retrieving virtual server: %s", err) 245 | } 246 | 247 | d.Set("name", result.Hostname) 248 | d.Set("domain", result.Domain) 249 | if result.Datacenter != nil { 250 | d.Set("region", result.Datacenter.Name) 251 | } 252 | d.Set("public_network_speed", result.NetworkComponents[0].MaxSpeed) 253 | d.Set("cpu", result.StartCpus) 254 | d.Set("ram", result.MaxMemory) 255 | d.Set("has_public_ip", result.PrimaryIpAddress != "") 256 | d.Set("ipv4_address", result.PrimaryIpAddress) 257 | d.Set("ipv4_address_private", result.PrimaryBackendIpAddress) 258 | 259 | connIpAddress := "" 260 | if result.PrimaryIpAddress != "" { 261 | connIpAddress = result.PrimaryIpAddress 262 | } else { 263 | connIpAddress = result.PrimaryBackendIpAddress 264 | } 265 | 266 | log.Printf("[INFO] Setting ConnInfo IP: %s", connIpAddress) 267 | d.SetConnInfo(map[string]string{ 268 | "type": "ssh", 269 | "host": connIpAddress, 270 | }) 271 | 272 | return nil 273 | } 274 | 275 | func resourceSoftLayerVirtualserverUpdate(d *schema.ResourceData, meta interface{}) error { 276 | client := meta.(*Client).virtualGuestService 277 | id, err := strconv.Atoi(d.Id()) 278 | if err != nil { 279 | return fmt.Errorf("Not a valid ID, must be an integer: %s", err) 280 | } 281 | result, err := client.GetObject(id) 282 | if err != nil { 283 | return fmt.Errorf("Error retrieving virtual server: %s", err) 284 | } 285 | 286 | result.Hostname = d.Get("name").(string) 287 | result.Domain = d.Get("domain").(string) 288 | result.StartCpus = d.Get("cpu").(int) 289 | result.MaxMemory = d.Get("ram").(int) 290 | result.NetworkComponents[0].MaxSpeed = d.Get("public_network_speed").(int) 291 | 292 | userData := d.Get("user_data").(string) 293 | if userData != "" { 294 | result.UserData = []datatypes.UserData{ 295 | datatypes.UserData{ 296 | Value: userData, 297 | }, 298 | } 299 | } 300 | 301 | _, err = client.EditObject(id, result) 302 | 303 | if err != nil { 304 | return fmt.Errorf("Couldn't update virtual server: %s", err) 305 | } 306 | 307 | return nil 308 | } 309 | 310 | func resourceSoftLayerVirtualserverDelete(d *schema.ResourceData, meta interface{}) error { 311 | client := meta.(*Client).virtualGuestService 312 | id, err := strconv.Atoi(d.Id()) 313 | if err != nil { 314 | return fmt.Errorf("Not a valid ID, must be an integer: %s", err) 315 | } 316 | 317 | _, err = WaitForNoActiveTransactions(d, meta) 318 | 319 | if err != nil { 320 | return fmt.Errorf("Error deleting virtual server, couldn't wait for zero active transactions: %s", err) 321 | } 322 | 323 | _, err = client.DeleteObject(id) 324 | 325 | if err != nil { 326 | return fmt.Errorf("Error deleting virtual server: %s", err) 327 | } 328 | 329 | return nil 330 | } 331 | 332 | func WaitForPublicIpAvailable(d *schema.ResourceData, meta interface{}) (interface{}, error) { 333 | log.Printf("Waiting for server (%s) to get a public IP", d.Id()) 334 | 335 | stateConf := &resource.StateChangeConf{ 336 | Pending: []string{"", "unavailable"}, 337 | Target: "available", 338 | Refresh: func() (interface{}, string, error) { 339 | fmt.Println("Refreshing server state...") 340 | client := meta.(*Client).virtualGuestService 341 | id, err := strconv.Atoi(d.Id()) 342 | if err != nil { 343 | return nil, "", fmt.Errorf("Not a valid ID, must be an integer: %s", err) 344 | } 345 | result, err := client.GetObject(id) 346 | if err != nil { 347 | return nil, "", fmt.Errorf("Error retrieving virtual server: %s", err) 348 | } 349 | if result.PrimaryIpAddress == "" { 350 | return result, "unavailable", nil 351 | } else { 352 | return result, "available", nil 353 | } 354 | }, 355 | Timeout: 30 * time.Minute, 356 | Delay: 10 * time.Second, 357 | MinTimeout: 3 * time.Second, 358 | } 359 | 360 | return stateConf.WaitForState() 361 | } 362 | 363 | func WaitForNoActiveTransactions(d *schema.ResourceData, meta interface{}) (interface{}, error) { 364 | log.Printf("Waiting for server (%s) to have zero active transactions", d.Id()) 365 | id, err := strconv.Atoi(d.Id()) 366 | if err != nil { 367 | return nil, fmt.Errorf("The instance ID %s must be numeric", d.Id()) 368 | } 369 | 370 | stateConf := &resource.StateChangeConf{ 371 | Pending: []string{"", "active"}, 372 | Target: "idle", 373 | Refresh: func() (interface{}, string, error) { 374 | client := meta.(*Client).virtualGuestService 375 | transactions, err := client.GetActiveTransactions(id) 376 | if err != nil { 377 | return nil, "", fmt.Errorf("Couldn't get active transactions: %s", err) 378 | } 379 | if len(transactions) == 0 { 380 | return transactions, "idle", nil 381 | } else { 382 | return transactions, "active", nil 383 | } 384 | }, 385 | Timeout: 10 * time.Minute, 386 | Delay: 10 * time.Second, 387 | MinTimeout: 3 * time.Second, 388 | } 389 | 390 | return stateConf.WaitForState() 391 | } 392 | -------------------------------------------------------------------------------- /softlayer/resource_softlayer_virtualserver_test.go: -------------------------------------------------------------------------------- 1 | package softlayer 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | "strings" 7 | "testing" 8 | 9 | "github.com/hashicorp/terraform/helper/resource" 10 | "github.com/hashicorp/terraform/terraform" 11 | datatypes "github.com/maximilien/softlayer-go/data_types" 12 | ) 13 | 14 | func TestAccSoftLayerVirtualserver_Basic(t *testing.T) { 15 | var server datatypes.SoftLayer_Virtual_Guest 16 | 17 | resource.Test(t, resource.TestCase{ 18 | PreCheck: func() { testAccPreCheck(t) }, 19 | Providers: testAccProviders, 20 | CheckDestroy: testAccCheckSoftLayerVirtualserverDestroy, 21 | Steps: []resource.TestStep{ 22 | resource.TestStep{ 23 | Config: testAccCheckSoftLayerVirtualserverConfig_basic, 24 | Check: resource.ComposeTestCheckFunc( 25 | testAccCheckSoftLayerVirtualserverExists("softlayer_virtualserver.terraform-acceptance-test-1", &server), 26 | resource.TestCheckResourceAttr( 27 | "softlayer_virtualserver.terraform-acceptance-test-1", "name", "terraform-test"), 28 | resource.TestCheckResourceAttr( 29 | "softlayer_virtualserver.terraform-acceptance-test-1", "domain", "bar.example.com"), 30 | resource.TestCheckResourceAttr( 31 | "softlayer_virtualserver.terraform-acceptance-test-1", "region", "ams01"), 32 | resource.TestCheckResourceAttr( 33 | "softlayer_virtualserver.terraform-acceptance-test-1", "public_network_speed", "10"), 34 | resource.TestCheckResourceAttr( 35 | "softlayer_virtualserver.terraform-acceptance-test-1", "cpu", "1"), 36 | resource.TestCheckResourceAttr( 37 | "softlayer_virtualserver.terraform-acceptance-test-1", "ram", "1024"), 38 | resource.TestCheckResourceAttr( 39 | "softlayer_virtualserver.terraform-acceptance-test-1", "disks.0", "25"), 40 | resource.TestCheckResourceAttr( 41 | "softlayer_virtualserver.terraform-acceptance-test-1", "disks.1", "10"), 42 | resource.TestCheckResourceAttr( 43 | "softlayer_virtualserver.terraform-acceptance-test-1", "disks.2", "20"), 44 | resource.TestCheckResourceAttr( 45 | "softlayer_virtualserver.terraform-acceptance-test-1", "user_data", "{\"fox\":[45]}"), 46 | ), 47 | }, 48 | }, 49 | }) 50 | } 51 | 52 | func testAccCheckSoftLayerVirtualserverDestroy(s *terraform.State) error { 53 | client := testAccProvider.Meta().(*Client).virtualGuestService 54 | 55 | for _, rs := range s.RootModule().Resources { 56 | if rs.Type != "softlayer_virtualserver" { 57 | continue 58 | } 59 | 60 | serverId, _ := strconv.Atoi(rs.Primary.ID) 61 | 62 | // Try to find the server 63 | _, err := client.GetObject(serverId) 64 | 65 | // Wait 66 | 67 | if err != nil && !strings.Contains(err.Error(), "404") { 68 | return fmt.Errorf( 69 | "Error waiting for server (%s) to be destroyed: %s", 70 | rs.Primary.ID, err) 71 | } 72 | } 73 | 74 | return nil 75 | } 76 | 77 | func testAccCheckSoftLayerVirtualserverExists(n string, server *datatypes.SoftLayer_Virtual_Guest) resource.TestCheckFunc { 78 | return func(s *terraform.State) error { 79 | rs, ok := s.RootModule().Resources[n] 80 | if !ok { 81 | return fmt.Errorf("Not found: %s", n) 82 | } 83 | 84 | if rs.Primary.ID == "" { 85 | return fmt.Errorf("No virtual server ID is set") 86 | } 87 | 88 | id, err := strconv.Atoi(rs.Primary.ID) 89 | 90 | if err != nil { 91 | return err 92 | } 93 | 94 | client := testAccProvider.Meta().(*Client).virtualGuestService 95 | retrieveServer, err := client.GetObject(id) 96 | 97 | if err != nil { 98 | return err 99 | } 100 | 101 | fmt.Printf("The ID is %d", id) 102 | 103 | if retrieveServer.Id != id { 104 | return fmt.Errorf("Virtual server not found") 105 | } 106 | 107 | *server = retrieveServer 108 | 109 | return nil 110 | } 111 | } 112 | 113 | const testAccCheckSoftLayerVirtualserverConfig_basic = ` 114 | resource "softlayer_virtualserver" "terraform-acceptance-test-1" { 115 | name = "terraform-test" 116 | domain = "bar.example.com" 117 | image = "DEBIAN_7_64" 118 | region = "ams01" 119 | public_network_speed = 10 120 | cpu = 1 121 | ram = 1024 122 | disks = [25, 10, 20] 123 | user_data = "{\"fox\":[45]}" 124 | } 125 | ` 126 | --------------------------------------------------------------------------------