Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

provider/azurerm: Event Hub Namespaces #9297

Merged
merged 15 commits into from
Oct 25, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions builtin/providers/azurerm/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/Azure/azure-sdk-for-go/arm/cdn"
"github.com/Azure/azure-sdk-for-go/arm/compute"
"github.com/Azure/azure-sdk-for-go/arm/eventhub"
"github.com/Azure/azure-sdk-for-go/arm/keyvault"
"github.com/Azure/azure-sdk-for-go/arm/network"
"github.com/Azure/azure-sdk-for-go/arm/resources/resources"
Expand Down Expand Up @@ -58,6 +59,8 @@ type ArmClient struct {
cdnProfilesClient cdn.ProfilesClient
cdnEndpointsClient cdn.EndpointsClient

eventHubNamespacesClient eventhub.NamespacesClient

providers resources.ProvidersClient
resourceGroupClient resources.GroupsClient
tagsClient resources.TagsClient
Expand Down Expand Up @@ -209,6 +212,12 @@ func (c *Config) getArmClient() (*ArmClient, error) {
agc.Sender = autorest.CreateSender(withRequestLogging())
client.appGatewayClient = agc

ehnc := eventhub.NewNamespacesClient(c.SubscriptionID)
setUserAgent(&ehnc.Client)
ehnc.Authorizer = spt
ehnc.Sender = autorest.CreateSender(withRequestLogging())
client.eventHubNamespacesClient = ehnc

ifc := network.NewInterfacesClient(c.SubscriptionID)
setUserAgent(&ifc.Client)
ifc.Authorizer = spt
Expand Down
33 changes: 33 additions & 0 deletions builtin/providers/azurerm/import_arm_eventhub_namespace_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package azurerm

import (
"testing"

"fmt"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)

func TestAccAzureRMEventHubNamespace_importBasic(t *testing.T) {
resourceName := "azurerm_eventhub_namespace.test"

ri := acctest.RandInt()
config := fmt.Sprintf(testAccAzureRMEventHubNamespace_basic, ri, ri)

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testCheckAzureRMEventHubNamespaceDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: config,
},

resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
4 changes: 3 additions & 1 deletion builtin/providers/azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ func Provider() terraform.ResourceProvider {
"azurerm_cdn_endpoint": resourceArmCdnEndpoint(),
"azurerm_cdn_profile": resourceArmCdnProfile(),

"azurerm_eventhub_namespace": resourceArmEventHubNamespace(),

"azurerm_lb": resourceArmLoadBalancer(),
"azurerm_lb_backend_address_pool": resourceArmLoadBalancerBackendAddressPool(),
"azurerm_lb_nat_rule": resourceArmLoadBalancerNatRule(),
Expand Down Expand Up @@ -193,7 +195,7 @@ func registerAzureResourceProvidersWithSubscription(client *riviera.Client) erro
var err error
providerRegistrationOnce.Do(func() {
// We register Microsoft.Compute during client initialization
providers := []string{"Microsoft.Network", "Microsoft.Cdn", "Microsoft.Storage", "Microsoft.Sql", "Microsoft.Search", "Microsoft.Resources", "Microsoft.ServiceBus", "Microsoft.KeyVault"}
providers := []string{"Microsoft.Network", "Microsoft.Cdn", "Microsoft.Storage", "Microsoft.Sql", "Microsoft.Search", "Microsoft.Resources", "Microsoft.ServiceBus", "Microsoft.KeyVault", "Microsoft.EventHub"}

var wg sync.WaitGroup
wg.Add(len(providers))
Expand Down
211 changes: 211 additions & 0 deletions builtin/providers/azurerm/resource_arm_eventhub_namespace.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
package azurerm

import (
"fmt"
"log"
"strings"

"github.com/Azure/azure-sdk-for-go/arm/eventhub"
"github.com/hashicorp/terraform/helper/schema"
"net/http"
)

// Default Authorization Rule/Policy created by Azure, used to populate the
// default connection strings and keys
var eventHubNamespaceDefaultAuthorizationRule = "RootManageSharedAccessKey"

func resourceArmEventHubNamespace() *schema.Resource {
return &schema.Resource{
Create: resourceArmEventHubNamespaceCreate,
Read: resourceArmEventHubNamespaceRead,
Update: resourceArmEventHubNamespaceCreate,
Delete: resourceArmEventHubNamespaceDelete,
Importer: &schema.ResourceImporter{
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a test to make sure that the import works?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a test but it's failing - posting this here for later as a reminder of what needs fixing:

TF_ACC=1 go test ./builtin/providers/azurerm -v -run TestAccAzureRMEventHubNamespace_importBasic -timeout 120m
=== RUN   TestAccAzureRMEventHubNamespace_importBasic
--- FAIL: TestAccAzureRMEventHubNamespace_importBasic (371.43s)
    testing.go:265: Step 1 error: ImportStateVerify attributes not equivalent. Difference is shown below. Top is actual, bottom is expected.

        (map[string]string) {
        }


        (map[string]string) (len=2) {
         (string) (len=8) "location": (string) (len=6) "westus",
         (string) (len=19) "resource_group_name": (string) (len=28) "acctestRG-342930116917413830"
        }

FAIL
exit status 1
FAIL    github.com/hashicorp/terraform/builtin/providers/azurerm    371.449s

State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

"location": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
StateFunc: azureRMNormalizeLocation,
},

"resource_group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

"sku": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateEventHubNamespaceSku,
},

"capacity": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validateEventHubNamespaceCapacity,
},

"default_primary_connection_string": {
Type: schema.TypeString,
Computed: true,
},

"default_secondary_connection_string": {
Type: schema.TypeString,
Computed: true,
},

"default_primary_key": {
Type: schema.TypeString,
Computed: true,
},

"default_secondary_key": {
Type: schema.TypeString,
Computed: true,
},

"tags": tagsSchema(),
},
}
}

func resourceArmEventHubNamespaceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient)
namespaceClient := client.eventHubNamespacesClient
log.Printf("[INFO] preparing arguments for Azure ARM EventHub Namespace creation.")

name := d.Get("name").(string)
location := d.Get("location").(string)
resGroup := d.Get("resource_group_name").(string)
sku := d.Get("sku").(string)
capacity := int32(d.Get("capacity").(int))
tags := d.Get("tags").(map[string]interface{})

parameters := eventhub.NamespaceCreateOrUpdateParameters{
Location: &location,
Sku: &eventhub.Sku{
Name: eventhub.SkuName(sku),
Tier: eventhub.SkuTier(sku),
Capacity: &capacity,
},
Tags: expandTags(tags),
}

_, err := namespaceClient.CreateOrUpdate(resGroup, name, parameters, make(chan struct{}))
if err != nil {
return err
}

read, err := namespaceClient.Get(resGroup, name)
if err != nil {
return err
}

if read.ID == nil {
return fmt.Errorf("Cannot read EventHub Namespace %s (resource group %s) ID", name, resGroup)
}

d.SetId(*read.ID)

return resourceArmEventHubNamespaceRead(d, meta)
}

func resourceArmEventHubNamespaceRead(d *schema.ResourceData, meta interface{}) error {
namespaceClient := meta.(*ArmClient).eventHubNamespacesClient

id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resGroup := id.ResourceGroup
name := id.Path["namespaces"]

resp, err := namespaceClient.Get(resGroup, name)
if err != nil {
return fmt.Errorf("Error making Read request on Azure EventHub Namespace %s: %s", name, err)
}
if resp.StatusCode == http.StatusNotFound {
d.SetId("")
return nil
}

d.Set("name", resp.Name)
d.Set("location", azureRMNormalizeLocation(*resp.Location))
d.Set("resource_group_name", resGroup)
d.Set("sku", string(resp.Sku.Name))
d.Set("capacity", resp.Sku.Capacity)

keys, err := namespaceClient.ListKeys(resGroup, name, eventHubNamespaceDefaultAuthorizationRule)
if err != nil {
log.Printf("[ERROR] Unable to List default keys for Namespace %s: %s", name, err)
} else {
d.Set("default_primary_connection_string", keys.PrimaryConnectionString)
d.Set("default_secondary_connection_string", keys.SecondaryConnectionString)
d.Set("default_primary_key", keys.PrimaryKey)
d.Set("default_secondary_key", keys.SecondaryKey)
}

flattenAndSetTags(d, resp.Tags)

return nil
}

func resourceArmEventHubNamespaceDelete(d *schema.ResourceData, meta interface{}) error {

namespaceClient := meta.(*ArmClient).eventHubNamespacesClient

id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resGroup := id.ResourceGroup
name := id.Path["namespaces"]

resp, err := namespaceClient.Delete(resGroup, name, make(chan struct{}))

if resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("Error issuing Azure ARM delete request of EventHub Namespace'%s': %s", name, err)
}

return nil
}

func validateEventHubNamespaceSku(v interface{}, k string) (ws []string, errors []error) {
value := strings.ToLower(v.(string))
skus := map[string]bool{
"basic": true,
"standard": true,
}

if !skus[value] {
errors = append(errors, fmt.Errorf("EventHub Namespace SKU can only be Basic or Standard"))
}
return
}

func validateEventHubNamespaceCapacity(v interface{}, k string) (ws []string, errors []error) {
value := v.(int)
capacities := map[int]bool{
1: true,
2: true,
4: true,
}

if !capacities[value] {
errors = append(errors, fmt.Errorf("EventHub Namespace Capacity can only be 1, 2 or 4"))
}
return
}
Loading