From f09280891ccd7e5c8ce31b4475ce10622b28824f Mon Sep 17 00:00:00 2001 From: Colin Hebert Date: Sat, 2 Jan 2016 12:20:55 +0100 Subject: [PATCH] Add support of custom networks in docker --- builtin/providers/docker/provider.go | 1 + .../docker/resource_docker_network.go | 135 ++++++++++++++++++ .../docker/resource_docker_network_funcs.go | 115 +++++++++++++++ .../docker/resource_docker_network_test.go | 65 +++++++++ .../providers/docker/r/network.html.markdown | 49 +++++++ website/source/layouts/docker.erb | 4 + 6 files changed, 369 insertions(+) create mode 100644 builtin/providers/docker/resource_docker_network.go create mode 100644 builtin/providers/docker/resource_docker_network_funcs.go create mode 100644 builtin/providers/docker/resource_docker_network_test.go create mode 100644 website/source/docs/providers/docker/r/network.html.markdown diff --git a/builtin/providers/docker/provider.go b/builtin/providers/docker/provider.go index fdc8b7719..799fd9bdb 100644 --- a/builtin/providers/docker/provider.go +++ b/builtin/providers/docker/provider.go @@ -28,6 +28,7 @@ func Provider() terraform.ResourceProvider { ResourcesMap: map[string]*schema.Resource{ "docker_container": resourceDockerContainer(), "docker_image": resourceDockerImage(), + "docker_network": resourceDockerNetwork(), }, ConfigureFunc: providerConfigure, diff --git a/builtin/providers/docker/resource_docker_network.go b/builtin/providers/docker/resource_docker_network.go new file mode 100644 index 000000000..4c14b2dea --- /dev/null +++ b/builtin/providers/docker/resource_docker_network.go @@ -0,0 +1,135 @@ +package docker + +import ( + "bytes" + "fmt" + "sort" + + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceDockerNetwork() *schema.Resource { + return &schema.Resource{ + Create: resourceDockerNetworkCreate, + Read: resourceDockerNetworkRead, + Delete: resourceDockerNetworkDelete, + + Schema: map[string]*schema.Schema{ + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "check_duplicate": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + }, + + "driver": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Computed: true, + }, + + "options": &schema.Schema{ + Type: schema.TypeMap, + Optional: true, + ForceNew: true, + Computed: true, + }, + + "ipam_driver": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + "ipam_config": &schema.Schema{ + Type: schema.TypeSet, + Optional: true, + ForceNew: true, + Elem: getIpamConfigElem(), + Set: resourceDockerIpamConfigHash, + }, + + "id": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + + "scope": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func getIpamConfigElem() *schema.Resource { + return &schema.Resource{ + Schema: map[string]*schema.Schema{ + "subnet": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + "ip_range": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + "gateway": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + "aux_address": &schema.Schema{ + Type: schema.TypeMap, + Optional: true, + ForceNew: true, + }, + }, + } +} + +func resourceDockerIpamConfigHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + + if v, ok := m["subnet"]; ok { + buf.WriteString(fmt.Sprintf("%v-", v.(string))) + } + + if v, ok := m["ip_range"]; ok { + buf.WriteString(fmt.Sprintf("%v-", v.(string))) + } + + if v, ok := m["gateway"]; ok { + buf.WriteString(fmt.Sprintf("%v-", v.(string))) + } + + if v, ok := m["aux_address"]; ok { + auxAddress := v.(map[string]interface{}) + + keys := make([]string, len(auxAddress)) + i := 0 + for k, _ := range auxAddress { + keys[i] = k + i++ + } + sort.Strings(keys) + + for _, k := range keys { + buf.WriteString(fmt.Sprintf("%v-%v-", k, auxAddress[k].(string))) + } + } + + return hashcode.String(buf.String()) +} diff --git a/builtin/providers/docker/resource_docker_network_funcs.go b/builtin/providers/docker/resource_docker_network_funcs.go new file mode 100644 index 000000000..61954f4af --- /dev/null +++ b/builtin/providers/docker/resource_docker_network_funcs.go @@ -0,0 +1,115 @@ +package docker + +import ( + "fmt" + + dc "github.com/fsouza/go-dockerclient" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceDockerNetworkCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*dc.Client) + + createOpts := dc.CreateNetworkOptions{ + Name: d.Get("name").(string), + } + if v, ok := d.GetOk("check_duplicate"); ok { + createOpts.CheckDuplicate = v.(bool) + } + if v, ok := d.GetOk("driver"); ok { + createOpts.Driver = v.(string) + } + if v, ok := d.GetOk("options"); ok { + createOpts.Options = v.(map[string]interface{}) + } + + ipamOpts := dc.IPAMOptions{} + ipamOptsSet := false + if v, ok := d.GetOk("ipam_driver"); ok { + ipamOpts.Driver = v.(string) + ipamOptsSet = true + } + if v, ok := d.GetOk("ipam_config"); ok { + ipamOpts.Config = ipamConfigSetToIpamConfigs(v.(*schema.Set)) + ipamOptsSet = true + } + + if ipamOptsSet { + createOpts.IPAM = ipamOpts + } + + var err error + var retNetwork *dc.Network + if retNetwork, err = client.CreateNetwork(createOpts); err != nil { + return fmt.Errorf("Unable to create network: %s", err) + } + if retNetwork == nil { + return fmt.Errorf("Returned network is nil") + } + + d.SetId(retNetwork.ID) + d.Set("name", retNetwork.Name) + d.Set("scope", retNetwork.Scope) + d.Set("driver", retNetwork.Driver) + d.Set("options", retNetwork.Options) + + return nil +} + +func resourceDockerNetworkRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*dc.Client) + + var err error + var retNetwork *dc.Network + if retNetwork, err = client.NetworkInfo(d.Id()); err != nil { + if _, ok := err.(*dc.NoSuchNetwork); !ok { + return fmt.Errorf("Unable to inspect network: %s", err) + } + } + if retNetwork == nil { + d.SetId("") + return nil + } + + d.Set("scope", retNetwork.Scope) + d.Set("driver", retNetwork.Driver) + d.Set("options", retNetwork.Options) + + return nil +} + +func resourceDockerNetworkDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*dc.Client) + + if err := client.RemoveNetwork(d.Id()); err != nil { + if _, ok := err.(*dc.NoSuchNetwork); !ok { + return fmt.Errorf("Error deleting network %s: %s", d.Id(), err) + } + } + + d.SetId("") + return nil +} + +func ipamConfigSetToIpamConfigs(ipamConfigSet *schema.Set) []dc.IPAMConfig { + ipamConfigs := make([]dc.IPAMConfig, ipamConfigSet.Len()) + + for i, ipamConfigInt := range ipamConfigSet.List() { + ipamConfigRaw := ipamConfigInt.(map[string]interface{}) + + ipamConfig := dc.IPAMConfig{} + ipamConfig.Subnet = ipamConfigRaw["subnet"].(string) + ipamConfig.IPRange = ipamConfigRaw["ip_range"].(string) + ipamConfig.Gateway = ipamConfigRaw["gateway"].(string) + + auxAddressRaw := ipamConfigRaw["aux_address"].(map[string]interface{}) + ipamConfig.AuxAddress = make(map[string]string, len(auxAddressRaw)) + for k, v := range auxAddressRaw { + ipamConfig.AuxAddress[k] = v.(string) + } + + ipamConfigs[i] = ipamConfig + } + + return ipamConfigs +} diff --git a/builtin/providers/docker/resource_docker_network_test.go b/builtin/providers/docker/resource_docker_network_test.go new file mode 100644 index 000000000..6e3bb4e38 --- /dev/null +++ b/builtin/providers/docker/resource_docker_network_test.go @@ -0,0 +1,65 @@ +package docker + +import ( + "fmt" + "testing" + + dc "github.com/fsouza/go-dockerclient" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccDockerNetwork_basic(t *testing.T) { + var n dc.Network + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccDockerNetworkConfig, + Check: resource.ComposeTestCheckFunc( + testAccNetwork("docker_network.foo", &n), + ), + }, + }, + }) +} + +func testAccNetwork(n string, network *dc.Network) 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 ID is set") + } + + client := testAccProvider.Meta().(*dc.Client) + networks, err := client.ListNetworks() + if err != nil { + return err + } + + for _, n := range networks { + if n.ID == rs.Primary.ID { + inspected, err := client.NetworkInfo(n.ID) + if err != nil { + return fmt.Errorf("Network could not be obtained: %s", err) + } + *network = *inspected + return nil + } + } + + return fmt.Errorf("Network not found: %s", rs.Primary.ID) + } +} + +const testAccDockerNetworkConfig = ` +resource "docker_network" "foo" { + name = "bar" +} +` diff --git a/website/source/docs/providers/docker/r/network.html.markdown b/website/source/docs/providers/docker/r/network.html.markdown new file mode 100644 index 000000000..77d4d02f1 --- /dev/null +++ b/website/source/docs/providers/docker/r/network.html.markdown @@ -0,0 +1,49 @@ +--- +layout: "docker" +page_title: "Docker: docker_network" +sidebar_current: "docs-docker-resource-network" +description: |- + Manages a Docker Network. +--- + +# docker\_network + +Manages a Docker Network. This can be used alongside +[docker\_container](/docs/providers/docker/r/container.html) +to create virtual networks within the docker environment. + +## Example Usage + +``` +# Find the latest Ubuntu precise image. +resource "docker_network" "private_network" { + name = "my_network" +} + +# Access it somewhere else with ${docker_image.docker_network.name} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required, string) The name of the Docker network. +* `check_duplicate` - (Optional, boolean) Requests daemon to check for networks with same name. +* `driver` - (Optional, string) Name of the network driver to use. Defaults to `bridge` driver. +* `options` - (Optional, map of strings) Network specific options to be used by the drivers. +* `ipam_driver` - (Optional, string) Driver used by the custom IP scheme of the network. +* `ipam_config` - (Optional, block) Configuration of the custom IP scheme of the network. + +The `ipam_config` block supports: + +* `subnet` - (Optional, string) +* `ip_range` - (Optional, string) +* `gateway` - (Optional, string) +* `aux_address` - (Optional, map of string) + +## Attributes Reference + +The following attributes are exported in addition to the above configuration: + +* `id` (string) +* `scope` (string) diff --git a/website/source/layouts/docker.erb b/website/source/layouts/docker.erb index 5bb5a1514..d5ae7e2ca 100644 --- a/website/source/layouts/docker.erb +++ b/website/source/layouts/docker.erb @@ -20,6 +20,10 @@ > docker_image + + > + docker_network +