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

New resources: iothub_endpoint_storage_container, iothub_endpoint_eventhub, iothub_endpoint_servicebus_queue, iothub_endpoint_servicebus_topic #3672

Closed
wants to merge 5 commits into from
Closed
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
19 changes: 19 additions & 0 deletions azurerm/helpers/validate/iothub.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,22 @@ func IoTHubConsumerGroupName(v interface{}, k string) (warnings []string, errors

return warnings, errors
}

func IoTHubEndpointName(v interface{}, _ string) (warnings []string, errors []error) {
value := v.(string)

reservedNames := []string{
"events",
"operationsMonitoringEvents",
"fileNotifications",
"$default",
}

for _, name := range reservedNames {
if name == value {
errors = append(errors, fmt.Errorf("The reserved endpoint name %s could not be used as a name for a custom endpoint", name))
}
}

return warnings, errors
}
25 changes: 25 additions & 0 deletions azurerm/helpers/validate/storage_container.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package validate

import (
"fmt"
"regexp"
)

func StorageContainerName(v interface{}, k string) (warnings []string, errors []error) {
value := v.(string)

if !regexp.MustCompile(`^\$root$|^\$web$|^[0-9a-z-]+$`).MatchString(value) {
errors = append(errors, fmt.Errorf(
"only lowercase alphanumeric characters and hyphens allowed in %q: %q",
k, value))
}
if len(value) < 3 || len(value) > 63 {
errors = append(errors, fmt.Errorf(
"%q must be between 3 and 63 characters: %q", k, value))
}
if regexp.MustCompile(`^-`).MatchString(value) {
errors = append(errors, fmt.Errorf(
"%q cannot begin with a hyphen: %q", k, value))
}
return warnings, errors
}
4 changes: 4 additions & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,10 @@ func Provider() terraform.ResourceProvider {
"azurerm_iot_dps_certificate": resourceArmIotDPSCertificate(),
"azurerm_iothub_consumer_group": resourceArmIotHubConsumerGroup(),
"azurerm_iothub": resourceArmIotHub(),
"azurerm_iothub_endpoint_eventhub": resourceArmIotHubEndpointEventHub(),
"azurerm_iothub_endpoint_servicebus_queue": resourceArmIotHubEndpointServiceBusQueue(),
"azurerm_iothub_endpoint_servicebus_topic": resourceArmIotHubEndpointServiceBusTopic(),
"azurerm_iothub_endpoint_storage_container": resourceArmIotHubEndpointStorageContainer(),
"azurerm_iothub_shared_access_policy": resourceArmIotHubSharedAccessPolicy(),
"azurerm_key_vault_access_policy": resourceArmKeyVaultAccessPolicy(),
"azurerm_key_vault_certificate": resourceArmKeyVaultCertificate(),
Expand Down
52 changes: 20 additions & 32 deletions azurerm/resource_arm_iothub.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,8 +222,10 @@ func resourceArmIotHub() *schema.Resource {
},

"endpoint": {
Type: schema.TypeList,
Optional: true,
Type: schema.TypeList,
Optional: true,
Computed: true,
Deprecated: "Use one of the `azurerm_iothub_endpoint_storage_container`, `azurerm_iothub_endpoint_eventhub`, `azurerm_iothub_endpoint_servicebus_queue`, `azurerm_iothub_endpoint_servicebus_topic` resources instead.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Expand Down Expand Up @@ -254,7 +256,7 @@ func resourceArmIotHub() *schema.Resource {
"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateIoTHubEndpointName,
ValidateFunc: validate.IoTHubEndpointName,
},
"batch_frequency_in_seconds": {
Type: schema.TypeInt,
Expand Down Expand Up @@ -460,32 +462,37 @@ func resourceArmIotHubCreateUpdate(d *schema.ResourceData, meta interface{}) err
location := azure.NormalizeLocation(d.Get("location").(string))
skuInfo := expandIoTHubSku(d)
t := d.Get("tags").(map[string]interface{})

fallbackRoute := expandIoTHubFallbackRoute(d)
routes := expandIoTHubRoutes(d)

endpoints, err := expandIoTHubEndpoints(d, subscriptionID)
if err != nil {
return fmt.Errorf("Error expanding `endpoint`: %+v", err)
routingProperties := devices.RoutingProperties{
Routes: routes,
FallbackRoute: fallbackRoute,
}

if _, ok := d.GetOk("endpoint"); ok {
endpoints, err := expandIoTHubEndpoints(d, subscriptionID)
if err != nil {
return fmt.Errorf("Error expanding `endpoint`: %+v", err)
}
routingProperties.Endpoints = endpoints
}

storageEndpoints, messagingEndpoints, enableFileUploadNotifications, err := expandIoTHubFileUpload(d)
if err != nil {
return fmt.Errorf("Error expanding `file_upload`: %+v", err)
}

routes := expandIoTHubRoutes(d)
ipFilterRules := expandIPFilterRules(d)

properties := devices.IotHubDescription{
Name: utils.String(name),
Location: utils.String(location),
Sku: skuInfo,
Properties: &devices.IotHubProperties{
IPFilterRules: ipFilterRules,
Routing: &devices.RoutingProperties{
Endpoints: endpoints,
Routes: routes,
FallbackRoute: fallbackRoute,
},
IPFilterRules: ipFilterRules,
Routing: &routingProperties,
StorageEndpoints: storageEndpoints,
MessagingEndpoints: messagingEndpoints,
EnableFileUploadNotifications: &enableFileUploadNotifications,
Expand Down Expand Up @@ -1052,25 +1059,6 @@ func flattenIoTHubFallbackRoute(input *devices.RoutingProperties) []interface{}
return []interface{}{output}
}

func validateIoTHubEndpointName(v interface{}, _ string) (warnings []string, errors []error) {
value := v.(string)

reservedNames := []string{
"events",
"operationsMonitoringEvents",
"fileNotifications",
"$default",
}

for _, name := range reservedNames {
if name == value {
errors = append(errors, fmt.Errorf("The reserved endpoint name %s could not be used as a name for a custom endpoint", name))
}
}

return warnings, errors
}

func validateIoTHubFileNameFormat(v interface{}, k string) (warnings []string, errors []error) {
value := v.(string)

Expand Down
238 changes: 238 additions & 0 deletions azurerm/resource_arm_iothub_endpoint_eventhub.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
package azurerm

import (
"fmt"
"regexp"
"strings"

"github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2018-12-01-preview/devices"
"github.com/hashicorp/terraform/helper/schema"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func resourceArmIotHubEndpointEventHub() *schema.Resource {
return &schema.Resource{
Create: resourceArmIotHubEndpointEventHubCreateUpdate,
Read: resourceArmIotHubEndpointEventHubRead,
Update: resourceArmIotHubEndpointEventHubCreateUpdate,
Delete: resourceArmIotHubEndpointEventHubDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

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

"resource_group_name": azure.SchemaResourceGroupName(),

"iothub_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.IoTHubName,
},

"connection_string": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
sharedAccessKeyRegex := regexp.MustCompile("SharedAccessKey=[^;]+")
sbProtocolRegex := regexp.MustCompile("sb://([^:]+)(:5671)?/;")

maskedNew := sbProtocolRegex.ReplaceAllString(new, "sb://$1:5671/;")
maskedNew = sharedAccessKeyRegex.ReplaceAllString(maskedNew, "SharedAccessKey=****")
return (new == d.Get(k).(string)) && (maskedNew == old)
},
Sensitive: true,
},
},
}
}

func resourceArmIotHubEndpointEventHubCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).iothub.ResourceClient
ctx := meta.(*ArmClient).StopContext
subscriptionID := meta.(*ArmClient).subscriptionId

iothubName := d.Get("iothub_name").(string)
resourceGroup := d.Get("resource_group_name").(string)

azureRMLockByName(iothubName, iothubResourceName)
defer azureRMUnlockByName(iothubName, iothubResourceName)

iothub, err := client.Get(ctx, resourceGroup, iothubName)
if err != nil {
if utils.ResponseWasNotFound(iothub.Response) {
return fmt.Errorf("IotHub %q (Resource Group %q) was not found", iothubName, resourceGroup)
}

return fmt.Errorf("Error loading IotHub %q (Resource Group %q): %+v", iothubName, resourceGroup, err)
}

endpointName := d.Get("name").(string)

resourceId := fmt.Sprintf("%s/Endpoints/%s", *iothub.ID, endpointName)

connectionStr := d.Get("connection_string").(string)

eventhubEndpoint := devices.RoutingEventHubProperties{
ConnectionString: &connectionStr,
Name: &endpointName,
SubscriptionID: &subscriptionID,
ResourceGroup: &resourceGroup,
}

routing := iothub.Properties.Routing

if routing == nil {
routing = &devices.RoutingProperties{}
}

if routing.Endpoints == nil {
routing.Endpoints = &devices.RoutingEndpoints{}
}

if routing.Endpoints.EventHubs == nil {
eventHubs := make([]devices.RoutingEventHubProperties, 0)
routing.Endpoints.EventHubs = &eventHubs
}

endpoints := make([]devices.RoutingEventHubProperties, 0)

alreadyExists := false
for _, existingEndpoint := range *routing.Endpoints.EventHubs {
if strings.EqualFold(*existingEndpoint.Name, endpointName) {
if d.IsNewResource() && requireResourcesToBeImported {
return tf.ImportAsExistsError("azurerm_iothub_endpoint_eventhub", resourceId)
}
endpoints = append(endpoints, eventhubEndpoint)
alreadyExists = true

} else {
endpoints = append(endpoints, existingEndpoint)
}
}

if d.IsNewResource() {
endpoints = append(endpoints, eventhubEndpoint)
} else if !alreadyExists {
return fmt.Errorf("Unable to find EventHub Endpoint %q defined for IotHub %q (Resource Group %q)", endpointName, iothubName, resourceGroup)
}

routing.Endpoints.EventHubs = &endpoints

future, err := client.CreateOrUpdate(ctx, resourceGroup, iothubName, iothub, "")
if err != nil {
return fmt.Errorf("Error creating/updating IotHub %q (Resource Group %q): %+v", iothubName, resourceGroup, err)
}

if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("Error waiting for the completion of the creating/updating of IotHub %q (Resource Group %q): %+v", iothubName, resourceGroup, err)
}

d.SetId(resourceId)

return resourceArmIotHubEndpointEventHubRead(d, meta)
}

func resourceArmIotHubEndpointEventHubRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).iothub.ResourceClient
ctx := meta.(*ArmClient).StopContext

parsedIothubEndpointId, err := parseAzureResourceID(d.Id())

if err != nil {
return err
}

resourceGroup := parsedIothubEndpointId.ResourceGroup
iothubName := parsedIothubEndpointId.Path["IotHubs"]
endpointName := parsedIothubEndpointId.Path["Endpoints"]

iothub, err := client.Get(ctx, resourceGroup, iothubName)
if err != nil {
return fmt.Errorf("Error loading IotHub %q (Resource Group %q): %+v", iothubName, resourceGroup, err)
}

d.Set("name", endpointName)
d.Set("iothub_name", iothubName)
d.Set("resource_group_name", resourceGroup)

if iothub.Properties == nil || iothub.Properties.Routing == nil || iothub.Properties.Routing.Endpoints == nil {
return nil
}

if endpoints := iothub.Properties.Routing.Endpoints.EventHubs; endpoints != nil {
for _, endpoint := range *endpoints {
if strings.EqualFold(*endpoint.Name, endpointName) {
d.Set("connection_string", endpoint.ConnectionString)
}
}
}

return nil
}

func resourceArmIotHubEndpointEventHubDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).iothub.ResourceClient
ctx := meta.(*ArmClient).StopContext

parsedIothubEndpointId, err := parseAzureResourceID(d.Id())

if err != nil {
return err
}

resourceGroup := parsedIothubEndpointId.ResourceGroup
iothubName := parsedIothubEndpointId.Path["IotHubs"]
endpointName := parsedIothubEndpointId.Path["Endpoints"]

azureRMLockByName(iothubName, iothubResourceName)
defer azureRMUnlockByName(iothubName, iothubResourceName)

iothub, err := client.Get(ctx, resourceGroup, iothubName)
if err != nil {
if utils.ResponseWasNotFound(iothub.Response) {
return fmt.Errorf("IotHub %q (Resource Group %q) was not found", iothubName, resourceGroup)
}

return fmt.Errorf("Error loading IotHub %q (Resource Group %q): %+v", iothubName, resourceGroup, err)
}

if iothub.Properties == nil || iothub.Properties.Routing == nil || iothub.Properties.Routing.Endpoints == nil {
return nil
}
endpoints := iothub.Properties.Routing.Endpoints.EventHubs

if endpoints == nil {
return nil
}

updatedEndpoints := make([]devices.RoutingEventHubProperties, 0)
for _, endpoint := range *endpoints {
if !strings.EqualFold(*endpoint.Name, endpointName) {
updatedEndpoints = append(updatedEndpoints, endpoint)
}
}

iothub.Properties.Routing.Endpoints.EventHubs = &updatedEndpoints

future, err := client.CreateOrUpdate(ctx, resourceGroup, iothubName, iothub, "")
if err != nil {
return fmt.Errorf("Error updating IotHub %q (Resource Group %q) with EventHub Endpoint %q: %+v", iothubName, resourceGroup, endpointName, err)
}

if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("Error waiting for IotHub %q (Resource Group %q) to finish updating EventHub Endpoint %q: %+v", iothubName, resourceGroup, endpointName, err)
}

return nil
}
Loading