diff --git a/builtin/bins/provider-profitbricks/main.go b/builtin/bins/provider-profitbricks/main.go new file mode 100644 index 000000000000..b8820809ecd9 --- /dev/null +++ b/builtin/bins/provider-profitbricks/main.go @@ -0,0 +1,12 @@ +package provider_profitbricks + +import ( + "github.com/hashicorp/terraform/builtin/providers/profitbricks" + "github.com/hashicorp/terraform/plugin" +) + +func main() { + plugin.Serve(&plugin.ServeOpts{ + ProviderFunc: profitbricks.Provider, + }) +} diff --git a/builtin/providers/profitbricks/config.go b/builtin/providers/profitbricks/config.go new file mode 100644 index 000000000000..957bc137c93b --- /dev/null +++ b/builtin/providers/profitbricks/config.go @@ -0,0 +1,19 @@ +package profitbricks + +import ( + "github.com/profitbricks/profitbricks-sdk-go" +) + +type Config struct { + Username string + Password string + Retries int +} + +// Client() returns a new client for accessing digital ocean. +func (c *Config) Client() (*Config, error) { + profitbricks.SetAuth(c.Username, c.Password) + profitbricks.SetDepth("5") + + return c, nil +} diff --git a/builtin/providers/profitbricks/provider.go b/builtin/providers/profitbricks/provider.go new file mode 100644 index 000000000000..e53b79521a64 --- /dev/null +++ b/builtin/providers/profitbricks/provider.go @@ -0,0 +1,64 @@ +package profitbricks + +import ( + "fmt" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +// Provider returns a schema.Provider for DigitalOcean. +func Provider() terraform.ResourceProvider { + return &schema.Provider{ + Schema: map[string]*schema.Schema{ + "username": { + Type: schema.TypeString, + Required: true, + DefaultFunc: schema.EnvDefaultFunc("PROFITBRICKS_USERNAME", nil), + Description: "Profitbricks username for API operations.", + }, + "password": { + Type: schema.TypeString, + Required: true, + DefaultFunc: schema.EnvDefaultFunc("PROFITBRICKS_PASSWORD", nil), + Description: "Profitbricks password for API operations.", + }, + "retries": { + Type: schema.TypeInt, + Optional: true, + Default: 50, + }, + }, + + ResourcesMap: map[string]*schema.Resource{ + "profitbricks_datacenter": resourceProfitBricksDatacenter(), + "profitbricks_ipblock": resourceProfitBricksIPBlock(), + "profitbricks_firewall": resourceProfitBricksFirewall(), + "profitbricks_lan": resourceProfitBricksLan(), + "profitbricks_loadbalancer": resourceProfitBricksLoadbalancer(), + "profitbricks_nic": resourceProfitBricksNic(), + "profitbricks_server": resourceProfitBricksServer(), + "profitbricks_volume": resourceProfitBricksVolume(), + }, + + ConfigureFunc: providerConfigure, + } +} + +func providerConfigure(d *schema.ResourceData) (interface{}, error) { + + if _, ok := d.GetOk("username"); !ok { + return nil, fmt.Errorf("ProfitBricks username has not been provided.") + } + + if _, ok := d.GetOk("password"); !ok { + return nil, fmt.Errorf("ProfitBricks password has not been provided.") + } + + config := Config{ + Username: d.Get("username").(string), + Password: d.Get("password").(string), + Retries: d.Get("retries").(int), + } + + return config.Client() +} diff --git a/builtin/providers/profitbricks/provider_test.go b/builtin/providers/profitbricks/provider_test.go new file mode 100644 index 000000000000..93b59387c230 --- /dev/null +++ b/builtin/providers/profitbricks/provider_test.go @@ -0,0 +1,39 @@ +package profitbricks + +import ( + "os" + "testing" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +var testAccProviders map[string]terraform.ResourceProvider +var testAccProvider *schema.Provider + +func init() { + testAccProvider = Provider().(*schema.Provider) + testAccProviders = map[string]terraform.ResourceProvider{ + "profitbricks": testAccProvider, + } +} + +func TestProvider(t *testing.T) { + if err := Provider().(*schema.Provider).InternalValidate(); err != nil { + t.Fatalf("err: %s", err) + } +} + +func TestProvider_impl(t *testing.T) { + var _ terraform.ResourceProvider = Provider() +} + +func testAccPreCheck(t *testing.T) { + if v := os.Getenv("PROFITBRICKS_USERNAME"); v == "" { + t.Fatal("PROFITBRICKS_USERNAME must be set for acceptance tests") + } + + if v := os.Getenv("PROFITBRICKS_PASSWORD"); v == "" { + t.Fatal("PROFITBRICKS_PASSWORD must be set for acceptance tests") + } +} diff --git a/builtin/providers/profitbricks/resource_profitbricks_datacenter.go b/builtin/providers/profitbricks/resource_profitbricks_datacenter.go new file mode 100644 index 000000000000..c5a42ec40ba8 --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_datacenter.go @@ -0,0 +1,184 @@ +package profitbricks + +import ( + "fmt" + "github.com/hashicorp/terraform/helper/schema" + "github.com/profitbricks/profitbricks-sdk-go" + "log" + "runtime" + "strings" + "time" +) + +func resourceProfitBricksDatacenter() *schema.Resource { + return &schema.Resource{ + Create: resourceProfitBricksDatacenterCreate, + Read: resourceProfitBricksDatacenterRead, + Update: resourceProfitBricksDatacenterUpdate, + Delete: resourceProfitBricksDatacenterDelete, + Schema: map[string]*schema.Schema{ + + //Datacenter parameters + "name": { + Type: schema.TypeString, + Required: true, + }, + + "location": { + Type: schema.TypeString, + Required: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + }, + } +} + +func resourceProfitBricksDatacenterCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + datacenter := profitbricks.Datacenter{ + Properties: profitbricks.DatacenterProperties{ + Name: d.Get("name").(string), + Location: d.Get("location").(string), + }, + } + + if attr, ok := d.GetOk("description"); ok { + datacenter.Properties.Description = attr.(string) + } + dc := profitbricks.CreateDatacenter(datacenter) + + if dc.StatusCode > 299 { + return fmt.Errorf( + "Error creating data center (%s) (%s)", d.Id(), dc.Response) + } + d.SetId(dc.Id) + + log.Printf("[INFO] DataCenter Id: %s", d.Id()) + + err := waitTillProvisioned(meta, dc.Headers.Get("Location")) + if err != nil { + return err + } + return resourceProfitBricksDatacenterRead(d, meta) +} + +func resourceProfitBricksDatacenterRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + profitbricks.SetAuth(config.Username, config.Password) + datacenter := profitbricks.GetDatacenter(d.Id()) + if datacenter.StatusCode > 299 { + return fmt.Errorf("Error while fetching a data center ID %s %s", d.Id(), datacenter.Response) + } + + d.Set("name", datacenter.Properties.Name) + d.Set("location", datacenter.Properties.Location) + d.Set("description", datacenter.Properties.Description) + return nil +} + +func resourceProfitBricksDatacenterUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + profitbricks.SetAuth(config.Username, config.Password) + + obj := profitbricks.DatacenterProperties{} + + if d.HasChange("name") { + _, newName := d.GetChange("name") + + obj.Name = newName.(string) + } + + if d.HasChange("description") { + _, newDescription := d.GetChange("description") + obj.Description = newDescription.(string) + } + + resp := profitbricks.PatchDatacenter(d.Id(), obj) + waitTillProvisioned(meta, resp.Headers.Get("Location")) + return resourceProfitBricksDatacenterRead(d, meta) +} + +func resourceProfitBricksDatacenterDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + + profitbricks.SetAuth(config.Username, config.Password) + dcid := d.Id() + resp := profitbricks.DeleteDatacenter(dcid) + + if resp.StatusCode > 299 { + return fmt.Errorf("An error occured while deleting the data center ID %s %s", d.Id(), string(resp.Body)) + } + err := waitTillProvisioned(meta, resp.Headers.Get("Location")) + if err != nil { + return err + } + d.SetId("") + return nil +} + +func waitTillProvisioned(meta interface{}, path string) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + for i := 0; i < config.Retries; i++ { + request := profitbricks.GetRequestStatus(path) + pc, _, _, ok := runtime.Caller(1) + details := runtime.FuncForPC(pc) + if ok && details != nil { + log.Printf("[DEBUG] Called from %s", details.Name()) + } + log.Printf("[DEBUG] Request status: %s", request.Metadata.Status) + log.Printf("[DEBUG] Request status path: %s", path) + + if request.Metadata.Status == "DONE" { + return nil + } + if request.Metadata.Status == "FAILED" { + + return fmt.Errorf("Request failed with following error: %s", request.Metadata.Message) + } + time.Sleep(10 * time.Second) + i++ + } + return fmt.Errorf("Timeout has expired") +} + +func getImageId(dcId string, imageName string, imageType string) string { + if imageName == "" { + return "" + } + dc := profitbricks.GetDatacenter(dcId) + if dc.StatusCode > 299 { + log.Print(fmt.Errorf("Error while fetching a data center ID %s %s", dcId, dc.Response)) + } + + images := profitbricks.ListImages() + if images.StatusCode > 299 { + log.Print(fmt.Errorf("Error while fetching the list of images %s", images.Response)) + } + + if len(images.Items) > 0 { + for _, i := range images.Items { + imgName := "" + if i.Properties.Name != "" { + imgName = i.Properties.Name + } + + if imageType == "SSD" { + imageType = "HDD" + } + if imgName != "" && strings.Contains(strings.ToLower(imgName), strings.ToLower(imageName)) && i.Properties.ImageType == imageType && i.Properties.Location == dc.Properties.Location && i.Properties.Public == true { + return i.Id + } + } + } + return "" +} diff --git a/builtin/providers/profitbricks/resource_profitbricks_datacenter_test.go b/builtin/providers/profitbricks/resource_profitbricks_datacenter_test.go new file mode 100644 index 000000000000..7ed87ed4b9bd --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_datacenter_test.go @@ -0,0 +1,109 @@ +package profitbricks + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/profitbricks/profitbricks-sdk-go" +) + +func TestAccProfitBricksDataCenter_Basic(t *testing.T) { + var datacenter profitbricks.Datacenter + lanName := "datacenter-test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDProfitBricksDatacenterDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckProfitBricksDatacenterConfig_basic, lanName), + Check: resource.ComposeTestCheckFunc( + testAccCheckProfitBricksDatacenterExists("profitbricks_datacenter.foobar", &datacenter), + testAccCheckProfitBricksDatacenterAttributes("profitbricks_datacenter.foobar", lanName), + resource.TestCheckResourceAttr("profitbricks_datacenter.foobar", "name", lanName), + ), + }, + resource.TestStep{ + Config: testAccCheckProfitBricksDatacenterConfig_update, + Check: resource.ComposeTestCheckFunc( + testAccCheckProfitBricksDatacenterExists("profitbricks_datacenter.foobar", &datacenter), + testAccCheckProfitBricksDatacenterAttributes("profitbricks_datacenter.foobar", "updated"), + resource.TestCheckResourceAttr("profitbricks_datacenter.foobar", "name", "updated"), + ), + }, + }, + }) +} + +func testAccCheckDProfitBricksDatacenterDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "profitbricks_datacenter" { + continue + } + + resp := profitbricks.GetDatacenter(rs.Primary.ID) + + if resp.StatusCode < 299 { + return fmt.Errorf("DataCenter still exists %s %s", rs.Primary.ID, resp.Response) + } + } + + return nil +} + +func testAccCheckProfitBricksDatacenterAttributes(n string, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + if rs.Primary.Attributes["name"] != name { + return fmt.Errorf("Bad name: expected %s : found %s ", name, rs.Primary.Attributes["name"]) + } + + return nil + } +} + +func testAccCheckProfitBricksDatacenterExists(n string, datacenter *profitbricks.Datacenter) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + foundDC := profitbricks.GetDatacenter(rs.Primary.ID) + + if foundDC.StatusCode != 200 { + return fmt.Errorf("Error occured while fetching DC: %s", rs.Primary.ID) + } + if foundDC.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + datacenter = &foundDC + + return nil + } +} + +const testAccCheckProfitBricksDatacenterConfig_basic = ` +resource "profitbricks_datacenter" "foobar" { + name = "%s" + location = "us/las" +}` + +const testAccCheckProfitBricksDatacenterConfig_update = ` +resource "profitbricks_datacenter" "foobar" { + name = "updated" + location = "us/las" +}` diff --git a/builtin/providers/profitbricks/resource_profitbricks_firewall.go b/builtin/providers/profitbricks/resource_profitbricks_firewall.go new file mode 100644 index 000000000000..e4fcd24bfcfc --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_firewall.go @@ -0,0 +1,234 @@ +package profitbricks + +import ( + "fmt" + "github.com/hashicorp/terraform/helper/schema" + "github.com/profitbricks/profitbricks-sdk-go" +) + +func resourceProfitBricksFirewall() *schema.Resource { + return &schema.Resource{ + Create: resourceProfitBricksFirewallCreate, + Read: resourceProfitBricksFirewallRead, + Update: resourceProfitBricksFirewallUpdate, + Delete: resourceProfitBricksFirewallDelete, + Schema: map[string]*schema.Schema{ + + "name": { + Type: schema.TypeString, + Optional: true, + }, + + "protocol": { + Type: schema.TypeString, + Required: true, + }, + "source_mac": { + Type: schema.TypeString, + Optional: true, + }, + "source_ip": { + Type: schema.TypeString, + Optional: true, + }, + "target_ip": { + Type: schema.TypeString, + Optional: true, + }, + "port_range_start": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + if v.(int) < 1 && v.(int) > 65534 { + errors = append(errors, fmt.Errorf("Port start range must be between 1 and 65534")) + } + return + }, + }, + + "port_range_end": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + if v.(int) < 1 && v.(int) > 65534 { + errors = append(errors, fmt.Errorf("Port end range must be between 1 and 65534")) + } + return + }, + }, + "icmp_type": { + Type: schema.TypeString, + Optional: true, + }, + "icmp_code": { + Type: schema.TypeString, + Optional: true, + }, + "datacenter_id": { + Type: schema.TypeString, + Required: true, + }, + "server_id": { + Type: schema.TypeString, + Required: true, + }, + "nic_id": { + Type: schema.TypeString, + Required: true, + }, + }, + } +} + +func resourceProfitBricksFirewallCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + fw := profitbricks.FirewallRule{ + Properties: profitbricks.FirewallruleProperties{ + Protocol: d.Get("protocol").(string), + }, + } + + if _, ok := d.GetOk("name"); ok { + fw.Properties.Name = d.Get("name").(string) + } + if _, ok := d.GetOk("source_mac"); ok { + fw.Properties.SourceMac = d.Get("source_mac").(string) + } + if _, ok := d.GetOk("source_ip"); ok { + fw.Properties.SourceIp = d.Get("source_ip").(string) + } + if _, ok := d.GetOk("target_ip"); ok { + fw.Properties.TargetIp = d.Get("target_ip").(string) + } + if _, ok := d.GetOk("port_range_start"); ok { + fw.Properties.PortRangeStart = d.Get("port_range_start").(int) + } + if _, ok := d.GetOk("port_range_end"); ok { + fw.Properties.PortRangeEnd = d.Get("port_range_end").(int) + } + if _, ok := d.GetOk("icmp_type"); ok { + fw.Properties.IcmpType = d.Get("icmp_type").(string) + } + if _, ok := d.GetOk("icmp_code"); ok { + fw.Properties.IcmpCode = d.Get("icmp_code").(string) + } + + fw = profitbricks.CreateFirewallRule(d.Get("datacenter_id").(string), d.Get("server_id").(string), d.Get("nic_id").(string), fw) + + if fw.StatusCode > 299 { + return fmt.Errorf("An error occured while creating a firewall rule: %s", fw.Response) + } + + err := waitTillProvisioned(meta, fw.Headers.Get("Location")) + if err != nil { + return err + } + d.SetId(fw.Id) + + return resourceProfitBricksFirewallRead(d, meta) +} + +func resourceProfitBricksFirewallRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + fw := profitbricks.GetFirewallRule(d.Get("datacenter_id").(string), d.Get("server_id").(string), d.Get("nic_id").(string), d.Id()) + + if fw.StatusCode > 299 { + return fmt.Errorf("An error occured while fetching a firewall rule dcId: %s server_id: %s nic_id: %s ID: %s %s", d.Get("datacenter_id").(string), d.Get("server_id").(string), d.Get("nic_id").(string), d.Id(), fw.Response) + } + + d.Set("protocol", fw.Properties.Protocol) + d.Set("name", fw.Properties.Name) + d.Set("source_mac", fw.Properties.SourceMac) + d.Set("source_ip", fw.Properties.SourceIp) + d.Set("target_ip", fw.Properties.TargetIp) + d.Set("port_range_start", fw.Properties.PortRangeStart) + d.Set("port_range_end", fw.Properties.PortRangeEnd) + d.Set("icmp_type", fw.Properties.IcmpType) + d.Set("icmp_code", fw.Properties.IcmpCode) + d.Set("nic_id", d.Get("nic_id").(string)) + + return nil +} + +func resourceProfitBricksFirewallUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + properties := profitbricks.FirewallruleProperties{} + + if d.HasChange("name") { + _, new := d.GetChange("name") + + properties.Name = new.(string) + } + if d.HasChange("source_mac") { + _, new := d.GetChange("source_mac") + + properties.SourceMac = new.(string) + } + if d.HasChange("source_ip") { + _, new := d.GetChange("source_ip") + + properties.SourceIp = new.(string) + } + if d.HasChange("target_ip") { + _, new := d.GetChange("target_ip") + + properties.TargetIp = new.(string) + } + if d.HasChange("port_range_start") { + _, new := d.GetChange("port_range_start") + + properties.PortRangeStart = new.(int) + } + if d.HasChange("port_range_end") { + _, new := d.GetChange("port_range_end") + + properties.PortRangeEnd = new.(int) + } + if d.HasChange("icmp_type") { + _, new := d.GetChange("icmp_type") + + properties.IcmpType = new.(int) + } + if d.HasChange("icmp_code") { + _, new := d.GetChange("icmp_code") + + properties.IcmpCode = new.(int) + } + + resp := profitbricks.PatchFirewallRule(d.Get("datacenter_id").(string), d.Get("server_id").(string), d.Get("nic_id").(string), d.Id(), properties) + + if resp.StatusCode > 299 { + return fmt.Errorf("An error occured while deleting a firewall rule ID %s %s", d.Id(), resp.Response) + } + + err := waitTillProvisioned(meta, resp.Headers.Get("Location")) + if err != nil { + return err + } + return resourceProfitBricksFirewallRead(d, meta) +} + +func resourceProfitBricksFirewallDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + resp := profitbricks.DeleteFirewallRule(d.Get("datacenter_id").(string), d.Get("server_id").(string), d.Get("nic_id").(string), d.Id()) + + if resp.StatusCode > 299 { + return fmt.Errorf("An error occured while deleting a firewall rule ID %s %s", d.Id(), string(resp.Body)) + } + + err := waitTillProvisioned(meta, resp.Headers.Get("Location")) + if err != nil { + return err + } + d.SetId("") + + return nil +} diff --git a/builtin/providers/profitbricks/resource_profitbricks_firewall_test.go b/builtin/providers/profitbricks/resource_profitbricks_firewall_test.go new file mode 100644 index 000000000000..612c0c7e1026 --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_firewall_test.go @@ -0,0 +1,201 @@ +package profitbricks + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/profitbricks/profitbricks-sdk-go" +) + +func TestAccProfitBricksFirewall_Basic(t *testing.T) { + var firewall profitbricks.FirewallRule + firewallName := "firewall" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDProfitBricksFirewallDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckProfitbricksFirewallConfig_basic, firewallName), + Check: resource.ComposeTestCheckFunc( + testAccCheckProfitBricksFirewallExists("profitbricks_firewall.webserver_http", &firewall), + testAccCheckProfitBricksFirewallAttributes("profitbricks_firewall.webserver_http", firewallName), + resource.TestCheckResourceAttr("profitbricks_firewall.webserver_http", "name", firewallName), + ), + }, + resource.TestStep{ + Config: testAccCheckProfitbricksFirewallConfig_update, + Check: resource.ComposeTestCheckFunc( + testAccCheckProfitBricksFirewallAttributes("profitbricks_firewall.webserver_http", "updated"), + resource.TestCheckResourceAttr("profitbricks_firewall.webserver_http", "name", "updated"), + ), + }, + }, + }) +} + +func testAccCheckDProfitBricksFirewallDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "profitbricks_firewall" { + continue + } + + resp := profitbricks.GetFirewallRule(rs.Primary.Attributes["datacenter_id"], rs.Primary.Attributes["server_id"], rs.Primary.Attributes["nic_id"], rs.Primary.ID) + + if resp.StatusCode < 299 { + return fmt.Errorf("Firewall still exists %s %s", rs.Primary.ID, resp.Response) + } + } + + return nil +} + +func testAccCheckProfitBricksFirewallAttributes(n string, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("testAccCheckProfitBricksFirewallAttributes: Not found: %s", n) + } + if rs.Primary.Attributes["name"] != name { + return fmt.Errorf("Bad name: %s", rs.Primary.Attributes["name"]) + } + + return nil + } +} + +func testAccCheckProfitBricksFirewallExists(n string, firewall *profitbricks.FirewallRule) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("testAccCheckProfitBricksFirewallExists: Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + foundServer := profitbricks.GetFirewallRule(rs.Primary.Attributes["datacenter_id"], rs.Primary.Attributes["server_id"], rs.Primary.Attributes["nic_id"], rs.Primary.ID) + + if foundServer.StatusCode != 200 { + return fmt.Errorf("Error occured while fetching Firewall rule: %s", rs.Primary.ID) + } + if foundServer.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + + firewall = &foundServer + + return nil + } +} + +const testAccCheckProfitbricksFirewallConfig_basic = ` +resource "profitbricks_datacenter" "foobar" { + name = "firewall-test" + location = "us/las" +} + +resource "profitbricks_server" "webserver" { + name = "webserver" + datacenter_id = "${profitbricks_datacenter.foobar.id}" + cores = 1 + ram = 1024 + availability_zone = "ZONE_1" + cpu_family = "AMD_OPTERON" + volume { + name = "system" + size = 5 + disk_type = "SSD" + image_name ="ubuntu-16.04" + image_password = "test1234" +} + nic { + lan = "1" + dhcp = true + firewall_active = true + firewall { + protocol = "TCP" + name = "SSH" + port_range_start = 22 + port_range_end = 22 + } + } +} + +resource "profitbricks_nic" "database_nic" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + server_id = "${profitbricks_server.webserver.id}" + lan = 2 + dhcp = true + firewall_active = true + name = "updated" +} + +resource "profitbricks_firewall" "webserver_http" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + server_id = "${profitbricks_server.webserver.id}" + nic_id = "${profitbricks_nic.database_nic.id}" + protocol = "TCP" + name = "%s" + port_range_start = 80 + port_range_end = 80 +}` + +const testAccCheckProfitbricksFirewallConfig_update = ` +resource "profitbricks_datacenter" "foobar" { + name = "firewall-test" + location = "us/las" +} + +resource "profitbricks_server" "webserver" { + name = "webserver" + datacenter_id = "${profitbricks_datacenter.foobar.id}" + cores = 1 + ram = 1024 + availability_zone = "ZONE_1" + cpu_family = "AMD_OPTERON" + volume { + name = "system" + size = 5 + disk_type = "SSD" + image_name ="ubuntu-16.04" + image_password = "test1234" +} + nic { + lan = "1" + dhcp = true + firewall_active = true + firewall { + protocol = "TCP" + name = "SSH" + port_range_start = 22 + port_range_end = 22 + } + } +} + +resource "profitbricks_nic" "database_nic" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + server_id = "${profitbricks_server.webserver.id}" + lan = 2 + dhcp = true + firewall_active = true + name = "updated" +} + +resource "profitbricks_firewall" "webserver_http" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + server_id = "${profitbricks_server.webserver.id}" + nic_id = "${profitbricks_nic.database_nic.id}" + protocol = "TCP" + name = "updated" + port_range_start = 80 + port_range_end = 80 +}` diff --git a/builtin/providers/profitbricks/resource_profitbricks_ipblock.go b/builtin/providers/profitbricks/resource_profitbricks_ipblock.go new file mode 100644 index 000000000000..008a1205008b --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_ipblock.go @@ -0,0 +1,95 @@ +package profitbricks + +import ( + "fmt" + "github.com/hashicorp/terraform/helper/schema" + "github.com/profitbricks/profitbricks-sdk-go" + "log" + "strings" +) + +func resourceProfitBricksIPBlock() *schema.Resource { + return &schema.Resource{ + Create: resourceProfitBricksIPBlockCreate, + Read: resourceProfitBricksIPBlockRead, + //Update: resourceProfitBricksIPBlockUpdate, + Delete: resourceProfitBricksIPBlockDelete, + Schema: map[string]*schema.Schema{ + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "size": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + }, + "ips": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceProfitBricksIPBlockCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + ipblock := profitbricks.IpBlock{ + Properties: profitbricks.IpBlockProperties{ + Size: d.Get("size").(int), + Location: d.Get("location").(string), + }, + } + + ipblock = profitbricks.ReserveIpBlock(ipblock) + + if ipblock.StatusCode > 299 { + return fmt.Errorf("An error occured while reserving an ip block: %s", ipblock.Response) + } + err := waitTillProvisioned(meta, ipblock.Headers.Get("Location")) + if err != nil { + return err + } + d.SetId(ipblock.Id) + + return resourceProfitBricksIPBlockRead(d, meta) +} + +func resourceProfitBricksIPBlockRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + ipblock := profitbricks.GetIpBlock(d.Id()) + + if ipblock.StatusCode > 299 { + return fmt.Errorf("An error occured while fetching an ip block ID %s %s", d.Id(), ipblock.Response) + } + + log.Printf("[INFO] IPS: %s", strings.Join(ipblock.Properties.Ips, ",")) + + d.Set("ips", strings.Join(ipblock.Properties.Ips, ",")) + d.Set("location", ipblock.Properties.Location) + d.Set("size", ipblock.Properties.Size) + + return nil +} + +func resourceProfitBricksIPBlockDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + resp := profitbricks.ReleaseIpBlock(d.Id()) + if resp.StatusCode > 299 { + return fmt.Errorf("An error occured while releasing an ipblock ID: %s %s", d.Id(), string(resp.Body)) + } + + err := waitTillProvisioned(meta, resp.Headers.Get("Location")) + if err != nil { + return err + } + d.SetId("") + return nil +} diff --git a/builtin/providers/profitbricks/resource_profitbricks_ipblock_test.go b/builtin/providers/profitbricks/resource_profitbricks_ipblock_test.go new file mode 100644 index 000000000000..a08dea904d1f --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_ipblock_test.go @@ -0,0 +1,96 @@ +package profitbricks + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/profitbricks/profitbricks-sdk-go" +) + +func TestAccProfitBricksIPBlock_Basic(t *testing.T) { + var ipblock profitbricks.IpBlock + location := "us/las" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDProfitBricksIPBlockDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckProfitbricksIPBlockConfig_basic, location), + Check: resource.ComposeTestCheckFunc( + testAccCheckProfitBricksIPBlockExists("profitbricks_ipblock.webserver_ip", &ipblock), + testAccCheckProfitBricksIPBlockAttributes("profitbricks_ipblock.webserver_ip", location), + resource.TestCheckResourceAttr("profitbricks_ipblock.webserver_ip", "location", location), + ), + }, + }, + }) +} + +func testAccCheckDProfitBricksIPBlockDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "profitbricks_ipblock" { + continue + } + + resp := profitbricks.GetIpBlock(rs.Primary.ID) + + if resp.StatusCode < 299 { + return fmt.Errorf("IPBlock still exists %s %s", rs.Primary.ID, resp.Response) + } + } + + return nil +} + +func testAccCheckProfitBricksIPBlockAttributes(n string, location string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("testAccCheckProfitBricksLanAttributes: Not found: %s", n) + } + if rs.Primary.Attributes["location"] != location { + return fmt.Errorf("Bad name: %s", rs.Primary.Attributes["location"]) + } + + return nil + } +} + +func testAccCheckProfitBricksIPBlockExists(n string, ipblock *profitbricks.IpBlock) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("testAccCheckProfitBricksIPBlockExists: Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + foundIP := profitbricks.GetIpBlock(rs.Primary.ID) + + if foundIP.StatusCode != 200 { + return fmt.Errorf("Error occured while fetching IP Block: %s", rs.Primary.ID) + } + if foundIP.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + + ipblock = &foundIP + + return nil + } +} + +const testAccCheckProfitbricksIPBlockConfig_basic = ` +resource "profitbricks_ipblock" "webserver_ip" { + location = "%s" + size = 1 +}` diff --git a/builtin/providers/profitbricks/resource_profitbricks_lan.go b/builtin/providers/profitbricks/resource_profitbricks_lan.go new file mode 100644 index 000000000000..28849928dfd9 --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_lan.go @@ -0,0 +1,123 @@ +package profitbricks + +import ( + "fmt" + "github.com/hashicorp/terraform/helper/schema" + "github.com/profitbricks/profitbricks-sdk-go" + "log" +) + +func resourceProfitBricksLan() *schema.Resource { + return &schema.Resource{ + Create: resourceProfitBricksLanCreate, + Read: resourceProfitBricksLanRead, + Update: resourceProfitBricksLanUpdate, + Delete: resourceProfitBricksLanDelete, + Schema: map[string]*schema.Schema{ + + "public": { + Type: schema.TypeBool, + Required: true, + }, + "name": { + Type: schema.TypeString, + Optional: true, + }, + "datacenter_id": { + Type: schema.TypeString, + Required: true, + }, + }, + } +} + +func resourceProfitBricksLanCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + profitbricks.SetDepth("5") + request := profitbricks.Lan{ + Properties: profitbricks.LanProperties{ + Public: d.Get("public").(bool), + }, + } + + log.Printf("[DEBUG] NAME %s", d.Get("name")) + if d.Get("name") != nil { + request.Properties.Name = d.Get("name").(string) + } + + lan := profitbricks.CreateLan(d.Get("datacenter_id").(string), request) + + log.Printf("[DEBUG] LAN ID: %s", lan.Id) + log.Printf("[DEBUG] LAN RESPONSE: %s", lan.Response) + + if lan.StatusCode > 299 { + return fmt.Errorf("An error occured while creating a lan: %s", lan.Response) + } + + err := waitTillProvisioned(meta, lan.Headers.Get("Location")) + if err != nil { + return err + } + d.SetId(lan.Id) + return resourceProfitBricksLanRead(d, meta) +} + +func resourceProfitBricksLanRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + lan := profitbricks.GetLan(d.Get("datacenter_id").(string), d.Id()) + + if lan.StatusCode > 299 { + return fmt.Errorf("An error occured while fetching a lan ID %s %s", d.Id(), lan.Response) + } + + d.Set("public", lan.Properties.Public) + d.Set("name", lan.Properties.Name) + d.Set("datacenter_id", d.Get("datacenter_id").(string)) + return nil +} + +func resourceProfitBricksLanUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + properties := &profitbricks.LanProperties{} + if d.HasChange("public") { + _, newValue := d.GetChange("public") + properties.Public = newValue.(bool) + } + if d.HasChange("name") { + _, newValue := d.GetChange("name") + properties.Name = newValue.(string) + } + log.Printf("[DEBUG] LAN UPDATE: %s : %s", properties, d.Get("name")) + if properties != nil { + lan := profitbricks.PatchLan(d.Get("datacenter_id").(string), d.Id(), *properties) + if lan.StatusCode > 299 { + return fmt.Errorf("An error occured while patching a lan ID %s %s", d.Id(), lan.Response) + } + err := waitTillProvisioned(meta, lan.Headers.Get("Location")) + if err != nil { + return err + } + } + return resourceProfitBricksLanRead(d, meta) +} + +func resourceProfitBricksLanDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + resp := profitbricks.DeleteLan(d.Get("datacenter_id").(string), d.Id()) + + if resp.Headers.Get("Location") != "" { + err := waitTillProvisioned(meta, resp.Headers.Get("Location")) + if err != nil { + return err + } + } + d.SetId("") + return nil +} diff --git a/builtin/providers/profitbricks/resource_profitbricks_lan_test.go b/builtin/providers/profitbricks/resource_profitbricks_lan_test.go new file mode 100644 index 000000000000..ffaedf91701e --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_lan_test.go @@ -0,0 +1,120 @@ +package profitbricks + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/profitbricks/profitbricks-sdk-go" +) + +func TestAccProfitBricksLan_Basic(t *testing.T) { + var lan profitbricks.Lan + lanName := "lanName" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDProfitBricksLanDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckProfitbricksLanConfig_basic, lanName), + Check: resource.ComposeTestCheckFunc( + testAccCheckProfitBricksLanExists("profitbricks_lan.webserver_lan", &lan), + testAccCheckProfitBricksLanAttributes("profitbricks_lan.webserver_lan", lanName), + resource.TestCheckResourceAttr("profitbricks_lan.webserver_lan", "name", lanName), + ), + }, + resource.TestStep{ + Config: testAccCheckProfitbricksLanConfig_update, + Check: resource.ComposeTestCheckFunc( + testAccCheckProfitBricksLanAttributes("profitbricks_lan.webserver_lan", "updated"), + resource.TestCheckResourceAttr("profitbricks_lan.webserver_lan", "name", "updated"), + ), + }, + }, + }) +} + +func testAccCheckDProfitBricksLanDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "profitbricks_datacenter" { + continue + } + + resp := profitbricks.GetLan(rs.Primary.Attributes["datacenter_id"], rs.Primary.ID) + + if resp.StatusCode < 299 { + return fmt.Errorf("LAN still exists %s %s", rs.Primary.ID, resp.Response) + } + } + + return nil +} + +func testAccCheckProfitBricksLanAttributes(n string, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("testAccCheckProfitBricksLanAttributes: Not found: %s", n) + } + if rs.Primary.Attributes["name"] != name { + return fmt.Errorf("Bad name: %s", rs.Primary.Attributes["name"]) + } + + return nil + } +} + +func testAccCheckProfitBricksLanExists(n string, lan *profitbricks.Lan) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("testAccCheckProfitBricksLanExists: Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + foundLan := profitbricks.GetLan(rs.Primary.Attributes["datacenter_id"], rs.Primary.ID) + + if foundLan.StatusCode != 200 { + return fmt.Errorf("Error occured while fetching Server: %s", rs.Primary.ID) + } + if foundLan.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + + lan = &foundLan + + return nil + } +} + +const testAccCheckProfitbricksLanConfig_basic = ` +resource "profitbricks_datacenter" "foobar" { + name = "lan-test" + location = "us/las" +} + +resource "profitbricks_lan" "webserver_lan" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + public = true + name = "%s" +}` + +const testAccCheckProfitbricksLanConfig_update = ` +resource "profitbricks_datacenter" "foobar" { + name = "lan-test" + location = "us/las" +} +resource "profitbricks_lan" "webserver_lan" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + public = true + name = "updated" +}` diff --git a/builtin/providers/profitbricks/resource_profitbricks_loadbalancer.go b/builtin/providers/profitbricks/resource_profitbricks_loadbalancer.go new file mode 100644 index 000000000000..c58af3e339c7 --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_loadbalancer.go @@ -0,0 +1,148 @@ +package profitbricks + +import ( + "fmt" + "github.com/hashicorp/terraform/helper/schema" + "github.com/profitbricks/profitbricks-sdk-go" +) + +func resourceProfitBricksLoadbalancer() *schema.Resource { + return &schema.Resource{ + Create: resourceProfitBricksLoadbalancerCreate, + Read: resourceProfitBricksLoadbalancerRead, + Update: resourceProfitBricksLoadbalancerUpdate, + Delete: resourceProfitBricksLoadbalancerDelete, + Schema: map[string]*schema.Schema{ + + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + + "ip": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "dhcp": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + }, + "datacenter_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + "nic_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + }, + } +} + +func resourceProfitBricksLoadbalancerCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + lb := profitbricks.Loadbalancer{ + Properties: profitbricks.LoadbalancerProperties{ + Name: d.Get("name").(string), + }, + } + + lb = profitbricks.CreateLoadbalancer(d.Get("datacenter_id").(string), lb) + + if lb.StatusCode > 299 { + return fmt.Errorf("Error occured while creating a loadbalancer %s", lb.Response) + } + err := waitTillProvisioned(meta, lb.Headers.Get("Location")) + + if err != nil { + return err + } + + d.SetId(lb.Id) + + nic := profitbricks.AssociateNic(d.Get("datacenter_id").(string), d.Id(), d.Get("nic_id").(string)) + + if nic.StatusCode > 299 { + return fmt.Errorf("Error occured while deleting a balanced nic: %s", nic.Response) + } + err = waitTillProvisioned(meta, nic.Headers.Get("Location")) + if err != nil { + return err + } + + return resourceProfitBricksLoadbalancerRead(d, meta) +} + +func resourceProfitBricksLoadbalancerRead(d *schema.ResourceData, meta interface{}) error { + lb := profitbricks.GetLoadbalancer(d.Get("datacenter_id").(string), d.Id()) + + d.Set("name", lb.Properties.Name) + d.Set("ip", lb.Properties.Ip) + d.Set("dhcp", lb.Properties.Dhcp) + + return nil +} + +func resourceProfitBricksLoadbalancerUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + properties := profitbricks.LoadbalancerProperties{} + if d.HasChange("name") { + _, new := d.GetChange("name") + properties.Name = new.(string) + } + if d.HasChange("ip") { + _, new := d.GetChange("ip") + properties.Ip = new.(string) + } + if d.HasChange("dhcp") { + _, new := d.GetChange("dhcp") + properties.Dhcp = new.(bool) + } + + if d.HasChange("nic_id") { + old, new := d.GetChange("dhcp") + + resp := profitbricks.DeleteBalancedNic(d.Get("datacenter_id").(string), d.Id(), old.(string)) + if resp.StatusCode > 299 { + return fmt.Errorf("Error occured while deleting a balanced nic: %s", string(resp.Body)) + } + err := waitTillProvisioned(meta, resp.Headers.Get("Location")) + if err != nil { + return err + } + + nic := profitbricks.AssociateNic(d.Get("datacenter_id").(string), d.Id(), new.(string)) + if nic.StatusCode > 299 { + return fmt.Errorf("Error occured while deleting a balanced nic: %s", nic.Response) + } + err = waitTillProvisioned(meta, nic.Headers.Get("Location")) + if err != nil { + return err + } + } + + return resourceProfitBricksLoadbalancerRead(d, meta) +} + +func resourceProfitBricksLoadbalancerDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + resp := profitbricks.DeleteLoadbalancer(d.Get("datacenter_id").(string), d.Id()) + + if resp.StatusCode > 299 { + return fmt.Errorf("Error occured while deleting a loadbalancer: %s", string(resp.Body)) + } + + err := waitTillProvisioned(meta, resp.Headers.Get("Location")) + if err != nil { + return err + } + + d.SetId("") + return nil +} diff --git a/builtin/providers/profitbricks/resource_profitbricks_loadbalancer_test.go b/builtin/providers/profitbricks/resource_profitbricks_loadbalancer_test.go new file mode 100644 index 000000000000..3c7a5702697c --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_loadbalancer_test.go @@ -0,0 +1,195 @@ +package profitbricks + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/profitbricks/profitbricks-sdk-go" +) + +func TestAccProfitBricksLoadbalancer_Basic(t *testing.T) { + var loadbalancer profitbricks.Loadbalancer + lbName := "loadbalancer" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDProfitBricksLoadbalancerDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckProfitbricksLoadbalancerConfig_basic, lbName), + Check: resource.ComposeTestCheckFunc( + testAccCheckProfitBricksLoadbalancerExists("profitbricks_loadbalancer.example", &loadbalancer), + testAccCheckProfitBricksLoadbalancerAttributes("profitbricks_loadbalancer.example", lbName), + resource.TestCheckResourceAttr("profitbricks_loadbalancer.example", "name", lbName), + ), + }, + resource.TestStep{ + Config: testAccCheckProfitbricksLoadbalancerConfig_update, + Check: resource.ComposeTestCheckFunc( + testAccCheckProfitBricksLoadbalancerAttributes("profitbricks_loadbalancer.example", "updated"), + resource.TestCheckResourceAttr("profitbricks_loadbalancer.example", "name", "updated"), + ), + }, + }, + }) +} + +func testAccCheckDProfitBricksLoadbalancerDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "profitbricks_loadbalancer" { + continue + } + + resp := profitbricks.GetLoadbalancer(rs.Primary.Attributes["datacenter_id"], rs.Primary.ID) + + if resp.StatusCode < 299 { + return fmt.Errorf("Firewall still exists %s %s", rs.Primary.ID, resp.Response) + } + } + + return nil +} + +func testAccCheckProfitBricksLoadbalancerAttributes(n string, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("testAccCheckProfitBricksLoadbalancerAttributes: Not found: %s", n) + } + if rs.Primary.Attributes["name"] != name { + return fmt.Errorf("Bad name: %s", rs.Primary.Attributes["name"]) + } + + return nil + } +} + +func testAccCheckProfitBricksLoadbalancerExists(n string, loadbalancer *profitbricks.Loadbalancer) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("testAccCheckProfitBricksLoadbalancerExists: Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + foundLB := profitbricks.GetLoadbalancer(rs.Primary.Attributes["datacenter_id"], rs.Primary.ID) + + if foundLB.StatusCode != 200 { + return fmt.Errorf("Error occured while fetching Loadbalancer: %s", rs.Primary.ID) + } + if foundLB.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + + loadbalancer = &foundLB + + return nil + } +} + +const testAccCheckProfitbricksLoadbalancerConfig_basic = ` +resource "profitbricks_datacenter" "foobar" { + name = "loadbalancer-test" + location = "us/las" +} + +resource "profitbricks_server" "webserver" { + name = "webserver" + datacenter_id = "${profitbricks_datacenter.foobar.id}" + cores = 1 + ram = 1024 + availability_zone = "ZONE_1" + cpu_family = "AMD_OPTERON" + volume { + name = "system" + size = 5 + disk_type = "SSD" + image_name ="ubuntu-16.04" + image_password = "test1234" +} + nic { + lan = "1" + dhcp = true + firewall_active = true + firewall { + protocol = "TCP" + name = "SSH" + port_range_start = 22 + port_range_end = 22 + } + } +} + +resource "profitbricks_nic" "database_nic" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + server_id = "${profitbricks_server.webserver.id}" + lan = "2" + dhcp = true + firewall_active = true + name = "updated" +} + +resource "profitbricks_loadbalancer" "example" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + nic_id = "${profitbricks_nic.database_nic.id}" + name = "%s" + dhcp = true +}` + +const testAccCheckProfitbricksLoadbalancerConfig_update = ` +resource "profitbricks_datacenter" "foobar" { + name = "loadbalancer-test" + location = "us/las" +} + +resource "profitbricks_server" "webserver" { + name = "webserver" + datacenter_id = "${profitbricks_datacenter.foobar.id}" + cores = 1 + ram = 1024 + availability_zone = "ZONE_1" + cpu_family = "AMD_OPTERON" + volume { + name = "system" + size = 5 + disk_type = "SSD" + image_name ="ubuntu-16.04" + image_password = "test1234" +} + nic { + lan = "1" + dhcp = true + firewall_active = true + firewall { + protocol = "TCP" + name = "SSH" + port_range_start = 22 + port_range_end = 22 + } + } +} + +resource "profitbricks_nic" "database_nic" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + server_id = "${profitbricks_server.webserver.id}" + lan = "2" + dhcp = true + firewall_active = true + name = "updated" +} + +resource "profitbricks_loadbalancer" "example" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + nic_id = "${profitbricks_nic.database_nic.id}" + name = "updated" + dhcp = true +}` diff --git a/builtin/providers/profitbricks/resource_profitbricks_nic.go b/builtin/providers/profitbricks/resource_profitbricks_nic.go new file mode 100644 index 000000000000..5b9e35e635f7 --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_nic.go @@ -0,0 +1,161 @@ +package profitbricks + +import ( + "fmt" + "github.com/hashicorp/terraform/helper/schema" + "github.com/profitbricks/profitbricks-sdk-go" + "log" + "strings" +) + +func resourceProfitBricksNic() *schema.Resource { + return &schema.Resource{ + Create: resourceProfitBricksNicCreate, + Read: resourceProfitBricksNicRead, + Update: resourceProfitBricksNicUpdate, + Delete: resourceProfitBricksNicDelete, + Schema: map[string]*schema.Schema{ + + "lan": &schema.Schema{ + Type: schema.TypeInt, + Required: true, + }, + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "dhcp": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + }, + "ip": { + Type: schema.TypeString, + Optional: true, + }, + "firewall_active": { + Type: schema.TypeBool, + Optional: true, + }, + "server_id": { + Type: schema.TypeString, + Required: true, + }, + "datacenter_id": { + Type: schema.TypeString, + Required: true, + }, + }, + } +} + +func resourceProfitBricksNicCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + nic := profitbricks.Nic{ + Properties: profitbricks.NicProperties{ + Lan: d.Get("lan").(int), + }, + } + if _, ok := d.GetOk("name"); ok { + nic.Properties.Name = d.Get("name").(string) + } + if _, ok := d.GetOk("dhcp"); ok { + nic.Properties.Dhcp = d.Get("dhcp").(bool) + } + + if _, ok := d.GetOk("ip"); ok { + raw := d.Get("ip").(string) + ips := strings.Split(raw, ",") + nic.Properties.Ips = ips + } + + nic = profitbricks.CreateNic(d.Get("datacenter_id").(string), d.Get("server_id").(string), nic) + if nic.StatusCode > 299 { + return fmt.Errorf("Error occured while creating a nic: %s", nic.Response) + } + + err := waitTillProvisioned(meta, nic.Headers.Get("Location")) + if err != nil { + return err + } + resp := profitbricks.RebootServer(d.Get("datacenter_id").(string), d.Get("server_id").(string)) + if resp.StatusCode > 299 { + return fmt.Errorf("Error occured while creating a nic: %s", string(resp.Body)) + + } + err = waitTillProvisioned(meta, resp.Headers.Get("Location")) + if err != nil { + return err + } + d.SetId(nic.Id) + return resourceProfitBricksNicRead(d, meta) +} + +func resourceProfitBricksNicRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + profitbricks.SetDepth("5") + + nic := profitbricks.GetNic(d.Get("datacenter_id").(string), d.Get("server_id").(string), d.Id()) + if nic.StatusCode > 299 { + return fmt.Errorf("Error occured while fetching a nic ID %s %s", d.Id(), nic.Response) + } + log.Printf("[INFO] LAN ON NIC: %s", nic.Properties.Lan) + d.Set("dhcp", nic.Properties.Dhcp) + d.Set("lan", nic.Properties.Lan) + d.Set("name", nic.Properties.Name) + d.Set("ip", nic.Properties.Ips) + + return nil +} + +func resourceProfitBricksNicUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + properties := profitbricks.NicProperties{} + + if d.HasChange("name") { + _, n := d.GetChange("name") + + properties.Name = n.(string) + } + if d.HasChange("lan") { + _, n := d.GetChange("lan") + properties.Lan = n.(int) + } + if d.HasChange("dhcp") { + _, n := d.GetChange("dhcp") + properties.Dhcp = n.(bool) + } + if d.HasChange("ip") { + _, raw := d.GetChange("ip") + ips := strings.Split(raw.(string), ",") + properties.Ips = ips + } + + nic := profitbricks.PatchNic(d.Get("datacenter_id").(string), d.Get("server_id").(string), d.Id(), properties) + + if nic.StatusCode > 299 { + return fmt.Errorf("Error occured while updating a nic: %s", nic.Response) + } + err := waitTillProvisioned(meta, nic.Headers.Get("Location")) + if err != nil { + return err + } + return resourceProfitBricksNicRead(d, meta) +} + +func resourceProfitBricksNicDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + resp := profitbricks.DeleteNic(d.Get("datacenter_id").(string), d.Get("server_id").(string), d.Id()) + err := waitTillProvisioned(meta, resp.Headers.Get("Location")) + if err != nil { + return err + } + d.SetId("") + return nil +} diff --git a/builtin/providers/profitbricks/resource_profitbricks_nic_test.go b/builtin/providers/profitbricks/resource_profitbricks_nic_test.go new file mode 100644 index 000000000000..02af16b6316a --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_nic_test.go @@ -0,0 +1,182 @@ +package profitbricks + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/profitbricks/profitbricks-sdk-go" +) + +func TestAccProfitBricksNic_Basic(t *testing.T) { + var nic profitbricks.Nic + volumeName := "volume" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDProfitBricksNicDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckProfitbricksNicConfig_basic, volumeName), + Check: resource.ComposeTestCheckFunc( + testAccCheckProfitBricksNICExists("profitbricks_nic.database_nic", &nic), + testAccCheckProfitBricksNicAttributes("profitbricks_nic.database_nic", volumeName), + resource.TestCheckResourceAttr("profitbricks_nic.database_nic", "name", volumeName), + ), + }, + resource.TestStep{ + Config: testAccCheckProfitbricksNicConfig_update, + Check: resource.ComposeTestCheckFunc( + testAccCheckProfitBricksNicAttributes("profitbricks_nic.database_nic", "updated"), + resource.TestCheckResourceAttr("profitbricks_nic.database_nic", "name", "updated"), + ), + }, + }, + }) +} + +func testAccCheckDProfitBricksNicDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "profitbricks_nic" { + continue + } + + resp := profitbricks.GetNic(rs.Primary.Attributes["datacenter_id"], rs.Primary.Attributes["nic_id"], rs.Primary.ID) + + if resp.StatusCode < 299 { + return fmt.Errorf("NIC still exists %s %s", rs.Primary.ID, resp.Response) + } + } + + return nil +} + +func testAccCheckProfitBricksNicAttributes(n string, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("testAccCheckProfitBricksNicAttributes: Not found: %s", n) + } + if rs.Primary.Attributes["name"] != name { + return fmt.Errorf("Bad name: %s", rs.Primary.Attributes["name"]) + } + + return nil + } +} + +func testAccCheckProfitBricksNICExists(n string, nic *profitbricks.Nic) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("testAccCheckProfitBricksVolumeExists: Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + foundNic := profitbricks.GetNic(rs.Primary.Attributes["datacenter_id"], rs.Primary.Attributes["server_id"], rs.Primary.ID) + + if foundNic.StatusCode != 200 { + return fmt.Errorf("Error occured while fetching Volume: %s", rs.Primary.ID) + } + if foundNic.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + + nic = &foundNic + + return nil + } +} + +const testAccCheckProfitbricksNicConfig_basic = ` +resource "profitbricks_datacenter" "foobar" { + name = "nic-test" + location = "us/las" +} + +resource "profitbricks_server" "webserver" { + name = "webserver" + datacenter_id = "${profitbricks_datacenter.foobar.id}" + cores = 1 + ram = 1024 + availability_zone = "ZONE_1" + cpu_family = "AMD_OPTERON" + volume { + name = "system" + size = 5 + disk_type = "SSD" + image_name ="ubuntu-16.04" + image_password = "test1234" +} + nic { + lan = "1" + dhcp = true + firewall_active = true + firewall { + protocol = "TCP" + name = "SSH" + port_range_start = 22 + port_range_end = 22 + } + } +} + +resource "profitbricks_nic" "database_nic" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + server_id = "${profitbricks_server.webserver.id}" + lan = 2 + dhcp = true + firewall_active = true + name = "%s" +}` + +const testAccCheckProfitbricksNicConfig_update = ` +resource "profitbricks_datacenter" "foobar" { + name = "nic-test" + location = "us/las" +} + +resource "profitbricks_server" "webserver" { + name = "webserver" + datacenter_id = "${profitbricks_datacenter.foobar.id}" + cores = 1 + ram = 1024 + availability_zone = "ZONE_1" + cpu_family = "AMD_OPTERON" + volume { + name = "system" + size = 5 + disk_type = "SSD" + image_name ="ubuntu-16.04" + image_password = "test1234" +} + nic { + lan = "1" + dhcp = true + firewall_active = true + firewall { + protocol = "TCP" + name = "SSH" + port_range_start = 22 + port_range_end = 22 + } + } +} + +resource "profitbricks_nic" "database_nic" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + server_id = "${profitbricks_server.webserver.id}" + lan = 2 + dhcp = true + firewall_active = true + name = "updated" +} +` diff --git a/builtin/providers/profitbricks/resource_profitbricks_server.go b/builtin/providers/profitbricks/resource_profitbricks_server.go new file mode 100644 index 000000000000..0db0b8e1090b --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_server.go @@ -0,0 +1,641 @@ +package profitbricks + +import ( + "crypto/x509" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "github.com/hashicorp/terraform/helper/schema" + "github.com/profitbricks/profitbricks-sdk-go" + "golang.org/x/crypto/ssh" + "io/ioutil" + "log" + "strconv" + "strings" +) + +func resourceProfitBricksServer() *schema.Resource { + return &schema.Resource{ + Create: resourceProfitBricksServerCreate, + Read: resourceProfitBricksServerRead, + Update: resourceProfitBricksServerUpdate, + Delete: resourceProfitBricksServerDelete, + Schema: map[string]*schema.Schema{ + + //Server parameters + "name": { + Type: schema.TypeString, + Required: true, + }, + "cores": { + Type: schema.TypeInt, + Required: true, + }, + "ram": { + Type: schema.TypeInt, + Required: true, + }, + "availability_zone": { + Type: schema.TypeString, + Optional: true, + }, + "licence_type": { + Type: schema.TypeString, + Optional: true, + }, + + "boot_volume": { + Type: schema.TypeString, + Computed: true, + }, + + "boot_cdrom": { + Type: schema.TypeString, + Computed: true, + }, + "cpu_family": { + Type: schema.TypeString, + Optional: true, + }, + "boot_image": { + Type: schema.TypeString, + Computed: true, + }, + "primary_nic": { + Type: schema.TypeString, + Computed: true, + }, + "datacenter_id": { + Type: schema.TypeString, + Required: true, + }, + "volume": { + Type: schema.TypeSet, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "image_name": { + Type: schema.TypeString, + Required: true, + }, + "size": { + Type: schema.TypeInt, + Required: true, + }, + + "disk_type": { + Type: schema.TypeString, + Required: true, + }, + "image_password": { + Type: schema.TypeString, + Optional: true, + }, + "licence_type": { + Type: schema.TypeString, + Optional: true, + }, + "ssh_key_path": { + Type: schema.TypeString, + Optional: true, + }, + "bus": { + Type: schema.TypeString, + Optional: true, + }, + "name": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + "nic": { + Type: schema.TypeSet, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "lan": { + Type: schema.TypeInt, + Required: true, + }, + "name": { + Type: schema.TypeString, + Optional: true, + }, + "dhcp": { + Type: schema.TypeBool, + Optional: true, + }, + + "ip": { + Type: schema.TypeString, + Optional: true, + }, + "firewall_active": { + Type: schema.TypeBool, + Optional: true, + }, + "firewall": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Optional: true, + }, + + "protocol": { + Type: schema.TypeString, + Required: true, + }, + "source_mac": { + Type: schema.TypeString, + Optional: true, + }, + "source_ip": { + Type: schema.TypeString, + Optional: true, + }, + "target_ip": { + Type: schema.TypeString, + Optional: true, + }, + "ip": { + Type: schema.TypeString, + Optional: true, + }, + "port_range_start": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + if v.(int) < 1 && v.(int) > 65534 { + errors = append(errors, fmt.Errorf("Port start range must be between 1 and 65534")) + } + return + }, + }, + + "port_range_end": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + if v.(int) < 1 && v.(int) > 65534 { + errors = append(errors, fmt.Errorf("Port end range must be between 1 and 65534")) + } + return + }, + }, + "icmp_type": { + Type: schema.TypeString, + Optional: true, + }, + "icmp_code": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func resourceProfitBricksServerCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + request := profitbricks.Server{ + Properties: profitbricks.ServerProperties{ + Name: d.Get("name").(string), + Cores: d.Get("cores").(int), + Ram: d.Get("ram").(int), + }, + } + + if v, ok := d.GetOk("availability_zone"); ok { + request.Properties.AvailabilityZone = v.(string) + } + + if v, ok := d.GetOk("cpu_family"); ok { + if v.(string) != "" { + request.Properties.CpuFamily = v.(string) + } + } + if vRaw, ok := d.GetOk("volume"); ok { + + volumeRaw := vRaw.(*schema.Set).List() + + for _, raw := range volumeRaw { + rawMap := raw.(map[string]interface{}) + var imagePassword, sshkey_path string + var image, licenceType string + + if rawMap["image_name"] != nil { + image = getImageId(d.Get("datacenter_id").(string), rawMap["image_name"].(string), rawMap["disk_type"].(string)) + if image == "" { + dc := profitbricks.GetDatacenter(d.Get("datacenter_id").(string)) + return fmt.Errorf("Image '%s' doesn't exist. in location %s", rawMap["image_name"], dc.Properties.Location) + + } + } + if rawMap["licence_type"] != nil { + licenceType = rawMap["licence_type"].(string) + } + + if rawMap["image_password"] != nil { + imagePassword = rawMap["image_password"].(string) + } + if rawMap["ssh_key_path"] != nil { + sshkey_path = rawMap["ssh_key_path"].(string) + } + if rawMap["image_name"] != nil { + if imagePassword == "" && sshkey_path == "" { + return fmt.Errorf("'image_password' and 'ssh_key_path' are not provided.") + } + } + var publicKey string + var err error + if sshkey_path != "" { + log.Println("[DEBUG] GETTING THE KEY") + _, publicKey, err = getSshKey(d, sshkey_path) + if err != nil { + return fmt.Errorf("Error fetching sshkeys (%s)", err) + } + d.Set("sshkey", publicKey) + } + + if image == "" && licenceType == "" { + return fmt.Errorf("Either 'image', or 'licenceType' must be set.") + } + + request.Entities = &profitbricks.ServerEntities{ + Volumes: &profitbricks.Volumes{ + Items: []profitbricks.Volume{ + profitbricks.Volume{ + Properties: profitbricks.VolumeProperties{ + Name: rawMap["name"].(string), + Size: rawMap["size"].(int), + Type: rawMap["disk_type"].(string), + ImagePassword: imagePassword, + Image: image, + Bus: rawMap["bus"].(string), + LicenceType: licenceType, + }, + }, + }, + }, + } + + log.Printf("[DEBUG] PUBLIC KEY %s", publicKey) + + if publicKey == "" { + request.Entities.Volumes.Items[0].Properties.SshKeys = nil + } else { + request.Entities.Volumes.Items[0].Properties.SshKeys = []string{publicKey} + } + } + + } + + if nRaw, ok := d.GetOk("nic"); ok { + nicRaw := nRaw.(*schema.Set).List() + + for _, raw := range nicRaw { + rawMap := raw.(map[string]interface{}) + nic := profitbricks.Nic{Properties: profitbricks.NicProperties{}} + if rawMap["lan"] != nil { + nic.Properties.Lan = rawMap["lan"].(int) + } + if rawMap["name"] != nil { + nic.Properties.Name = rawMap["name"].(string) + } + if rawMap["dhcp"] != nil { + nic.Properties.Dhcp = rawMap["dhcp"].(bool) + } + if rawMap["firewall_active"] != nil { + nic.Properties.FirewallActive = rawMap["firewall_active"].(bool) + } + if rawMap["ip"] != nil { + rawIps := rawMap["ip"].(string) + ips := strings.Split(rawIps, ",") + if rawIps != "" { + nic.Properties.Ips = ips + } + } + request.Entities.Nics = &profitbricks.Nics{ + Items: []profitbricks.Nic{ + nic, + }, + } + + if rawMap["firewall"] != nil { + rawFw := rawMap["firewall"].(*schema.Set).List() + for _, rraw := range rawFw { + fwRaw := rraw.(map[string]interface{}) + log.Println("[DEBUG] fwRaw", fwRaw["protocol"]) + + firewall := profitbricks.FirewallRule{ + Properties: profitbricks.FirewallruleProperties{ + Protocol: fwRaw["protocol"].(string), + }, + } + + if fwRaw["name"] != nil { + firewall.Properties.Name = fwRaw["name"].(string) + } + if fwRaw["source_mac"] != nil { + firewall.Properties.SourceMac = fwRaw["source_mac"].(string) + } + if fwRaw["source_ip"] != nil { + firewall.Properties.SourceIp = fwRaw["source_ip"].(string) + } + if fwRaw["target_ip"] != nil { + firewall.Properties.TargetIp = fwRaw["target_ip"].(string) + } + if fwRaw["port_range_start"] != nil { + firewall.Properties.PortRangeStart = fwRaw["port_range_start"].(int) + } + if fwRaw["port_range_end"] != nil { + firewall.Properties.PortRangeEnd = fwRaw["port_range_end"].(int) + } + if fwRaw["icmp_type"] != nil { + firewall.Properties.IcmpType = fwRaw["icmp_type"].(string) + } + if fwRaw["icmp_code"] != nil { + firewall.Properties.IcmpCode = fwRaw["icmp_code"].(string) + } + + request.Entities.Nics.Items[0].Entities = &profitbricks.NicEntities{ + &profitbricks.FirewallRules{ + Items: []profitbricks.FirewallRule{ + firewall, + }, + }, + } + } + + } + } + } + + if len(request.Entities.Nics.Items[0].Properties.Ips) == 0 { + request.Entities.Nics.Items[0].Properties.Ips = nil + } + server := profitbricks.CreateServer(d.Get("datacenter_id").(string), request) + + jsn, _ := json.Marshal(request) + log.Println("[DEBUG] Server request", string(jsn)) + log.Println("[DEBUG] Server response", server.Response) + + if server.StatusCode > 299 { + return fmt.Errorf( + "Error creating server: (%s)", server.Response) + } + + err := waitTillProvisioned(meta, server.Headers.Get("Location")) + if err != nil { + return err + } + d.SetId(server.Id) + server = profitbricks.GetServer(d.Get("datacenter_id").(string), server.Id) + d.Set("primary_nic", server.Entities.Nics.Items[0]) + if len(server.Entities.Nics.Items[0].Properties.Ips) > 0 { + d.SetConnInfo(map[string]string{ + "type": "ssh", + "host": server.Entities.Nics.Items[0].Properties.Ips[0], + "password": request.Entities.Volumes.Items[0].Properties.ImagePassword, + }) + } + return resourceProfitBricksServerRead(d, meta) +} + +func resourceProfitBricksServerRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + dcId := d.Get("datacenter_id").(string) + + server := profitbricks.GetServer(dcId, d.Id()) + + primarynic := "" + + if server.Entities != nil && server.Entities.Nics != nil && len(server.Entities.Nics.Items) > 0 { + for _, n := range server.Entities.Nics.Items { + if n.Properties.Lan != 0 { + lan := profitbricks.GetLan(dcId, strconv.Itoa(n.Properties.Lan)) + if lan.StatusCode > 299 { + return fmt.Errorf("Error while fetching a lan %s", lan.Response) + } + if lan.Properties.Public.(interface{}) == true { + primarynic = n.Id + break + } + } + } + } + + d.Set("name", server.Properties.Name) + d.Set("cores", server.Properties.Cores) + d.Set("ram", server.Properties.Ram) + d.Set("availability_zone", server.Properties.AvailabilityZone) + d.Set("primary_nic", primarynic) + + if server.Properties.BootVolume != nil { + d.Set("boot_volume", server.Properties.BootVolume.Id) + } + if server.Properties.BootCdrom != nil { + d.Set("boot_cdrom", server.Properties.BootCdrom.Id) + } + return nil +} + +func resourceProfitBricksServerUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + dcId := d.Get("datacenter_id").(string) + + request := profitbricks.ServerProperties{} + + if d.HasChange("name") { + _, n := d.GetChange("name") + request.Name = n.(string) + } + if d.HasChange("cores") { + _, n := d.GetChange("cores") + request.Cores = n.(int) + } + if d.HasChange("ram") { + _, n := d.GetChange("ram") + request.Ram = n.(int) + } + if d.HasChange("availability_zone") { + _, n := d.GetChange("availability_zone") + request.AvailabilityZone = n.(string) + } + if d.HasChange("cpu_family") { + _, n := d.GetChange("cpu_family") + request.CpuFamily = n.(string) + } + server := profitbricks.PatchServer(dcId, d.Id(), request) + log.Println("[INFO] hlab hlab", request) + + //Volume stuff + if d.HasChange("volume") { + volume := server.Entities.Volumes.Items[0] + _, new := d.GetChange("volume") + + newVolume := new.(*schema.Set).List() + properties := profitbricks.VolumeProperties{} + + for _, raw := range newVolume { + rawMap := raw.(map[string]interface{}) + if rawMap["name"] != nil { + properties.Name = rawMap["name"].(string) + } + if rawMap["size"] != nil { + properties.Size = rawMap["size"].(int) + } + if rawMap["bus"] != nil { + properties.Bus = rawMap["bus"].(string) + } + } + + volume = profitbricks.PatchVolume(d.Get("datacenter_id").(string), server.Entities.Volumes.Items[0].Id, properties) + log.Println("[INFO] blah blah", properties) + + if volume.StatusCode > 299 { + return fmt.Errorf("Error patching volume (%s) (%s)", d.Id(), volume.Response) + } + + err := waitTillProvisioned(meta, volume.Headers.Get("Location")) + if err != nil { + return err + } + } + + //Nic stuff + if d.HasChange("nic") { + nic := profitbricks.Nic{} + for _, n := range server.Entities.Nics.Items { + if n.Id == d.Get("primary_nic").(string) { + nic = n + break + } + } + _, new := d.GetChange("nic") + + newNic := new.(*schema.Set).List() + properties := profitbricks.NicProperties{} + + for _, raw := range newNic { + rawMap := raw.(map[string]interface{}) + if rawMap["name"] != nil { + properties.Name = rawMap["name"].(string) + } + if rawMap["ip"] != nil { + rawIps := rawMap["ip"].(string) + ips := strings.Split(rawIps, ",") + + if rawIps != "" { + nic.Properties.Ips = ips + } + } + if rawMap["lan"] != nil { + properties.Lan = rawMap["lan"].(int) + } + if rawMap["dhcp"] != nil { + properties.Dhcp = rawMap["dhcp"].(bool) + } + } + + nic = profitbricks.PatchNic(d.Get("datacenter_id").(string), server.Id, server.Entities.Nics.Items[0].Id, properties) + log.Println("[INFO] blah blah", properties) + + if nic.StatusCode > 299 { + return fmt.Errorf( + "Error patching nic (%s)", nic.Response) + } + + err := waitTillProvisioned(meta, nic.Headers.Get("Location")) + if err != nil { + return err + } + } + + if server.StatusCode > 299 { + return fmt.Errorf( + "Error patching server (%s) (%s)", d.Id(), server.Response) + } + return resourceProfitBricksServerRead(d, meta) +} + +func resourceProfitBricksServerDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + dcId := d.Get("datacenter_id").(string) + + server := profitbricks.GetServer(dcId, d.Id()) + + if server.Properties.BootVolume != nil { + resp := profitbricks.DeleteVolume(dcId, server.Properties.BootVolume.Id) + err := waitTillProvisioned(meta, resp.Headers.Get("Location")) + if err != nil { + return err + } + } + + resp := profitbricks.DeleteServer(dcId, d.Id()) + if resp.StatusCode > 299 { + return fmt.Errorf("An error occured while deleting a server ID %s %s", d.Id(), string(resp.Body)) + + } + err := waitTillProvisioned(meta, resp.Headers.Get("Location")) + if err != nil { + return err + } + d.SetId("") + return nil +} + +func getSshKey(d *schema.ResourceData, path string) (privatekey string, publickey string, err error) { + pemBytes, err := ioutil.ReadFile(path) + + if err != nil { + return "", "", err + } + + block, _ := pem.Decode(pemBytes) + + if block == nil { + return "", "", errors.New("File " + path + " contains nothing") + } + + priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) + + if err != nil { + return "", "", err + } + + priv_blk := pem.Block{ + Type: "RSA PRIVATE KEY", + Headers: nil, + Bytes: x509.MarshalPKCS1PrivateKey(priv), + } + + pub, err := ssh.NewPublicKey(&priv.PublicKey) + if err != nil { + return "", "", err + } + publickey = string(ssh.MarshalAuthorizedKey(pub)) + privatekey = string(pem.EncodeToMemory(&priv_blk)) + + return privatekey, publickey, nil +} diff --git a/builtin/providers/profitbricks/resource_profitbricks_server_test.go b/builtin/providers/profitbricks/resource_profitbricks_server_test.go new file mode 100644 index 000000000000..d4891ec5ca06 --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_server_test.go @@ -0,0 +1,169 @@ +package profitbricks + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/profitbricks/profitbricks-sdk-go" +) + +func TestAccProfitBricksServer_Basic(t *testing.T) { + var server profitbricks.Server + serverName := "webserver" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDProfitBricksServerDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckProfitbricksServerConfig_basic, serverName), + Check: resource.ComposeTestCheckFunc( + testAccCheckProfitBricksServerExists("profitbricks_server.webserver", &server), + testAccCheckProfitBricksServerAttributes("profitbricks_server.webserver", serverName), + resource.TestCheckResourceAttr("profitbricks_server.webserver", "name", serverName), + ), + }, + resource.TestStep{ + Config: testAccCheckProfitbricksServerConfig_update, + Check: resource.ComposeTestCheckFunc( + testAccCheckProfitBricksServerAttributes("profitbricks_server.webserver", "updated"), + resource.TestCheckResourceAttr("profitbricks_server.webserver", "name", "updated"), + ), + }, + }, + }) +} + +func testAccCheckDProfitBricksServerDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "profitbricks_datacenter" { + continue + } + + resp := profitbricks.GetServer(rs.Primary.Attributes["datacenter_id"], rs.Primary.ID) + + if resp.StatusCode < 299 { + return fmt.Errorf("Server still exists %s %s", rs.Primary.ID, resp.Response) + } + } + + return nil +} + +func testAccCheckProfitBricksServerAttributes(n string, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("testAccCheckProfitBricksServerAttributes: Not found: %s", n) + } + if rs.Primary.Attributes["name"] != name { + return fmt.Errorf("Bad name: %s", rs.Primary.Attributes["name"]) + } + + return nil + } +} + +func testAccCheckProfitBricksServerExists(n string, server *profitbricks.Server) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("testAccCheckProfitBricksServerExists: Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + foundServer := profitbricks.GetServer(rs.Primary.Attributes["datacenter_id"], rs.Primary.ID) + + if foundServer.StatusCode != 200 { + return fmt.Errorf("Error occured while fetching Server: %s", rs.Primary.ID) + } + if foundServer.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + + server = &foundServer + + return nil + } +} + +const testAccCheckProfitbricksServerConfig_basic = ` +resource "profitbricks_datacenter" "foobar" { + name = "server-test" + location = "us/las" +} + +resource "profitbricks_lan" "webserver_lan" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + public = true + name = "public" +} + +resource "profitbricks_server" "webserver" { + name = "%s" + datacenter_id = "${profitbricks_datacenter.foobar.id}" + cores = 1 + ram = 1024 + availability_zone = "ZONE_1" + cpu_family = "AMD_OPTERON" + volume { + name = "system" + size = 5 + disk_type = "SSD" + image_name ="ubuntu-16.04" + image_password = "test1234" +} + nic { + lan = "${profitbricks_lan.webserver_lan.id}" + dhcp = true + firewall_active = true + firewall { + protocol = "TCP" + name = "SSH" + port_range_start = 22 + port_range_end = 22 + } + } +}` + +const testAccCheckProfitbricksServerConfig_update = ` +resource "profitbricks_datacenter" "foobar" { + name = "server-test" + location = "us/las" +} + +resource "profitbricks_server" "webserver" { + name = "updated" + datacenter_id = "${profitbricks_datacenter.foobar.id}" + cores = 1 + ram = 1024 + availability_zone = "ZONE_1" + cpu_family = "AMD_OPTERON" + volume { + name = "system" + size = 5 + disk_type = "SSD" + image_name ="ubuntu-16.04" + image_password = "test1234" +} + nic { + lan = "1" + dhcp = true + firewall_active = true + firewall { + protocol = "TCP" + name = "SSH" + port_range_start = 22 + port_range_end = 22 + } + } +}` diff --git a/builtin/providers/profitbricks/resource_profitbricks_volume.go b/builtin/providers/profitbricks/resource_profitbricks_volume.go new file mode 100644 index 000000000000..afc2a72973a0 --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_volume.go @@ -0,0 +1,235 @@ +package profitbricks + +import ( + "encoding/json" + "fmt" + "github.com/hashicorp/terraform/helper/schema" + "github.com/profitbricks/profitbricks-sdk-go" + "log" +) + +func resourceProfitBricksVolume() *schema.Resource { + return &schema.Resource{ + Create: resourceProfitBricksVolumeCreate, + Read: resourceProfitBricksVolumeRead, + Update: resourceProfitBricksVolumeUpdate, + Delete: resourceProfitBricksVolumeDelete, + Schema: map[string]*schema.Schema{ + "image_name": { + Type: schema.TypeString, + Optional: true, + }, + "size": { + Type: schema.TypeInt, + Required: true, + }, + + "disk_type": { + Type: schema.TypeString, + Required: true, + }, + "image_password": { + Type: schema.TypeString, + Optional: true, + }, + "licence_type": { + Type: schema.TypeString, + Optional: true, + }, + "ssh_key_path": { + Type: schema.TypeString, + Optional: true, + }, + "sshkey": { + Type: schema.TypeString, + Computed: true, + }, + "bus": { + Type: schema.TypeString, + Optional: true, + }, + "name": { + Type: schema.TypeString, + Optional: true, + }, + "server_id": { + Type: schema.TypeString, + Required: true, + }, + "datacenter_id": { + Type: schema.TypeString, + Required: true, + }, + }, + } +} + +func resourceProfitBricksVolumeCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + var err error + dcId := d.Get("datacenter_id").(string) + serverId := d.Get("server_id").(string) + + imagePassword := d.Get("image_password").(string) + sshkey := d.Get("ssh_key_path").(string) + image_name := d.Get("image_name").(string) + + if image_name != "" { + if imagePassword == "" && sshkey == "" { + return fmt.Errorf("'image_password' and 'sshkey' are not provided.") + } + } + + licenceType := d.Get("licence_type").(string) + + if image_name == "" && licenceType == "" { + return fmt.Errorf("Either 'image_name', or 'licenceType' must be set.") + } + + var publicKey string + + if sshkey != "" { + _, publicKey, err = getSshKey(d, sshkey) + if err != nil { + return fmt.Errorf("Error fetching sshkeys (%s)", err) + } + d.Set("sshkey", publicKey) + } + + log.Printf("[INFO] public key: %s", publicKey) + + image := getImageId(d.Get("datacenter_id").(string), image_name, d.Get("disk_type").(string)) + + volume := profitbricks.Volume{ + Properties: profitbricks.VolumeProperties{ + Name: d.Get("name").(string), + Size: d.Get("size").(int), + Type: d.Get("disk_type").(string), + ImagePassword: imagePassword, + Image: image, + Bus: d.Get("bus").(string), + LicenceType: licenceType, + }, + } + + if publicKey != "" { + volume.Properties.SshKeys = []string{publicKey} + + } else { + volume.Properties.SshKeys = nil + } + jsn, _ := json.Marshal(volume) + log.Printf("[INFO] volume: %s", string(jsn)) + + volume = profitbricks.CreateVolume(dcId, volume) + + if volume.StatusCode > 299 { + return fmt.Errorf("An error occured while creating a volume: %s", volume.Response) + } + + err = waitTillProvisioned(meta, volume.Headers.Get("Location")) + if err != nil { + return err + } + volume = profitbricks.AttachVolume(dcId, serverId, volume.Id) + if volume.StatusCode > 299 { + return fmt.Errorf("An error occured while attaching a volume dcId: %s server_id: %s ID: %s Response: %s", dcId, serverId, volume.Id, volume.Response) + } + + err = waitTillProvisioned(meta, volume.Headers.Get("Location")) + if err != nil { + return err + } + d.SetId(volume.Id) + + return resourceProfitBricksVolumeRead(d, meta) +} + +func resourceProfitBricksVolumeRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + dcId := d.Get("datacenter_id").(string) + + volume := profitbricks.GetVolume(dcId, d.Id()) + if volume.StatusCode > 299 { + return fmt.Errorf("An error occured while fetching a volume ID %s %s", d.Id(), volume.Response) + + } + + d.Set("name", volume.Properties.Name) + d.Set("disk_type", volume.Properties.Type) + d.Set("size", volume.Properties.Size) + d.Set("bus", volume.Properties.Bus) + d.Set("image_name", volume.Properties.Image) + + return nil +} + +func resourceProfitBricksVolumeUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + properties := profitbricks.VolumeProperties{} + dcId := d.Get("datacenter_id").(string) + + if d.HasChange("name") { + _, newValue := d.GetChange("name") + properties.Name = newValue.(string) + } + if d.HasChange("disk_type") { + _, newValue := d.GetChange("disk_type") + properties.Type = newValue.(string) + } + if d.HasChange("size") { + _, newValue := d.GetChange("size") + properties.Size = newValue.(int) + } + if d.HasChange("bus") { + _, newValue := d.GetChange("bus") + properties.Bus = newValue.(string) + } + + volume := profitbricks.PatchVolume(dcId, d.Id(), properties) + err := waitTillProvisioned(meta, volume.Headers.Get("Location")) + if err != nil { + return err + } + if volume.StatusCode > 299 { + return fmt.Errorf("An error occured while updating a volume ID %s %s", d.Id(), volume.Response) + + } + err = resourceProfitBricksVolumeRead(d, meta) + if err != nil { + return err + } + d.SetId(d.Get("server_id").(string)) + err = resourceProfitBricksServerRead(d, meta) + if err != nil { + return err + } + + d.SetId(volume.Id) + return nil +} + +func resourceProfitBricksVolumeDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + profitbricks.SetAuth(config.Username, config.Password) + + dcId := d.Get("datacenter_id").(string) + + resp := profitbricks.DeleteVolume(dcId, d.Id()) + if resp.StatusCode > 299 { + return fmt.Errorf("An error occured while deleting a volume ID %s %s", d.Id(), string(resp.Body)) + + } + err := waitTillProvisioned(meta, resp.Headers.Get("Location")) + if err != nil { + return err + } + d.SetId("") + return nil +} diff --git a/builtin/providers/profitbricks/resource_profitbricks_volume_test.go b/builtin/providers/profitbricks/resource_profitbricks_volume_test.go new file mode 100644 index 000000000000..e1586f024f89 --- /dev/null +++ b/builtin/providers/profitbricks/resource_profitbricks_volume_test.go @@ -0,0 +1,189 @@ +package profitbricks + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/profitbricks/profitbricks-sdk-go" +) + +func TestAccProfitBricksVolume_Basic(t *testing.T) { + var volume profitbricks.Volume + volumeName := "volume" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDProfitBricksVolumeDestroyCheck, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: fmt.Sprintf(testAccCheckProfitbricksVolumeConfig_basic, volumeName), + Check: resource.ComposeTestCheckFunc( + testAccCheckProfitBricksVolumeExists("profitbricks_volume.database_volume", &volume), + testAccCheckProfitBricksVolumeAttributes("profitbricks_volume.database_volume", volumeName), + resource.TestCheckResourceAttr("profitbricks_volume.database_volume", "name", volumeName), + ), + }, + resource.TestStep{ + Config: testAccCheckProfitbricksVolumeConfig_update, + Check: resource.ComposeTestCheckFunc( + testAccCheckProfitBricksVolumeAttributes("profitbricks_volume.database_volume", "updated"), + resource.TestCheckResourceAttr("profitbricks_volume.database_volume", "name", "updated"), + ), + }, + }, + }) +} + +func testAccCheckDProfitBricksVolumeDestroyCheck(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "profitbricks_datacenter" { + continue + } + + resp := profitbricks.GetVolume(rs.Primary.Attributes["datacenter_id"], rs.Primary.ID) + + if resp.StatusCode < 299 { + return fmt.Errorf("Volume still exists %s %s", rs.Primary.ID, resp.Response) + } + } + + return nil +} + +func testAccCheckProfitBricksVolumeAttributes(n string, name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("testAccCheckProfitBricksVolumeAttributes: Not found: %s", n) + } + if rs.Primary.Attributes["name"] != name { + return fmt.Errorf("Bad name: %s", rs.Primary.Attributes["name"]) + } + + return nil + } +} + +func testAccCheckProfitBricksVolumeExists(n string, volume *profitbricks.Volume) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + + if !ok { + return fmt.Errorf("testAccCheckProfitBricksVolumeExists: Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Record ID is set") + } + + foundServer := profitbricks.GetVolume(rs.Primary.Attributes["datacenter_id"], rs.Primary.ID) + + if foundServer.StatusCode != 200 { + return fmt.Errorf("Error occured while fetching Volume: %s", rs.Primary.ID) + } + if foundServer.Id != rs.Primary.ID { + return fmt.Errorf("Record not found") + } + + volume = &foundServer + + return nil + } +} + +const testAccCheckProfitbricksVolumeConfig_basic = ` +resource "profitbricks_datacenter" "foobar" { + name = "volume-test" + location = "us/las" +} + +resource "profitbricks_lan" "webserver_lan" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + public = true + name = "public" +} + +resource "profitbricks_server" "webserver" { + name = "webserver" + datacenter_id = "${profitbricks_datacenter.foobar.id}" + cores = 1 + ram = 1024 + availability_zone = "ZONE_1" + cpu_family = "AMD_OPTERON" + volume { + name = "system" + size = 5 + disk_type = "SSD" + image_name ="ubuntu-16.04" + image_password = "test1234" +} + nic { + lan = "${profitbricks_lan.webserver_lan.id}" + dhcp = true + firewall_active = true + firewall { + protocol = "TCP" + name = "SSH" + port_range_start = 22 + port_range_end = 22 + } + } +} + +resource "profitbricks_volume" "database_volume" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + server_id = "${profitbricks_server.webserver.id}" + licence_type = "OTHER" + name = "%s" + size = 5 + disk_type = "SSD" + bus = "VIRTIO" +}` + +const testAccCheckProfitbricksVolumeConfig_update = ` +resource "profitbricks_datacenter" "foobar" { + name = "volume-test" + location = "us/las" +} + +resource "profitbricks_server" "webserver" { + name = "webserver" + datacenter_id = "${profitbricks_datacenter.foobar.id}" + cores = 1 + ram = 1024 + availability_zone = "ZONE_1" + cpu_family = "AMD_OPTERON" + volume { + name = "system" + size = 5 + disk_type = "SSD" + image_name ="ubuntu-16.04" + image_password = "test1234" +} + nic { + lan = "1" + dhcp = true + firewall_active = true + firewall { + protocol = "TCP" + name = "SSH" + port_range_start = 22 + port_range_end = 22 + } + } +} + +resource "profitbricks_volume" "database_volume" { + datacenter_id = "${profitbricks_datacenter.foobar.id}" + server_id = "${profitbricks_server.webserver.id}" + licence_type = "OTHER" + name = "updated" + size = 5 + disk_type = "SSD" + bus = "VIRTIO" +}` diff --git a/command/internal_plugin_list.go b/command/internal_plugin_list.go index f94367acc91f..95ca582b47bc 100644 --- a/command/internal_plugin_list.go +++ b/command/internal_plugin_list.go @@ -46,6 +46,7 @@ import ( pagerdutyprovider "github.com/hashicorp/terraform/builtin/providers/pagerduty" postgresqlprovider "github.com/hashicorp/terraform/builtin/providers/postgresql" powerdnsprovider "github.com/hashicorp/terraform/builtin/providers/powerdns" + profitbricksprovider "github.com/hashicorp/terraform/builtin/providers/profitbricks" rabbitmqprovider "github.com/hashicorp/terraform/builtin/providers/rabbitmq" rancherprovider "github.com/hashicorp/terraform/builtin/providers/rancher" randomprovider "github.com/hashicorp/terraform/builtin/providers/random" @@ -112,6 +113,7 @@ var InternalProviders = map[string]plugin.ProviderFunc{ "pagerduty": pagerdutyprovider.Provider, "postgresql": postgresqlprovider.Provider, "powerdns": powerdnsprovider.Provider, + "profitbricks": profitbricksprovider.Provider, "rabbitmq": rabbitmqprovider.Provider, "rancher": rancherprovider.Provider, "random": randomprovider.Provider, diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/LICENSE b/vendor/github.com/profitbricks/profitbricks-sdk-go/LICENSE new file mode 100644 index 000000000000..42c49ecc259d --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015 ProfitBricks GmbH + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/README.md b/vendor/github.com/profitbricks/profitbricks-sdk-go/README.md new file mode 100644 index 000000000000..b41efd6794d8 --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/README.md @@ -0,0 +1,342 @@ +# Go SDK + +The ProfitBricks Client Library for [Go](https://www.golang.org/) provides you with access to the ProfitBricks REST API. It is designed for developers who are building applications in Go. + +This guide will walk you through getting setup with the library and performing various actions against the API. + +# Table of Contents +* [Concepts](#concepts) +* [Getting Started](#getting-started) +* [Installation](#installation) +* [How to: Create Data Center](#how-to-create-data-center) +* [How to: Delete Data Center](#how-to-delete-data-center) +* [How to: Create Server](#how-to-create-server) +* [How to: List Available Images](#how-to-list-available-images) +* [How to: Create Storage Volume](#how-to-create-storage-volume) +* [How to: Update Cores and Memory](#how-to-update-cores-and-memory) +* [How to: Attach or Detach Storage Volume](#how-to-attach-or-detach-storage-volume) +* [How to: List Servers, Volumes, and Data Centers](#how-to-list-servers-volumes-and-data-centers) +* [Example](#example) +* [Return Types](#return-types) +* [Support](#support) + + +# Concepts + +The Go SDK wraps the latest version of the ProfitBricks REST API. All API operations are performed over SSL and authenticated using your ProfitBricks portal credentials. The API can be accessed within an instance running in ProfitBricks or directly over the Internet from any application that can send an HTTPS request and receive an HTTPS response. + +# Getting Started + +Before you begin you will need to have [signed-up](https://www.profitbricks.com/signup) for a ProfitBricks account. The credentials you setup during sign-up will be used to authenticate against the API. + +Install the Go language from: [Go Installation](https://golang.org/doc/install) + +The `GOPATH` environment variable specifies the location of your Go workspace. It is likely the only environment variable you'll need to set when developing Go code. This is an example of pointing to a workspace configured underneath your home directory: + +``` +mkdir -p ~/go/bin +export GOPATH=~/go +export GOBIN=$GOPATH/bin +export PATH=$PATH:$GOBIN +``` + +# Installation + +The following go command will download `profitbricks-sdk-go` to your configured `GOPATH`: + +```go +go get "github.com/profitbricks/profitbricks-sdk-go" +``` + +The source code of the package will be located at: + + $GOBIN\src\profitbricks-sdk-go + +Create main package file *example.go*: + +```go +package main + +import ( + "fmt" +) + +func main() { +} +``` + +Import GO SDK: + +```go +import( + "github.com/profitbricks/profitbricks-sdk-go" +) +``` + +Add your credentials for connecting to ProfitBricks: + +```go +profitbricks.SetAuth("username", "password") +``` + +Set depth: + +```go +profitbricks.SetDepth("5") +``` + +Depth controls the amount of data returned from the REST server ( range 1-5 ). The larger the number the more information is returned from the server. This is especially useful if you are looking for the information in the nested objects. + +**Caution**: You will want to ensure you follow security best practices when using credentials within your code or stored in a file. + +# How To's + +## How To: Create Data Center + +ProfitBricks introduces the concept of Data Centers. These are logically separated from one another and allow you to have a self-contained environment for all servers, volumes, networking, snapshots, and so forth. The goal is to give you the same experience as you would have if you were running your own physical data center. + +The following code example shows you how to programmatically create a data center: + +```go +dcrequest := profitbricks.Datacenter{ + Properties: profitbricks.DatacenterProperties{ + Name: "example.go3", + Description: "description", + Location: "us/lasdev", + }, + } + +datacenter := profitbricks.CreateDatacenter(dcrequest) +``` + +## How To: Create Data Center with Multiple Resources + +To create a complex Data Center you would do this. As you can see, you can create quite a few of the objects you will need later all in one request.: + +```go +datacenter := model.Datacenter{ + Properties: model.DatacenterProperties{ + Name: "composite test", + Location:location, + }, + Entities:model.DatacenterEntities{ + Servers: &model.Servers{ + Items:[]model.Server{ + model.Server{ + Properties: model.ServerProperties{ + Name : "server1", + Ram: 2048, + Cores: 1, + }, + Entities:model.ServerEntities{ + Volumes: &model.AttachedVolumes{ + Items:[]model.Volume{ + model.Volume{ + Properties: model.VolumeProperties{ + Type_:"HDD", + Size:10, + Name:"volume1", + Image:"1f46a4a3-3f47-11e6-91c6-52540005ab80", + Bus:"VIRTIO", + ImagePassword:"test1234", + SshKeys: []string{"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCoLVLHON4BSK3D8L4H79aFo..."}, + }, + }, + }, + }, + Nics: &model.Nics{ + Items: []model.Nic{ + model.Nic{ + Properties: model.NicProperties{ + Name : "nic", + Lan : "1", + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + +dc := CompositeCreateDatacenter(datacenter) + +``` + + +## How To: Delete Data Center + +You will want to exercise a bit of caution here. Removing a data center will destroy all objects contained within that data center -- servers, volumes, snapshots, and so on. + +The code to remove a data center is as follows. This example assumes you want to remove previously data center: + +```go +profitbricks.DeleteDatacenter(response.Id) +``` + +## How To: Create Server + +The server create method has a list of required parameters followed by a hash of optional parameters. The optional parameters are specified within the "options" hash and the variable names match the [REST API](https://devops.profitbricks.com/api/rest/) parameters. + +The following example shows you how to create a new server in the data center created above: + +```go +req := profitbricks.Server{ + Properties: profitbricks.ServerProperties{ + Name: "go01", + Ram: 1024, + Cores: 2, + }, +} +server := CreateServer(datacenter.Id, req) +``` + +## How To: List Available Images + +A list of disk and ISO images are available from ProfitBricks for immediate use. These can be easily viewed and selected. The following shows you how to get a list of images. This list represents both CDROM images and HDD images. + +```go +images := profitbricks.ListImages() +``` + +This will return a [collection](#Collection) object + +## How To: Create Storage Volume + +ProfitBricks allows for the creation of multiple storage volumes that can be attached and detached as needed. It is useful to attach an image when creating a storage volume. The storage size is in gigabytes. + +```go +volumerequest := profitbricks.Volume{ + Properties: profitbricks.VolumeProperties{ + Size: 1, + Name: "Volume Test", + LicenceType: "LINUX", + Type: "HDD", + }, +} + +storage := CreateVolume(datacenter.Id, volumerequest) +``` + +## How To: Update Cores and Memory + +ProfitBricks allows users to dynamically update cores, memory, and disk independently of each other. This removes the restriction of needing to upgrade to the next size available size to receive an increase in memory. You can now simply increase the instances memory keeping your costs in-line with your resource needs. + +Note: The memory parameter value must be a multiple of 256, e.g. 256, 512, 768, 1024, and so forth. + +The following code illustrates how you can update cores and memory: + +```go +serverupdaterequest := profitbricks.ServerProperties{ + Cores: 1, + Ram: 256, +} + +resp := PatchServer(datacenter.Id, server.Id, serverupdaterequest) +``` + +## How To: Attach or Detach Storage Volume + +ProfitBricks allows for the creation of multiple storage volumes. You can detach and reattach these on the fly. This allows for various scenarios such as re-attaching a failed OS disk to another server for possible recovery or moving a volume to another location and spinning it up. + +The following illustrates how you would attach and detach a volume and CDROM to/from a server: + +```go +profitbricks.AttachVolume(datacenter.Id, server.Id, volume.Id) +profitbricks.AttachCdrom(datacenter.Id, server.Id, images.Items[0].Id) + +profitbricks.DetachVolume(datacenter.Id, server.Id, volume.Id) +profitbricks.DetachCdrom(datacenter.Id, server.Id, images.Items[0].Id) +``` + +## How To: List Servers, Volumes, and Data Centers + +Go SDK provides standard functions for retrieving a list of volumes, servers, and datacenters. + +The following code illustrates how to pull these three list types: + +```go +volumes := profitbricks.ListVolumes(datacenter.Id) + +servers := profitbricks.ListServers(datacenter.Id) + +datacenters := profitbricks.ListDatacenters() +``` + +## Example + +```go +package main + +import ( + "fmt" + "time" + + "github.com/profitbricks/profitbricks-sdk-go" +) + +func main() { + + //Sets username and password + profitbricks.SetAuth("username", "password") + //Sets depth. + profitbricks.SetDepth("5") + + dcrequest := profitbricks.Datacenter{ + Properties: profitbricks.DatacenterProperties{ + Name: "example.go3", + Description: "description", + Location: "us/lasdev", + }, + } + + datacenter := profitbricks.CreateDatacenter(dcrequest) + + serverrequest := profitbricks.Server{ + Properties: profitbricks.ServerProperties{ + Name: "go01", + Ram: 1024, + Cores: 2, + }, + } + server := profitbricks.CreateServer(datacenter.Id, serverrequest) + + volumerequest := profitbricks.Volume{ + Properties: profitbricks.VolumeProperties{ + Size: 1, + Name: "Volume Test", + LicenceType: "LINUX", + Type: "HDD", + }, + } + + storage := profitbricks.CreateVolume(datacenter.Id, volumerequest) + + serverupdaterequest := profitbricks.ServerProperties{ + Name: "go01renamed", + Cores: 1, + Ram: 256, + } + + profitbricks.PatchServer(datacenter.Id, server.Id, serverupdaterequest) + //It takes a moment for a volume to be provisioned so we wait. + time.Sleep(60 * time.Second) + + profitbricks.AttachVolume(datacenter.Id, server.Id, storage.Id) + + volumes := profitbricks.ListVolumes(datacenter.Id) + fmt.Println(volumes.Items) + servers := profitbricks.ListServers(datacenter.Id) + fmt.Println(servers.Items) + datacenters := profitbricks.ListDatacenters() + fmt.Println(datacenters.Items) + + profitbricks.DeleteServer(datacenter.Id, server.Id) + profitbricks.DeleteDatacenter(datacenter.Id) +} +``` + +# Support +You are welcome to contact us with questions or comments at [ProfitBricks DevOps Central](https://devops.profitbricks.com/). Please report any issues via [GitHub's issue tracker](https://github.com/profitbricks/profitbricks-sdk-go/issues). \ No newline at end of file diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/config.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/config.go new file mode 100644 index 000000000000..5671089519f9 --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/config.go @@ -0,0 +1,23 @@ +package profitbricks + +// Endpoint is the base url for REST requests . +var Endpoint = "https://api.profitbricks.com/rest/v2" + +// Username for authentication . +var Username string + +// Password for authentication . +var Passwd string + +// SetEndpoint is used to set the REST Endpoint. Endpoint is declared in config.go +func SetEndpoint(newendpoint string) string { + Endpoint = newendpoint + return Endpoint +} + +// SetAuth is used to set Username and Passwd. Username and Passwd are declared in config.go + +func SetAuth(u, p string) { + Username = u + Passwd = p +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/datacenter.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/datacenter.go new file mode 100644 index 000000000000..eb3d9094f8fe --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/datacenter.go @@ -0,0 +1,121 @@ +package profitbricks + +import ( + "bytes" + "encoding/json" + "net/http" + "time" +) + +type Datacenter struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` + Properties DatacenterProperties `json:"properties,omitempty"` + Entities DatacenterEntities `json:"entities,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type DatacenterElementMetadata struct { + CreatedDate time.Time `json:"createdDate,omitempty"` + CreatedBy string `json:"createdBy,omitempty"` + Etag string `json:"etag,omitempty"` + LastModifiedDate time.Time `json:"lastModifiedDate,omitempty"` + LastModifiedBy string `json:"lastModifiedBy,omitempty"` + State string `json:"state,omitempty"` +} + +type DatacenterProperties struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + Location string `json:"location,omitempty"` + Version int32 `json:"version,omitempty"` +} + +type DatacenterEntities struct { + Servers *Servers `json:"servers,omitempty"` + Volumes *Volumes `json:"volumes,omitempty"` + Loadbalancers *Loadbalancers `json:"loadbalancers,omitempty"` + Lans *Lans `json:"lans,omitempty"` +} + +type Datacenters struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Items []Datacenter `json:"items,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +func ListDatacenters() Datacenters { + path := dc_col_path() + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + resp := do(req) + return toDataCenters(resp) +} + +func CreateDatacenter(dc Datacenter) Datacenter { + obj, _ := json.Marshal(dc) + path := dc_col_path() + url := mk_url(path) + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj)) + req.Header.Add("Content-Type", FullHeader) + + return toDataCenter(do(req)) +} + +func CompositeCreateDatacenter(datacenter Datacenter) Datacenter { + obj, _ := json.Marshal(datacenter) + path := dc_col_path() + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj)) + req.Header.Add("Content-Type", FullHeader) + return toDataCenter(do(req)) +} + +func GetDatacenter(dcid string) Datacenter { + path := dc_path(dcid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toDataCenter(do(req)) +} + +func PatchDatacenter(dcid string, obj DatacenterProperties) Datacenter { + jason_patch := []byte(MkJson(obj)) + path := dc_path(dcid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jason_patch)) + req.Header.Add("Content-Type", PatchHeader) + return toDataCenter(do(req)) +} + +func DeleteDatacenter(dcid string) Resp { + path := dc_path(dcid) + return is_delete(path) +} + +func toDataCenter(resp Resp) Datacenter { + var dc Datacenter + json.Unmarshal(resp.Body, &dc) + dc.Response = string(resp.Body) + dc.Headers = &resp.Headers + dc.StatusCode = resp.StatusCode + return dc +} + +func toDataCenters(resp Resp) Datacenters { + var col Datacenters + json.Unmarshal(resp.Body, &col) + col.Response = string(resp.Body) + col.Headers = &resp.Headers + col.StatusCode = resp.StatusCode + return col +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/doc.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/doc.go new file mode 100644 index 000000000000..f19e26da9b5f --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/doc.go @@ -0,0 +1,6 @@ +/* +Package profitbricks is a client library for interacting with Profitbricks RESTful APIs. + + +*/ +package profitbricks diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/firewallrule.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/firewallrule.go new file mode 100644 index 000000000000..c175121a5553 --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/firewallrule.go @@ -0,0 +1,99 @@ +package profitbricks + +import ( + "bytes" + "encoding/json" + "net/http" +) + +type FirewallRule struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` + Properties FirewallruleProperties `json:"properties,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type FirewallruleProperties struct { + Name string `json:"name,omitempty"` + Protocol string `json:"protocol,omitempty"` + SourceMac string `json:"sourceMac,omitempty"` + SourceIp string `json:"sourceIp,omitempty"` + TargetIp string `json:"targetIp,omitempty"` + IcmpCode interface{} `json:"icmpCode,omitempty"` + IcmpType interface{} `json:"icmpType,omitempty"` + PortRangeStart interface{} `json:"portRangeStart,omitempty"` + PortRangeEnd interface{} `json:"portRangeEnd,omitempty"` +} + +type FirewallRules struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Items []FirewallRule `json:"items,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +func ListFirewallRules(dcId string, serverid string, nicId string) FirewallRules { + path := fwrule_col_path(dcId, serverid, nicId) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + resp := do(req) + return toFirewallRules(resp) +} + +func GetFirewallRule(dcid string, srvid string, nicId string, fwId string) FirewallRule { + path := fwrule_path(dcid, srvid, nicId, fwId) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + resp := do(req) + return toFirewallRule(resp) +} + +func CreateFirewallRule(dcid string, srvid string, nicId string, fw FirewallRule) FirewallRule { + path := fwrule_col_path(dcid, srvid, nicId) + url := mk_url(path) + `?depth=` + Depth + obj, _ := json.Marshal(fw) + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj)) + req.Header.Add("Content-Type", FullHeader) + return toFirewallRule(do(req)) +} + +func PatchFirewallRule(dcid string, srvid string, nicId string, fwId string, obj FirewallruleProperties) FirewallRule { + jason_patch := []byte(MkJson(obj)) + path := fwrule_path(dcid, srvid, nicId, fwId) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jason_patch)) + req.Header.Add("Content-Type", PatchHeader) + return toFirewallRule(do(req)) +} + +func DeleteFirewallRule(dcid string, srvid string, nicId string, fwId string) Resp { + path := fwrule_path(dcid, srvid, nicId, fwId) + return is_delete(path) +} + +func toFirewallRule(resp Resp) FirewallRule { + var dc FirewallRule + json.Unmarshal(resp.Body, &dc) + dc.Response = string(resp.Body) + dc.Headers = &resp.Headers + dc.StatusCode = resp.StatusCode + return dc +} + +func toFirewallRules(resp Resp) FirewallRules { + var col FirewallRules + json.Unmarshal(resp.Body, &col) + col.Response = string(resp.Body) + col.Headers = &resp.Headers + col.StatusCode = resp.StatusCode + return col +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/image.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/image.go new file mode 100644 index 000000000000..95ec9e25a9fd --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/image.go @@ -0,0 +1,98 @@ +package profitbricks + +import ( + "encoding/json" + "net/http" +) + +type Image struct { + Id string `json:"id,omitempty"` + Type string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` + Properties ImageProperties `json:"properties,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type ImageProperties struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + Location string `json:"location,omitempty"` + Size int `json:"size,omitempty"` + CpuHotPlug bool `json:"cpuHotPlug,omitempty"` + CpuHotUnplug bool `json:"cpuHotUnplug,omitempty"` + RamHotPlug bool `json:"ramHotPlug,omitempty"` + RamHotUnplug bool `json:"ramHotUnplug,omitempty"` + NicHotPlug bool `json:"nicHotPlug,omitempty"` + NicHotUnplug bool `json:"nicHotUnplug,omitempty"` + DiscVirtioHotPlug bool `json:"discVirtioHotPlug,omitempty"` + DiscVirtioHotUnplug bool `json:"discVirtioHotUnplug,omitempty"` + DiscScsiHotPlug bool `json:"discScsiHotPlug,omitempty"` + DiscScsiHotUnplug bool `json:"discScsiHotUnplug,omitempty"` + LicenceType string `json:"licenceType,omitempty"` + ImageType string `json:"imageType,omitempty"` + Public bool `json:"public,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type Images struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Items []Image `json:"items,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type Cdroms struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Items []Image `json:"items,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +// ListImages returns an Collection struct +func ListImages() Images { + path := image_col_path() + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + resp := do(req) + return toImages(resp) +} + +// GetImage returns an Instance struct where id ==imageid +func GetImage(imageid string) Image { + path := image_path(imageid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + resp := do(req) + return toImage(resp) +} + +func toImage(resp Resp) Image { + var image Image + json.Unmarshal(resp.Body, &image) + image.Response = string(resp.Body) + image.Headers = &resp.Headers + image.StatusCode = resp.StatusCode + return image +} + +func toImages(resp Resp) Images { + var col Images + json.Unmarshal(resp.Body, &col) + col.Response = string(resp.Body) + col.Headers = &resp.Headers + col.StatusCode = resp.StatusCode + return col +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/ipblock.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/ipblock.go new file mode 100644 index 000000000000..1b78262bb181 --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/ipblock.go @@ -0,0 +1,82 @@ +package profitbricks + +import ( + "bytes" + "encoding/json" + "net/http" +) + +type IpBlock struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` + Properties IpBlockProperties `json:"properties,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type IpBlockProperties struct { + Ips []string `json:"ips,omitempty"` + Location string `json:"location,omitempty"` + Size int `json:"size,omitempty"` +} + +type IpBlocks struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Items []IpBlock `json:"items,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +// ListIpBlocks +func ListIpBlocks() IpBlocks { + path := ipblock_col_path() + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toIpBlocks(do(req)) +} + +func ReserveIpBlock(request IpBlock) IpBlock { + obj, _ := json.Marshal(request) + path := ipblock_col_path() + url := mk_url(path) + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj)) + req.Header.Add("Content-Type", FullHeader) + return toIpBlock(do(req)) +} +func GetIpBlock(ipblockid string) IpBlock { + path := ipblock_path(ipblockid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toIpBlock(do(req)) +} + +func ReleaseIpBlock(ipblockid string) Resp { + path := ipblock_path(ipblockid) + return is_delete(path) +} + +func toIpBlock(resp Resp) IpBlock { + var obj IpBlock + json.Unmarshal(resp.Body, &obj) + obj.Response = string(resp.Body) + obj.Headers = &resp.Headers + obj.StatusCode = resp.StatusCode + return obj +} + +func toIpBlocks(resp Resp) IpBlocks { + var col IpBlocks + json.Unmarshal(resp.Body, &col) + col.Response = string(resp.Body) + col.Headers = &resp.Headers + col.StatusCode = resp.StatusCode + return col +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/lan.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/lan.go new file mode 100644 index 000000000000..f29310bf9012 --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/lan.go @@ -0,0 +1,109 @@ +package profitbricks + +import ( + "bytes" + "encoding/json" + "net/http" +) + +type Lan struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` + Properties LanProperties `json:"properties,omitempty"` + Entities *LanEntities `json:"entities,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type LanProperties struct { + Name string `json:"name,omitempty"` + Public interface{} `json:"public,omitempty"` +} + +type LanEntities struct { + Nics *LanNics `json:"nics,omitempty"` +} + +type LanNics struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Items []Nic `json:"items,omitempty"` +} + +type Lans struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Items []Lan `json:"items,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +// ListLan returns a Collection for lans in the Datacenter +func ListLans(dcid string) Lans { + path := lan_col_path(dcid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toLans(do(req)) +} + +// CreateLan creates a lan in the datacenter +// from a jason []byte and returns a Instance struct +func CreateLan(dcid string, request Lan) Lan { + obj, _ := json.Marshal(request) + path := lan_col_path(dcid) + url := mk_url(path) + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj)) + req.Header.Add("Content-Type", FullHeader) + return toLan(do(req)) +} + +// GetLan pulls data for the lan where id = lanid returns an Instance struct +func GetLan(dcid, lanid string) Lan { + path := lan_path(dcid, lanid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toLan(do(req)) +} + +// PatchLan does a partial update to a lan using json from []byte jason +// returns a Instance struct +func PatchLan(dcid string, lanid string, obj LanProperties) Lan { + jason := []byte(MkJson(obj)) + path := lan_path(dcid, lanid) + url := mk_url(path) + req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jason)) + req.Header.Add("Content-Type", PatchHeader) + return toLan(do(req)) +} + +// DeleteLan deletes a lan where id == lanid +func DeleteLan(dcid, lanid string) Resp { + path := lan_path(dcid, lanid) + return is_delete(path) +} + +func toLan(resp Resp) Lan { + var lan Lan + json.Unmarshal(resp.Body, &lan) + lan.Response = string(resp.Body) + lan.Headers = &resp.Headers + lan.StatusCode = resp.StatusCode + return lan +} + +func toLans(resp Resp) Lans { + var col Lans + json.Unmarshal(resp.Body, &col) + col.Response = string(resp.Body) + col.Headers = &resp.Headers + col.StatusCode = resp.StatusCode + return col +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/loadbalancer.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/loadbalancer.go new file mode 100644 index 000000000000..2a5b3389f5d9 --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/loadbalancer.go @@ -0,0 +1,145 @@ +package profitbricks + +import ( + "bytes" + "encoding/json" + "net/http" +) + +type Loadbalancer struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` + Properties LoadbalancerProperties `json:"properties,omitempty"` + Entities LoadbalancerEntities `json:"entities,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type LoadbalancerProperties struct { + Name string `json:"name,omitempty"` + Ip string `json:"ip,omitempty"` + Dhcp bool `json:"dhcp,omitempty"` +} + +type LoadbalancerEntities struct { + Balancednics *BalancedNics `json:"balancednics,omitempty"` +} + +type BalancedNics struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Items []Nic `json:"items,omitempty"` +} + +type Loadbalancers struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Items []Loadbalancer `json:"items,omitempty"` + + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type LoablanacerCreateRequest struct { + LoadbalancerProperties `json:"properties"` +} + +// Listloadbalancers returns a Collection struct +// for loadbalancers in the Datacenter +func ListLoadbalancers(dcid string) Loadbalancers { + path := lbal_col_path(dcid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toLoadbalancers(do(req)) +} + +// Createloadbalancer creates a loadbalancer in the datacenter +//from a jason []byte and returns a Instance struct +func CreateLoadbalancer(dcid string, request Loadbalancer) Loadbalancer { + obj, _ := json.Marshal(request) + path := lbal_col_path(dcid) + url := mk_url(path) + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj)) + req.Header.Add("Content-Type", FullHeader) + return toLoadbalancer(do(req)) +} + +// GetLoadbalancer pulls data for the Loadbalancer +// where id = lbalid returns a Instance struct +func GetLoadbalancer(dcid, lbalid string) Loadbalancer { + path := lbal_path(dcid, lbalid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toLoadbalancer(do(req)) +} + +func PatchLoadbalancer(dcid string, lbalid string, obj LoadbalancerProperties) Loadbalancer { + jason := []byte(MkJson(obj)) + path := lbal_path(dcid, lbalid) + url := mk_url(path) + req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jason)) + req.Header.Add("Content-Type", PatchHeader) + return toLoadbalancer(do(req)) +} + +func DeleteLoadbalancer(dcid, lbalid string) Resp { + path := lbal_path(dcid, lbalid) + return is_delete(path) +} + +func ListBalancedNics(dcid, lbalid string) Nics { + path := balnic_col_path(dcid, lbalid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toNics(do(req)) +} + +func AssociateNic(dcid string, lbalid string, nicid string) Nic { + sm := map[string]string{"id": nicid} + jason := []byte(MkJson(sm)) + path := balnic_col_path(dcid, lbalid) + url := mk_url(path) + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jason)) + req.Header.Add("Content-Type", FullHeader) + return toNic(do(req)) +} + +func GetBalancedNic(dcid, lbalid, balnicid string) Nic { + path := balnic_path(dcid, lbalid, balnicid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toNic(do(req)) +} + +func DeleteBalancedNic(dcid, lbalid, balnicid string) Resp { + path := balnic_path(dcid, lbalid, balnicid) + return is_delete(path) +} + +func toLoadbalancer(resp Resp) Loadbalancer { + var server Loadbalancer + json.Unmarshal(resp.Body, &server) + server.Response = string(resp.Body) + server.Headers = &resp.Headers + server.StatusCode = resp.StatusCode + return server +} + +func toLoadbalancers(resp Resp) Loadbalancers { + var col Loadbalancers + json.Unmarshal(resp.Body, &col) + col.Response = string(resp.Body) + col.Headers = &resp.Headers + col.StatusCode = resp.StatusCode + return col +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/location.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/location.go new file mode 100644 index 000000000000..279429464123 --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/location.go @@ -0,0 +1,65 @@ +package profitbricks + +import ( + "encoding/json" + "net/http" +) + +type Location struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Metadata DatacenterElementMetadata `json:"metadata,omitempty"` + Properties Properties `json:"properties,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type Locations struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Items []Location `json:"items,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type Properties struct { + Name string `json:"name,omitempty"` +} + +// ListLocations returns location collection data +func ListLocations() Locations { + url := mk_url(location_col_path()) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toLocations(do(req)) +} + +// GetLocation returns location data +func GetLocation(locid string) Location { + url := mk_url(location_path(locid)) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toLocation(do(req)) +} + +func toLocation(resp Resp) Location { + var obj Location + json.Unmarshal(resp.Body, &obj) + obj.Response = string(resp.Body) + obj.Headers = &resp.Headers + obj.StatusCode = resp.StatusCode + return obj +} + +func toLocations(resp Resp) Locations { + var col Locations + json.Unmarshal(resp.Body, &col) + col.Response = string(resp.Body) + col.Headers = &resp.Headers + col.StatusCode = resp.StatusCode + return col +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/nic.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/nic.go new file mode 100644 index 000000000000..74764f56b716 --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/nic.go @@ -0,0 +1,110 @@ +package profitbricks + +import ( + "bytes" + "encoding/json" + "net/http" +) + +type Nic struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` + Properties NicProperties `json:"properties,omitempty"` + Entities *NicEntities `json:"entities,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type NicProperties struct { + Name string `json:"name,omitempty"` + Mac string `json:"mac,omitempty"` + Ips []string `json:"ips,omitempty"` + Dhcp bool `json:"dhcp,omitempty"` + Lan int `json:"lan,omitempty"` + FirewallActive bool `json:"firewallActive,omitempty"` +} + +type NicEntities struct { + Firewallrules *FirewallRules `json:"firewallrules,omitempty"` +} + +type Nics struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Items []Nic `json:"items,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type NicCreateRequest struct { + NicProperties `json:"properties"` +} + +// ListNics returns a Nics struct collection +func ListNics(dcid, srvid string) Nics { + path := nic_col_path(dcid, srvid) + `?depth=` + Depth + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toNics(do(req)) +} + +// CreateNic creates a nic on a server +// from a jason []byte and returns a Instance struct +func CreateNic(dcid string, srvid string, request Nic) Nic { + obj, _ := json.Marshal(request) + path := nic_col_path(dcid, srvid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj)) + req.Header.Add("Content-Type", FullHeader) + return toNic(do(req)) +} + +// GetNic pulls data for the nic where id = srvid returns a Instance struct +func GetNic(dcid, srvid, nicid string) Nic { + path := nic_path(dcid, srvid, nicid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toNic(do(req)) +} + +// PatchNic partial update of nic properties passed in as jason []byte +// Returns Instance struct +func PatchNic(dcid string, srvid string, nicid string, obj NicProperties) Nic { + jason := []byte(MkJson(obj)) + path := nic_path(dcid, srvid, nicid) + url := mk_url(path) + req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jason)) + req.Header.Add("Content-Type", PatchHeader) + return toNic(do(req)) +} + +// DeleteNic deletes the nic where id=nicid and returns a Resp struct +func DeleteNic(dcid, srvid, nicid string) Resp { + path := nic_path(dcid, srvid, nicid) + return is_delete(path) +} + +func toNic(resp Resp) Nic { + var obj Nic + json.Unmarshal(resp.Body, &obj) + obj.Response = string(resp.Body) + obj.Headers = &resp.Headers + obj.StatusCode = resp.StatusCode + return obj +} + +func toNics(resp Resp) Nics { + var col Nics + json.Unmarshal(resp.Body, &col) + col.Response = string(resp.Body) + col.Headers = &resp.Headers + col.StatusCode = resp.StatusCode + return col +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/paths.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/paths.go new file mode 100644 index 000000000000..3b3c7f50dfaa --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/paths.go @@ -0,0 +1,173 @@ +package profitbricks + +// slash returns "/" great for making url paths +func slash(str string) string { + return "/" + str +} + +// dc_col_path returns the string "/datacenters" +func dc_col_path() string { + return slash("datacenters") +} + +// dc_path returns the string "/datacenters/" +func dc_path(dcid string) string { + return dc_col_path() + slash(dcid) +} + +// image_col_path returns the string" /images" +func image_col_path() string { + return slash("images") +} + +// image_path returns the string"/images/" +func image_path(imageid string) string { + return image_col_path() + slash(imageid) +} + +// ipblock_col_path returns the string "/ipblocks" +func ipblock_col_path() string { + return slash("ipblocks") +} + +// ipblock_path returns the string "/ipblocks/" +func ipblock_path(ipblockid string) string { + return ipblock_col_path() + slash(ipblockid) +} + +// location_col_path returns the string "/locations" +func location_col_path() string { + return slash("locations") +} + +// location_path returns the string "/locations/" +func location_path(locid string) string { + return location_col_path() + slash(locid) +} + +// request_col_path returns the string "/requests" +func request_col_path() string { + return slash("requests") +} + +// request_path returns the string "/requests/" +func request_path(requestid string) string { + return request_col_path() + slash(requestid) +} + +// request_status_path returns the string "/requests/status" +func request_status_path(requestid string) string { + return request_path(requestid) + slash("status") +} + +// snapshot_col_path returns the string "/snapshots" +func snapshot_col_path() string { + return slash("snapshots") +} + +// snapshot_path returns the string "/snapshots/" +func snapshot_path(snapid string) string { + return snapshot_col_path() + slash(snapid) +} + +// lan_col_path returns the string "/datacenters//lans" +func lan_col_path(dcid string) string { + return dc_path(dcid) + slash("lans") +} + +// lan_path returns the string "/datacenters//lans/" +func lan_path(dcid, lanid string) string { + return lan_col_path(dcid) + slash(lanid) +} + +// lbal_col_path returns the string "/loadbalancers" +func lbal_col_path(dcid string) string { + return dc_path(dcid) + slash("loadbalancers") +} + +// lbalpath returns the string "/loadbalancers/" +func lbal_path(dcid, lbalid string) string { + return lbal_col_path(dcid) + slash(lbalid) +} + +// server_col_path returns the string "/datacenters//servers" +func server_col_path(dcid string) string { + return dc_path(dcid) + slash("servers") +} + +// server_path returns the string "/datacenters//servers/" +func server_path(dcid, srvid string) string { + return server_col_path(dcid) + slash(srvid) +} + +// server_cmd_path returns the string "/datacenters//servers//" +func server_command_path(dcid, srvid, cmd string) string { + return server_path(dcid, srvid) + slash(cmd) +} + +// volume_col_path returns the string "/volumes" +func volume_col_path(dcid string) string { + return dc_path(dcid) + slash("volumes") +} + +// volume_path returns the string "/volumes/" +func volume_path(dcid, volid string) string { + return volume_col_path(dcid) + slash(volid) +} + +// lan_nic_col_path returns the string /datacenters//lans//nics +func lan_nic_col(dcid, lanid string) string { + return lan_path(dcid, lanid) + slash("nics") + +} + +// balnic_col_path returns the string "/loadbalancers//balancednics" +func balnic_col_path(dcid, lbalid string) string { + return lbal_path(dcid, lbalid) + slash("balancednics") +} + +// balnic_path returns the string "/loadbalancers//balancednics" +func balnic_path(dcid, lbalid, balnicid string) string { + return balnic_col_path(dcid, lbalid) + slash(balnicid) +} + +// server_cdrom_col_path returns the string "/datacenters//servers//cdroms" +func server_cdrom_col_path(dcid, srvid string) string { + return server_path(dcid, srvid) + slash("cdroms") +} + +// server_cdrom_path returns the string "/datacenters//servers//cdroms/" +func server_cdrom_path(dcid, srvid, cdid string) string { + return server_cdrom_col_path(dcid, srvid) + slash(cdid) +} + +// server_volume_col_path returns the string "/datacenters//servers//volumes" +func server_volume_col_path(dcid, srvid string) string { + return server_path(dcid, srvid) + slash("volumes") +} + +// server_volume_path returns the string "/datacenters//servers//volumes/" +func server_volume_path(dcid, srvid, volid string) string { + return server_volume_col_path(dcid, srvid) + slash(volid) +} + +// nic_path returns the string "/datacenters//servers//nics" +func nic_col_path(dcid, srvid string) string { + return server_path(dcid, srvid) + slash("nics") +} + +// nic_path returns the string "/datacenters//servers//nics/" +func nic_path(dcid, srvid, nicid string) string { + return nic_col_path(dcid, srvid) + slash(nicid) +} + +// fwrule_col_path returns the string "/datacenters//servers//nics//firewallrules" +func fwrule_col_path(dcid, srvid, nicid string) string { + return nic_path(dcid, srvid, nicid) + slash("firewallrules") +} + +// fwrule_path returns the string +// "/datacenters//servers//nics//firewallrules/" +func fwrule_path(dcid, srvid, nicid, fwruleid string) string { + return fwrule_col_path(dcid, srvid, nicid) + slash(fwruleid) +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/req.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/req.go new file mode 100644 index 000000000000..b5f21c17d069 --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/req.go @@ -0,0 +1,80 @@ +package profitbricks + +import ( + "bytes" + "encoding/json" + "io/ioutil" + "net/http" + "strings" +) + +//FullHeader is the standard header to include with all http requests except is_patch and is_command +const FullHeader = "application/vnd.profitbricks.resource+json" + +//PatchHeader is used with is_patch . +const PatchHeader = "application/vnd.profitbricks.partial-properties+json" + +//CommandHeader is used with is_command +const CommandHeader = "application/x-www-form-urlencoded" + +var Depth = "5" + +// SetDepth is used to set Depth +func SetDepth(newdepth string) string { + Depth = newdepth + return Depth +} + +// mk_url either: +// returns the path (if it`s a full url) +// or +// returns Endpoint+ path . +func mk_url(path string) string { + if strings.HasPrefix(path, "http") { + //REMOVE AFTER TESTING + path := strings.Replace(path, "https://api.profitbricks.com/rest/v2", Endpoint, 1) + // END REMOVE + return path + } + if strings.HasPrefix(path, "") { + //REMOVE AFTER TESTING + path := strings.Replace(path, "", Endpoint, 1) + return path + } + url := Endpoint + path + return url +} + +func do(req *http.Request) Resp { + client := &http.Client{} + req.SetBasicAuth(Username, Passwd) + resp, err := client.Do(req) + if err != nil { + panic(err) + } + defer resp.Body.Close() + resp_body, _ := ioutil.ReadAll(resp.Body) + var R Resp + R.Req = resp.Request + R.Body = resp_body + R.Headers = resp.Header + R.StatusCode = resp.StatusCode + return R +} + +// is_delete performs an http.NewRequest DELETE and returns a Resp struct +func is_delete(path string) Resp { + url := mk_url(path) + req, _ := http.NewRequest("DELETE", url, nil) + req.Header.Add("Content-Type", FullHeader) + return do(req) +} + +// is_command performs an http.NewRequest POST and returns a Resp struct +func is_command(path string, jason string) Resp { + url := mk_url(path) + body := json.RawMessage(jason) + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(body)) + req.Header.Add("Content-Type", CommandHeader) + return do(req) +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/request.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/request.go new file mode 100644 index 000000000000..023ae1a4a24a --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/request.go @@ -0,0 +1,43 @@ +package profitbricks + +import ( + "encoding/json" + "net/http" +) + +type RequestStatus struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Metadata RequestStatusMetadata `json:"metadata,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} +type RequestStatusMetadata struct { + Status string `json:"status,omitempty"` + Message string `json:"message,omitempty"` + Etag string `json:"etag,omitempty"` + Targets []RequestTarget `json:"targets,omitempty"` +} + +type RequestTarget struct { + Target ResourceReference `json:"target,omitempty"` + Status string `json:"status,omitempty"` +} + +func GetRequestStatus(path string) RequestStatus { + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toRequestStatus(do(req)) +} + +func toRequestStatus(resp Resp) RequestStatus { + var server RequestStatus + json.Unmarshal(resp.Body, &server) + server.Response = string(resp.Body) + server.Headers = &resp.Headers + server.StatusCode = resp.StatusCode + return server +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/resp.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/resp.go new file mode 100644 index 000000000000..12d68e0d247e --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/resp.go @@ -0,0 +1,61 @@ +package profitbricks + +import "net/http" +import "fmt" +import ( + "encoding/json" +) + +func MkJson(i interface{}) string { + jason, err := json.MarshalIndent(&i, "", " ") + if err != nil { + panic(err) + } + // fmt.Println(string(jason)) + return string(jason) +} + +// MetaData is a map for metadata returned in a Resp.Body +type StringMap map[string]string + +type StringIfaceMap map[string]interface{} + +type StringCollectionMap map[string]Collection + +// Resp is the struct returned by all Rest request functions +type Resp struct { + Req *http.Request + StatusCode int + Headers http.Header + Body []byte +} + +// PrintHeaders prints the http headers as k,v pairs +func (r *Resp) PrintHeaders() { + for key, value := range r.Headers { + fmt.Println(key, " : ", value[0]) + } + +} + +type Id_Type_Href struct { + Id string `json:"id"` + Type string `json:"type"` + Href string `json:"href"` +} + +type MetaData StringIfaceMap + +type Instance struct { + Id_Type_Href + MetaData StringMap `json:"metaData,omitempty"` + Properties StringIfaceMap `json:"properties,omitempty"` + Entities StringCollectionMap `json:"entities,omitempty"` + Resp Resp `json:"-"` +} + +type Collection struct { + Id_Type_Href + Items []Instance `json:"items,omitempty"` + Resp Resp `json:"-"` +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/server.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/server.go new file mode 100644 index 000000000000..d20a367184a4 --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/server.go @@ -0,0 +1,206 @@ +package profitbricks + +import ( + "bytes" + "encoding/json" + "net/http" +) + +type Server struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` + Properties ServerProperties `json:"properties,omitempty"` + Entities *ServerEntities `json:"entities,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type ServerProperties struct { + Name string `json:"name,omitempty"` + Cores int `json:"cores,omitempty"` + Ram int `json:"ram,omitempty"` + AvailabilityZone string `json:"availabilityZone,omitempty"` + VmState string `json:"vmState,omitempty"` + BootCdrom *ResourceReference `json:"bootCdrom,omitempty"` + BootVolume *ResourceReference `json:"bootVolume,omitempty"` + CpuFamily string `json:"cpuFamily,omitempty"` +} + +type ServerEntities struct { + Cdroms *Cdroms `json:"cdroms,omitempty"` + Volumes *Volumes `json:"volumes,omitempty"` + Nics *Nics `json:"nics,omitempty"` +} + +type Servers struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Items []Server `json:"items,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type ResourceReference struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` +} + +type CreateServerRequest struct { + ServerProperties `json:"properties"` +} + +// ListServers returns a server struct collection +func ListServers(dcid string) Servers { + path := server_col_path(dcid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + resp := do(req) + return toServers(resp) +} + +// CreateServer creates a server from a jason []byte and returns a Instance struct +func CreateServer(dcid string, server Server) Server { + obj, _ := json.Marshal(server) + path := server_col_path(dcid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj)) + req.Header.Add("Content-Type", FullHeader) + return toServer(do(req)) +} + +// GetServer pulls data for the server where id = srvid returns a Instance struct +func GetServer(dcid, srvid string) Server { + path := server_path(dcid, srvid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toServer(do(req)) +} + +// PatchServer partial update of server properties passed in as jason []byte +// Returns Instance struct +func PatchServer(dcid string, srvid string, props ServerProperties) Server { + jason, _ := json.Marshal(props) + path := server_path(dcid, srvid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jason)) + req.Header.Add("Content-Type", PatchHeader) + return toServer(do(req)) +} + +// DeleteServer deletes the server where id=srvid and returns Resp struct +func DeleteServer(dcid, srvid string) Resp { + path := server_path(dcid, srvid) + return is_delete(path) +} + +func ListAttachedCdroms(dcid, srvid string) Images { + path := server_cdrom_col_path(dcid, srvid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toImages(do(req)) +} + +func AttachCdrom(dcid string, srvid string, cdid string) Image { + jason := []byte(`{"id":"` + cdid + `"}`) + path := server_cdrom_col_path(dcid, srvid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jason)) + req.Header.Add("Content-Type", FullHeader) + return toImage(do(req)) +} + +func GetAttachedCdrom(dcid, srvid, cdid string) Volume { + path := server_cdrom_path(dcid, srvid, cdid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toVolume(do(req)) +} + +func DetachCdrom(dcid, srvid, cdid string) Resp { + path := server_cdrom_path(dcid, srvid, cdid) + return is_delete(path) +} + +func ListAttachedVolumes(dcid, srvid string) Volumes { + path := server_volume_col_path(dcid, srvid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + resp := do(req) + return toVolumes(resp) +} + +func AttachVolume(dcid string, srvid string, volid string) Volume { + jason := []byte(`{"id":"` + volid + `"}`) + path := server_volume_col_path(dcid, srvid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jason)) + req.Header.Add("Content-Type", FullHeader) + return toVolume(do(req)) +} + +func GetAttachedVolume(dcid, srvid, volid string) Volume { + path := server_volume_path(dcid, srvid, volid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + resp := do(req) + return toVolume(resp) +} + +func DetachVolume(dcid, srvid, volid string) Resp { + path := server_volume_path(dcid, srvid, volid) + return is_delete(path) +} + +// StartServer starts a server +func StartServer(dcid, srvid string) Resp { + return server_command(dcid, srvid, "start") +} + +// StopServer stops a server +func StopServer(dcid, srvid string) Resp { + return server_command(dcid, srvid, "stop") +} + +// RebootServer reboots a server +func RebootServer(dcid, srvid string) Resp { + return server_command(dcid, srvid, "reboot") +} + +// server_command is a generic function for running server commands +func server_command(dcid, srvid, cmd string) Resp { + jason := ` + {} + ` + path := server_command_path(dcid, srvid, cmd) + return is_command(path, jason) +} + +func toServer(resp Resp) Server { + var server Server + json.Unmarshal(resp.Body, &server) + server.Response = string(resp.Body) + server.Headers = &resp.Headers + server.StatusCode = resp.StatusCode + return server +} + +func toServers(resp Resp) Servers { + var col Servers + json.Unmarshal(resp.Body, &col) + col.Response = string(resp.Body) + col.Headers = &resp.Headers + col.StatusCode = resp.StatusCode + return col +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/snapshot.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/snapshot.go new file mode 100644 index 000000000000..a5f54c04f3e3 --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/snapshot.go @@ -0,0 +1,96 @@ +package profitbricks + +import ( + "bytes" + "encoding/json" + "net/http" +) + +type Snapshot struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Metadata DatacenterElementMetadata `json:"metadata,omitempty"` + Properties SnapshotProperties `json:"properties,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type SnapshotProperties struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + Location string `json:"location,omitempty"` + Size int `json:"size,omitempty"` + CpuHotPlug bool `json:"cpuHotPlug,omitempty"` + CpuHotUnplug bool `json:"cpuHotUnplug,omitempty"` + RamHotPlug bool `json:"ramHotPlug,omitempty"` + RamHotUnplug bool `json:"ramHotUnplug,omitempty"` + NicHotPlug bool `json:"nicHotPlug,omitempty"` + NicHotUnplug bool `json:"nicHotUnplug,omitempty"` + DiscVirtioHotPlug bool `json:"discVirtioHotPlug,omitempty"` + DiscVirtioHotUnplug bool `json:"discVirtioHotUnplug,omitempty"` + DiscScsiHotPlug bool `json:"discScsiHotPlug,omitempty"` + DiscScsiHotUnplug bool `json:"discScsiHotUnplug,omitempty"` + LicenceType string `json:"licenceType,omitempty"` +} + +type Snapshots struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Items []Snapshot `json:"items,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +func ListSnapshots() Snapshots { + path := snapshot_col_path() + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toSnapshots(do(req)) +} + +func GetSnapshot(snapshotId string) Snapshot { + path := snapshot_col_path() + slash(snapshotId) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + return toSnapshot(do(req)) +} + +func DeleteSnapshot(snapshotId string) Resp { + path := snapshot_col_path() + slash(snapshotId) + url := mk_url(path) + req, _ := http.NewRequest("DELETE", url, nil) + req.Header.Add("Content-Type", FullHeader) + return do(req) +} + +func UpdateSnapshot(snapshotId string, request SnapshotProperties) Snapshot { + path := snapshot_col_path() + slash(snapshotId) + obj, _ := json.Marshal(request) + url := mk_url(path) + req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(obj)) + req.Header.Add("Content-Type", PatchHeader) + return toSnapshot(do(req)) +} + +func toSnapshot(resp Resp) Snapshot { + var lan Snapshot + json.Unmarshal(resp.Body, &lan) + lan.Response = string(resp.Body) + lan.Headers = &resp.Headers + lan.StatusCode = resp.StatusCode + return lan +} +func toSnapshots(resp Resp) Snapshots { + var col Snapshots + json.Unmarshal(resp.Body, &col) + col.Response = string(resp.Body) + col.Headers = &resp.Headers + col.StatusCode = resp.StatusCode + return col +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/test_helpers.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/test_helpers.go new file mode 100644 index 000000000000..35df1f929172 --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/test_helpers.go @@ -0,0 +1,72 @@ +package profitbricks + +import ( + "fmt" + "time" +) + +func mkdcid(name string) string { + request := Datacenter{ + Properties: DatacenterProperties{ + Name: name, + Description: "description", + Location: "us/las", + }, + } + dc := CreateDatacenter(request) + fmt.Println("===========================") + fmt.Println("Created a DC " + name) + fmt.Println("Created a DC id " + dc.Id) + fmt.Println(dc.StatusCode) + fmt.Println("===========================") + return dc.Id +} + +func mksrvid(srv_dcid string) string { + var req = Server{ + Properties: ServerProperties{ + Name: "GO SDK test", + Ram: 1024, + Cores: 2, + }, + } + srv := CreateServer(srv_dcid, req) + fmt.Println("===========================") + fmt.Println("Created a server " + srv.Id) + fmt.Println(srv.StatusCode) + fmt.Println("===========================") + + waitTillProvisioned(srv.Headers.Get("Location")) + return srv.Id +} + +func mknic(lbal_dcid, serverid string) string { + var request = Nic{ + Properties: NicProperties{ + Name: "GO SDK Original Nic", + Lan: 1, + }, + } + + resp := CreateNic(lbal_dcid, serverid, request) + fmt.Println("===========================") + fmt.Println("created a nic at server " + serverid) + + fmt.Println("created a nic with id " + resp.Id) + fmt.Println(resp.StatusCode) + fmt.Println("===========================") + return resp.Id +} + +func waitTillProvisioned(path string) { + waitCount := 20 + fmt.Println(path) + for i := 0; i < waitCount; i++ { + request := GetRequestStatus(path) + if request.Metadata.Status == "DONE" { + break + } + time.Sleep(10 * time.Second) + i++ + } +} diff --git a/vendor/github.com/profitbricks/profitbricks-sdk-go/volume.go b/vendor/github.com/profitbricks/profitbricks-sdk-go/volume.go new file mode 100644 index 000000000000..2982448d7324 --- /dev/null +++ b/vendor/github.com/profitbricks/profitbricks-sdk-go/volume.go @@ -0,0 +1,131 @@ +package profitbricks + +import ( + "bytes" + "encoding/json" + "net/http" +) + +type Volume struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` + Properties VolumeProperties `json:"properties,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type VolumeProperties struct { + Name string `json:"name,omitempty"` + Type string `json:"type,omitempty"` + Size int `json:"size,omitempty"` + Image string `json:"image,omitempty"` + ImagePassword string `json:"imagePassword,omitempty"` + SshKeys []string `json:"sshKeys,omitempty"` + Bus string `json:"bus,omitempty"` + LicenceType string `json:"licenceType,omitempty"` + CpuHotPlug bool `json:"cpuHotPlug,omitempty"` + CpuHotUnplug bool `json:"cpuHotUnplug,omitempty"` + RamHotPlug bool `json:"ramHotPlug,omitempty"` + RamHotUnplug bool `json:"ramHotUnplug,omitempty"` + NicHotPlug bool `json:"nicHotPlug,omitempty"` + NicHotUnplug bool `json:"nicHotUnplug,omitempty"` + DiscVirtioHotPlug bool `json:"discVirtioHotPlug,omitempty"` + DiscVirtioHotUnplug bool `json:"discVirtioHotUnplug,omitempty"` + DiscScsiHotPlug bool `json:"discScsiHotPlug,omitempty"` + DiscScsiHotUnplug bool `json:"discScsiHotUnplug,omitempty"` + DeviceNumber int64 `json:"deviceNumber,omitempty"` +} + +type Volumes struct { + Id string `json:"id,omitempty"` + Type_ string `json:"type,omitempty"` + Href string `json:"href,omitempty"` + Items []Volume `json:"items,omitempty"` + Response string `json:"Response,omitempty"` + Headers *http.Header `json:"headers,omitempty"` + StatusCode int `json:"headers,omitempty"` +} + +type CreateVolumeRequest struct { + VolumeProperties `json:"properties"` +} + +// ListVolumes returns a Collection struct for volumes in the Datacenter +func ListVolumes(dcid string) Volumes { + path := volume_col_path(dcid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + resp := do(req) + return toVolumes(resp) +} + +func GetVolume(dcid string, volumeId string) Volume { + path := volume_path(dcid, volumeId) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("GET", url, nil) + req.Header.Add("Content-Type", FullHeader) + resp := do(req) + return toVolume(resp) +} + +func PatchVolume(dcid string, volid string, request VolumeProperties) Volume { + obj, _ := json.Marshal(request) + path := volume_path(dcid, volid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(obj)) + req.Header.Add("Content-Type", PatchHeader) + return toVolume(do(req)) +} + +func CreateVolume(dcid string, request Volume) Volume { + obj, _ := json.Marshal(request) + path := volume_col_path(dcid) + url := mk_url(path) + `?depth=` + Depth + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(obj)) + req.Header.Add("Content-Type", FullHeader) + return toVolume(do(req)) +} + +func DeleteVolume(dcid, volid string) Resp { + path := volume_path(dcid, volid) + return is_delete(path) +} + +func CreateSnapshot(dcid string, volid string, name string) Snapshot { + var path = volume_path(dcid, volid) + path = path + "/create-snapshot" + url := mk_url(path) + body := json.RawMessage("name=" + name) + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(body)) + req.Header.Add("Content-Type", CommandHeader) + return toSnapshot(do(req)) +} + +func RestoreSnapshot(dcid string, volid string, snapshotId string) Resp { + var path = volume_path(dcid, volid) + path = path + "/restore-snapshot" + + return is_command(path, "snapshotId="+snapshotId) +} + +func toVolume(resp Resp) Volume { + var server Volume + json.Unmarshal(resp.Body, &server) + server.Response = string(resp.Body) + server.Headers = &resp.Headers + server.StatusCode = resp.StatusCode + return server +} + +func toVolumes(resp Resp) Volumes { + var col Volumes + json.Unmarshal(resp.Body, &col) + col.Response = string(resp.Body) + col.Headers = &resp.Headers + col.StatusCode = resp.StatusCode + return col +} diff --git a/vendor/vendor.json b/vendor/vendor.json index 839498c3a48b..4f4df57584b0 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -2444,6 +2444,33 @@ "revision": "42fa80f2ac6ed17a977ce826074bd3009593fa9d" }, { +<<<<<<< HEAD + "checksumSHA1": "atkFfe1CrxF+Cz4p4Z78RMXC0Kg=", + "path": "github.com/profitbricks/profitbricks-sdk-go", + "revision": "ccbdd70b24ec5c6cd000a34aba264d708c106af9", + "revisionTime": "2016-07-28T11:13:56Z" + }, + { + "checksumSHA1": "4Q/JrLYYcwGRPVpd6sJ5yW/E9GQ=", + "path": "github.com/rackspace/gophercloud", + "revision": "985a863d6dd5f928b485dbc8ef440813aafa39ad", + "revisionTime": "2016-06-23T23:57:31Z" + }, + { + "checksumSHA1": "dh2tsaicjrx9LgR6uuSeilSFzAY=", + "path": "github.com/rackspace/gophercloud/openstack", + "revision": "985a863d6dd5f928b485dbc8ef440813aafa39ad", + "revisionTime": "2016-06-23T23:57:31Z" + }, + { + "checksumSHA1": "KXOy+EDMJgyZT0MoTXMhcFZVgNM=", + "path": "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes", + "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", + "revisionTime": "2016-06-03T22:34:01Z" + }, + { +======= +>>>>>>> upstream/master "checksumSHA1": "uh4DrOO+91jmxNlamBoloURUPO0=", "path": "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/testing", "revision": "d47105ce4ef90cea9a14b85c8dd172b760085828", diff --git a/website/source/docs/providers/profitbricks/index.html.markdown b/website/source/docs/providers/profitbricks/index.html.markdown new file mode 100644 index 000000000000..59106bb1f81d --- /dev/null +++ b/website/source/docs/providers/profitbricks/index.html.markdown @@ -0,0 +1,60 @@ +--- +layout: "profitbricks" +page_title: "Provider: ProfitBricks" +sidebar_current: "docs-profitbricks-index" +description: |- + A provider for ProfitBricks. +--- + +# ProfitBricks Provider + +The ProfitBricks provider gives the ability to deploy and configure resources using ProfitBricks Cloud API. + +Use the navigation to the left to read about the available resources. + + +## Usage + +The provider needs to be configured with proper credentials before it can be used. + + +``` +$ export PROFITBRICKS_USERNAME="profitbricks_username" +$ export PROFITBRICKS_PASSWORD="profitbricks_password" +``` + +Or you can provide your credentials like this: + + +The credentials provided in `.tf` file will override credentials in the environment variables. + +## Example Usage + + +``` +provider "profitbricks" { + username = "profitbricks_username" + password = "profitbricks_password" + retries = 100 +} + + +resource "profitbricks_datacenter" "main" { + ... +} +``` + + +## Configuration Reference + +The following arguments are supported: + +* `username` - (Required) If omitted, the `PROFITBRICKS_USERNAME` environment variable is used. + +* `password` - (Required) If omitted, the `PROFITBRICKS_PASSWORD` environment variable is used. + +* `retries` - (Optional) Number of retries while waiting for a resource to be provisioned. Default value is 50. + + +#Support +You are welcome to contact us with questions or comments at [ProfitBricks DevOps Central](https://devops.profitbricks.com/). \ No newline at end of file diff --git a/website/source/docs/providers/profitbricks/r/profitbricks_datacenter.html.markdown b/website/source/docs/providers/profitbricks/r/profitbricks_datacenter.html.markdown new file mode 100644 index 000000000000..452a5a5c5173 --- /dev/null +++ b/website/source/docs/providers/profitbricks/r/profitbricks_datacenter.html.markdown @@ -0,0 +1,29 @@ +--- +layout: "profitbricks" +page_title: "ProfitBricks: profitbricks_datacenter" +sidebar_current: "docs-profitbricks-resource-profitbricks_datacenter" +description: |- + Creates and manages Profitbricks Virtual Data Center. +--- + +# profitbricks\_datacenter + +Manages a Virtual Data Center on ProfitBricks + +## Example Usage + +``` +resource "profitbricks_datacenter" "example" { + name = "datacenter name" + location = "us/las" + description = "datacenter description" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required)[string] The name of the Virtual Data Center. +* `location` - (Required)[string] The physical location where the data center will be created. +* `description` - (Optional)[string] Description for the data center. diff --git a/website/source/docs/providers/profitbricks/r/profitbricks_firewall.html.markdown b/website/source/docs/providers/profitbricks/r/profitbricks_firewall.html.markdown new file mode 100644 index 000000000000..36c54ea3db43 --- /dev/null +++ b/website/source/docs/providers/profitbricks/r/profitbricks_firewall.html.markdown @@ -0,0 +1,41 @@ +--- +layout: "profitbricks" +page_title: "ProfitBricks: profitbricks_firewall" +sidebar_current: "docs-profitbricks-resource-profitbricks_firewall" +description: |- + Creates and manages Firewall Rules. +--- + +# profitbricks\_firewall + +Manages a Firewall Rules on ProfitBricks + +## Example Usage + +``` +resource "profitbricks_firewall" "example" { + datacenter_id = "${profitbricks_datacenter.example.id}" + server_id = "${profitbricks_server.example.id}" + nic_id = "${profitbricks_server.example.primary_nic}" + protocol = "TCP" + name = "test" + port_range_start = 1 + port_range_end = 2 +} +``` + +####Argument reference + +* `datacenter_id` - (Required)[string] +* `server_id` - (Required)[string] +* `nic_id` - (Required)[string] +* `protocol` - (Required)[string] The protocol for the rule: TCP, UDP, ICMP, ANY. +* `name` - (Optional)[string] The name of the firewall rule. +* `source_mac` - (Optional)[string] Only traffic originating from the respective MAC address is allowed. Valid format: aa:bb:cc:dd:ee:ff. +* `source_ip` - (Optional)[string] Only traffic originating from the respective IPv4 address is allowed. +* `target_ip` - (Optional)[string] Only traffic directed to the respective IP address of the NIC is allowed. +* `port_range_start` - (Optional)[string] Defines the start range of the allowed port (from 1 to 65534) if protocol TCP or UDP is chosen. +* `port_range_end` - (Optional)[string] Defines the end range of the allowed port (from 1 to 65534) if the protocol TCP or UDP is chosen. +* `icmp_type` - (Optional)[string] Defines the allowed type (from 0 to 254) if the protocol ICMP is chosen. +* `icmp_code` - (Optional)[string] Defines the allowed code (from 0 to 254) if protocol ICMP is chosen. + diff --git a/website/source/docs/providers/profitbricks/r/profitbricks_ipblock.html.markdown b/website/source/docs/providers/profitbricks/r/profitbricks_ipblock.html.markdown new file mode 100644 index 000000000000..a51c13abc1fa --- /dev/null +++ b/website/source/docs/providers/profitbricks/r/profitbricks_ipblock.html.markdown @@ -0,0 +1,27 @@ +--- +layout: "profitbricks" +page_title: "ProfitBricks: profitbricks_ipblock" +sidebar_current: "docs-profitbricks-resource-profitbricks_ipblock" +description: |- + Creates and manages IP Block objects. +--- + +# profitbricks\_ipblock + +Manages a IP Blocks on ProfitBricks + +## Example Usage + +``` +resource "profitbricks_ipblock" "example" { + location = "${profitbricks_datacenter.example.location}" + size = 1 +} +``` + +##Argument reference + +* `location` - (Required) +* `size` - (Required) + + \ No newline at end of file diff --git a/website/source/docs/providers/profitbricks/r/profitbricks_lan.html.markdown b/website/source/docs/providers/profitbricks/r/profitbricks_lan.html.markdown new file mode 100644 index 000000000000..27da18f10d11 --- /dev/null +++ b/website/source/docs/providers/profitbricks/r/profitbricks_lan.html.markdown @@ -0,0 +1,26 @@ +--- +layout: "profitbricks" +page_title: "ProfitBricks: profitbricks_lan" +sidebar_current: "docs-profitbricks-resource-profitbricks_lan" +description: |- + Creates and manages LAN objects. +--- + +# profitbricks\_lan + +Manages a LANs on ProfitBricks + +## Example Usage + +``` +resource "profitbricks_lan" "example" { + datacenter_id = "${profitbricks_datacenter.example.id}" + public = true +} +``` + +##Argument reference + +* `datacenter_id` - (Required) [string] +* `name` - (Optional) [string] The name of the LAN +* `public` - (Optional) [Boolean] indicating if the LAN faces the public Internet or not. diff --git a/website/source/docs/providers/profitbricks/r/profitbricks_loadbalancer.html.markdown b/website/source/docs/providers/profitbricks/r/profitbricks_loadbalancer.html.markdown new file mode 100644 index 000000000000..5172d9d07e2b --- /dev/null +++ b/website/source/docs/providers/profitbricks/r/profitbricks_loadbalancer.html.markdown @@ -0,0 +1,30 @@ +--- +layout: "profitbricks" +page_title: "ProfitBricks: profitbricks_loadbalancer" +sidebar_current: "docs-profitbricks-resource-profitbricks_loadbalancer" +description: |- + Creates and manages Load Balancers +--- + +# profitbricks\_loadbalancer + +Manages a Load Balancers on ProfitBricks + +## Example Usage + +``` +resource "profitbricks_loadbalancer" "example" { + datacenter_id = "${profitbricks_datacenter.example.id}" + nic_id = "${profitbricks_nic.example.id}" + name = "load balancer name" + dhcp = true +} +``` + +##Argument reference + +* `datacenter_id` - (Required)[string] +* `nic_id` - (Required)[string] +* `dhcp` - (Optional) [boolean] Indicates if the load balancer will reserve an IP using DHCP. +* `ip` - (Optional) [string] IPv4 address of the load balancer. + diff --git a/website/source/docs/providers/profitbricks/r/profitbricks_nic.html.markdown b/website/source/docs/providers/profitbricks/r/profitbricks_nic.html.markdown new file mode 100644 index 000000000000..e1caaccbd320 --- /dev/null +++ b/website/source/docs/providers/profitbricks/r/profitbricks_nic.html.markdown @@ -0,0 +1,34 @@ +--- +layout: "profitbricks" +page_title: "ProfitBricks: profitbricks_nic" +sidebar_current: "docs-profitbricks-resource-profitbricks_nic" +description: |- + Creates and manages Network Interface objects. +--- + +# profitbricks\_nic + +Manages a NICs on ProfitBricks + +## Example Usage + +``` +resource "profitbricks_nic" "example" { + datacenter_id = "${profitbricks_datacenter.example.id}" + server_id = "${profitbricks_server.example.id}" + lan = 2 + dhcp = true + ip = "${profitbricks_ipblock.example.ip}" +} +``` + +##Argument reference + +* `datacenter_id` - (Required)[string][1](#myfootnote1) +* `server_id` - (Required)[string][1](#myfootnote1) +* `lan` - (Required) [integer] The LAN ID the NIC will sit on. +* `name` - (Optional) [string] The name of the LAN. +* `dhcp` - (Optional) [boolean] +* `ip` - (Optional) [string] IP assigned to the NIC. +* `firewall_active` - (Optional) [boolean] If this resource is set to true and is nested under a server resource firewall, with open SSH port, resource must be nested under the nic. + \ No newline at end of file diff --git a/website/source/docs/providers/profitbricks/r/profitbricks_server.html.markdown b/website/source/docs/providers/profitbricks/r/profitbricks_server.html.markdown new file mode 100644 index 000000000000..6b292722da30 --- /dev/null +++ b/website/source/docs/providers/profitbricks/r/profitbricks_server.html.markdown @@ -0,0 +1,59 @@ +--- +layout: "profitbricks" +page_title: "ProfitBricks: profitbricks_server" +sidebar_current: "docs-profitbricks-resource-profitbricks_server" +description: |- + Creates and manages ProfitBricks Server objects. +--- + +# profitbricks\_server + +Manages a Servers on ProfitBricks + +## Example Usage + +This resource will create an operational server. After this section completes, the provisioner can be called. + +``` +resource "profitbricks_server" "example" { + name = "server" + datacenter_id = "${profitbricks_datacenter.example.id}" + cores = 1 + ram = 1024 + availability_zone = "ZONE_1" + cpu_family = "AMD_OPTERON" + volume { + name = "new" + image_name = "${var.ubuntu}" + size = 5 + disk_type = "SSD" + ssh_key_path = "${var.private_key_path}" + image_password = "test1234" + } + nic { + lan = "${profitbricks_lan.example.id}" + dhcp = true + ip = "${profitbricks_ipblock.example.ip}" + firewall_active = true + firewall { + protocol = "TCP" + name = "SSH" + port_range_start = 22 + port_range_end = 22 + } + } + } +``` + +##Argument reference + +* `name` - (Required) [string] The name of the server. +* `datacenter_id` - (Required)[string] +* `cores` - (Required)[integer] Number of server cores. +* `ram` - (Required)[integer] The amount of memory for the server in MB. +* `availability_zone` - (Optional)[string] The availability zone in which the server should exist. +* `licence_type` - (Optional)[string] Sets the OS type of the server. +* `cpuFamily` - (Optional)[string] Sets the CPU type. "AMD_OPTERON" or "INTEL_XEON". Defaults to "AMD_OPTERON". +* `volume` - (Required) See Volume section. +* `nic` - (Required) See NIC section. +* `firewall` - (Optional) See Firewall Rule section. diff --git a/website/source/docs/providers/profitbricks/r/profitbricks_volume.html.markdown b/website/source/docs/providers/profitbricks/r/profitbricks_volume.html.markdown new file mode 100644 index 000000000000..29e5e61b22b2 --- /dev/null +++ b/website/source/docs/providers/profitbricks/r/profitbricks_volume.html.markdown @@ -0,0 +1,39 @@ +--- +layout: "profitbricks" +page_title: "ProfitBricks: profitbricks_server" +sidebar_current: "docs-profitbricks-resource-profitbricks_volume" +description: |- + Creates and manages ProfitBricks Volume objects. +--- + +# profitbricks\_volume + +Manages a Volumes on ProfitBricks + +## Example Usage + +A primary volume will be created with the server. If there is a need for additional volume, this resource handles it. + +``` +resource "profitbricks_volume" "example" { + datacenter_id = "${profitbricks_datacenter.example.id}" + server_id = "${profitbricks_server.example.id}" + image_name = "${var.ubuntu}" + size = 5 + disk_type = "HDD" + sshkey_path = "${var.private_key_path}" + bus = "VIRTIO" +} +``` + +##Argument reference + +* `datacenter_id` - (Required) [string] [1](#myfootnote1) +* `server_id` - (Required)[string] [1](#myfootnote1) +* `disk_type` - (Required) [string] The volume type, HDD or SSD. +* `bus` - (Required) [boolean] The bus type of the volume. +* `size` - (Required)[integer] The size of the volume in GB. +* `image_password` - [string] Required if `sshkey_path` is not provided. +* `image_name` - [string] The image or snapshot ID. It is required if `licence_type` is not provided. +* `licence_type` - [string] Required if `image_name` is not provided. +* `name` - (Optional) [string] The name of the volume. \ No newline at end of file