From e5c5c621be84fdcfd6011da7a1c07a28dab868b8 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Thu, 28 Sep 2017 11:49:35 +0530 Subject: [PATCH 01/69] added iothub dependency --- .gitignore | 2 + .../resource_arm_iothub_resource_provider.go | 0 .../azure-sdk-for-go/arm/iothub/client.go | 53 + .../azure-sdk-for-go/arm/iothub/models.go | 539 ++++++ .../azure-sdk-for-go/arm/iothub/resource.go | 1577 +++++++++++++++++ .../azure-sdk-for-go/arm/iothub/version.go | 28 + vendor/vendor.json | 6 + 7 files changed, 2205 insertions(+) create mode 100644 azurerm/resource_arm_iothub_resource_provider.go create mode 100755 vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go create mode 100755 vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go create mode 100755 vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go create mode 100755 vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go diff --git a/.gitignore b/.gitignore index 759d64580fcd..5f873cf88e6c 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,5 @@ website/vendor # Test exclusions !command/test-fixtures/**/*.tfstate !command/test-fixtures/**/.terraform/ + +.env.sh diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go new file mode 100755 index 000000000000..b54c132eeeee --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go @@ -0,0 +1,53 @@ +// Package iothub implements the Azure ARM Iothub service API version +// 2016-02-03. +// +// Use this API to manage the IoT hubs in your subscription. +package iothub + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" +) + +const ( + // DefaultBaseURI is the default URI used for the service Iothub + DefaultBaseURI = "https://management.azure.com" +) + +// ManagementClient is the base client for Iothub. +type ManagementClient struct { + autorest.Client + BaseURI string + SubscriptionID string +} + +// New creates an instance of the ManagementClient client. +func New(subscriptionID string) ManagementClient { + return NewWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewWithBaseURI creates an instance of the ManagementClient client. +func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { + return ManagementClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: baseURI, + SubscriptionID: subscriptionID, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go new file mode 100755 index 000000000000..6fa4abb25319 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go @@ -0,0 +1,539 @@ +package iothub + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" + "github.com/Azure/go-autorest/autorest/to" + "net/http" +) + +// AccessRights enumerates the values for access rights. +type AccessRights string + +const ( + // DeviceConnect specifies the device connect state for access rights. + DeviceConnect AccessRights = "DeviceConnect" + // RegistryRead specifies the registry read state for access rights. + RegistryRead AccessRights = "RegistryRead" + // RegistryReadDeviceConnect specifies the registry read device connect + // state for access rights. + RegistryReadDeviceConnect AccessRights = "RegistryRead, DeviceConnect" + // RegistryReadRegistryWrite specifies the registry read registry write + // state for access rights. + RegistryReadRegistryWrite AccessRights = "RegistryRead, RegistryWrite" + // RegistryReadRegistryWriteDeviceConnect specifies the registry read + // registry write device connect state for access rights. + RegistryReadRegistryWriteDeviceConnect AccessRights = "RegistryRead, RegistryWrite, DeviceConnect" + // RegistryReadRegistryWriteServiceConnect specifies the registry read + // registry write service connect state for access rights. + RegistryReadRegistryWriteServiceConnect AccessRights = "RegistryRead, RegistryWrite, ServiceConnect" + // RegistryReadRegistryWriteServiceConnectDeviceConnect specifies the + // registry read registry write service connect device connect state for + // access rights. + RegistryReadRegistryWriteServiceConnectDeviceConnect AccessRights = "RegistryRead, RegistryWrite, ServiceConnect, DeviceConnect" + // RegistryReadServiceConnect specifies the registry read service connect + // state for access rights. + RegistryReadServiceConnect AccessRights = "RegistryRead, ServiceConnect" + // RegistryReadServiceConnectDeviceConnect specifies the registry read + // service connect device connect state for access rights. + RegistryReadServiceConnectDeviceConnect AccessRights = "RegistryRead, ServiceConnect, DeviceConnect" + // RegistryWrite specifies the registry write state for access rights. + RegistryWrite AccessRights = "RegistryWrite" + // RegistryWriteDeviceConnect specifies the registry write device connect + // state for access rights. + RegistryWriteDeviceConnect AccessRights = "RegistryWrite, DeviceConnect" + // RegistryWriteServiceConnect specifies the registry write service connect + // state for access rights. + RegistryWriteServiceConnect AccessRights = "RegistryWrite, ServiceConnect" + // RegistryWriteServiceConnectDeviceConnect specifies the registry write + // service connect device connect state for access rights. + RegistryWriteServiceConnectDeviceConnect AccessRights = "RegistryWrite, ServiceConnect, DeviceConnect" + // ServiceConnect specifies the service connect state for access rights. + ServiceConnect AccessRights = "ServiceConnect" + // ServiceConnectDeviceConnect specifies the service connect device connect + // state for access rights. + ServiceConnectDeviceConnect AccessRights = "ServiceConnect, DeviceConnect" +) + +// Capabilities enumerates the values for capabilities. +type Capabilities string + +const ( + // DeviceManagement specifies the device management state for capabilities. + DeviceManagement Capabilities = "DeviceManagement" + // None specifies the none state for capabilities. + None Capabilities = "None" +) + +// IPFilterActionType enumerates the values for ip filter action type. +type IPFilterActionType string + +const ( + // Accept specifies the accept state for ip filter action type. + Accept IPFilterActionType = "Accept" + // Reject specifies the reject state for ip filter action type. + Reject IPFilterActionType = "Reject" +) + +// JobStatus enumerates the values for job status. +type JobStatus string + +const ( + // Cancelled specifies the cancelled state for job status. + Cancelled JobStatus = "cancelled" + // Completed specifies the completed state for job status. + Completed JobStatus = "completed" + // Enqueued specifies the enqueued state for job status. + Enqueued JobStatus = "enqueued" + // Failed specifies the failed state for job status. + Failed JobStatus = "failed" + // Running specifies the running state for job status. + Running JobStatus = "running" + // Unknown specifies the unknown state for job status. + Unknown JobStatus = "unknown" +) + +// JobType enumerates the values for job type. +type JobType string + +const ( + // JobTypeBackup specifies the job type backup state for job type. + JobTypeBackup JobType = "backup" + // JobTypeExport specifies the job type export state for job type. + JobTypeExport JobType = "export" + // JobTypeFactoryResetDevice specifies the job type factory reset device + // state for job type. + JobTypeFactoryResetDevice JobType = "factoryResetDevice" + // JobTypeFirmwareUpdate specifies the job type firmware update state for + // job type. + JobTypeFirmwareUpdate JobType = "firmwareUpdate" + // JobTypeImport specifies the job type import state for job type. + JobTypeImport JobType = "import" + // JobTypeReadDeviceProperties specifies the job type read device + // properties state for job type. + JobTypeReadDeviceProperties JobType = "readDeviceProperties" + // JobTypeRebootDevice specifies the job type reboot device state for job + // type. + JobTypeRebootDevice JobType = "rebootDevice" + // JobTypeUnknown specifies the job type unknown state for job type. + JobTypeUnknown JobType = "unknown" + // JobTypeUpdateDeviceConfiguration specifies the job type update device + // configuration state for job type. + JobTypeUpdateDeviceConfiguration JobType = "updateDeviceConfiguration" + // JobTypeWriteDeviceProperties specifies the job type write device + // properties state for job type. + JobTypeWriteDeviceProperties JobType = "writeDeviceProperties" +) + +// NameUnavailabilityReason enumerates the values for name unavailability +// reason. +type NameUnavailabilityReason string + +const ( + // AlreadyExists specifies the already exists state for name unavailability + // reason. + AlreadyExists NameUnavailabilityReason = "AlreadyExists" + // Invalid specifies the invalid state for name unavailability reason. + Invalid NameUnavailabilityReason = "Invalid" +) + +// OperationMonitoringLevel enumerates the values for operation monitoring +// level. +type OperationMonitoringLevel string + +const ( + // OperationMonitoringLevelError specifies the operation monitoring level + // error state for operation monitoring level. + OperationMonitoringLevelError OperationMonitoringLevel = "Error" + // OperationMonitoringLevelErrorInformation specifies the operation + // monitoring level error information state for operation monitoring level. + OperationMonitoringLevelErrorInformation OperationMonitoringLevel = "Error, Information" + // OperationMonitoringLevelInformation specifies the operation monitoring + // level information state for operation monitoring level. + OperationMonitoringLevelInformation OperationMonitoringLevel = "Information" + // OperationMonitoringLevelNone specifies the operation monitoring level + // none state for operation monitoring level. + OperationMonitoringLevelNone OperationMonitoringLevel = "None" +) + +// ScaleType enumerates the values for scale type. +type ScaleType string + +const ( + // ScaleTypeAutomatic specifies the scale type automatic state for scale + // type. + ScaleTypeAutomatic ScaleType = "Automatic" + // ScaleTypeManual specifies the scale type manual state for scale type. + ScaleTypeManual ScaleType = "Manual" + // ScaleTypeNone specifies the scale type none state for scale type. + ScaleTypeNone ScaleType = "None" +) + +// Sku enumerates the values for sku. +type Sku string + +const ( + // F1 specifies the f1 state for sku. + F1 Sku = "F1" + // S1 specifies the s1 state for sku. + S1 Sku = "S1" + // S2 specifies the s2 state for sku. + S2 Sku = "S2" + // S3 specifies the s3 state for sku. + S3 Sku = "S3" +) + +// SkuTier enumerates the values for sku tier. +type SkuTier string + +const ( + // Free specifies the free state for sku tier. + Free SkuTier = "Free" + // Standard specifies the standard state for sku tier. + Standard SkuTier = "Standard" +) + +// Capacity is ioT Hub capacity information. +type Capacity struct { + Minimum *int64 `json:"minimum,omitempty"` + Maximum *int64 `json:"maximum,omitempty"` + Default *int64 `json:"default,omitempty"` + ScaleType ScaleType `json:"scaleType,omitempty"` +} + +// CloudToDeviceProperties is the IoT hub cloud-to-device messaging properties. +type CloudToDeviceProperties struct { + MaxDeliveryCount *int32 `json:"maxDeliveryCount,omitempty"` + DefaultTTLAsIso8601 *string `json:"defaultTtlAsIso8601,omitempty"` + Feedback *FeedbackProperties `json:"feedback,omitempty"` +} + +// Description is the description of the IoT hub. +type Description struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Subscriptionid *string `json:"subscriptionid,omitempty"` + Resourcegroup *string `json:"resourcegroup,omitempty"` + Etag *string `json:"etag,omitempty"` + Properties *Properties `json:"properties,omitempty"` + Sku *SkuInfo `json:"sku,omitempty"` +} + +// DescriptionListResult is the JSON-serialized array of IotHubDescription +// objects with a next link. +type DescriptionListResult struct { + autorest.Response `json:"-"` + Value *[]Description `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// DescriptionListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client DescriptionListResult) DescriptionListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// ErrorDetails is error details. +type ErrorDetails struct { + Code *string `json:"Code,omitempty"` + HTTPStatusCode *string `json:"HttpStatusCode,omitempty"` + Message *string `json:"Message,omitempty"` + Details *string `json:"Details,omitempty"` +} + +// EventHubConsumerGroupInfo is the properties of the EventHubConsumerGroupInfo +// object. +type EventHubConsumerGroupInfo struct { + autorest.Response `json:"-"` + Tags *map[string]*string `json:"tags,omitempty"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` +} + +// EventHubConsumerGroupsListResult is the JSON-serialized array of Event +// Hub-compatible consumer group names with a next link. +type EventHubConsumerGroupsListResult struct { + autorest.Response `json:"-"` + Value *[]string `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// EventHubConsumerGroupsListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client EventHubConsumerGroupsListResult) EventHubConsumerGroupsListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// EventHubProperties is the properties of the provisioned Event Hub-compatible +// endpoint used by the IoT hub. +type EventHubProperties struct { + RetentionTimeInDays *int64 `json:"retentionTimeInDays,omitempty"` + PartitionCount *int32 `json:"partitionCount,omitempty"` + PartitionIds *[]string `json:"partitionIds,omitempty"` + Path *string `json:"path,omitempty"` + Endpoint *string `json:"endpoint,omitempty"` +} + +// ExportDevicesRequest is use to provide parameters when requesting an export +// of all devices in the IoT hub. +type ExportDevicesRequest struct { + ExportBlobContainerURI *string `json:"ExportBlobContainerUri,omitempty"` + ExcludeKeys *bool `json:"ExcludeKeys,omitempty"` +} + +// FeedbackProperties is the properties of the feedback queue for +// cloud-to-device messages. +type FeedbackProperties struct { + LockDurationAsIso8601 *string `json:"lockDurationAsIso8601,omitempty"` + TTLAsIso8601 *string `json:"ttlAsIso8601,omitempty"` + MaxDeliveryCount *int32 `json:"maxDeliveryCount,omitempty"` +} + +// ImportDevicesRequest is use to provide parameters when requesting an import +// of all devices in the hub. +type ImportDevicesRequest struct { + InputBlobContainerURI *string `json:"InputBlobContainerUri,omitempty"` + OutputBlobContainerURI *string `json:"OutputBlobContainerUri,omitempty"` +} + +// IPFilterRule is the IP filter rules for the IoT hub. +type IPFilterRule struct { + FilterName *string `json:"filterName,omitempty"` + Action IPFilterActionType `json:"action,omitempty"` + IPMask *string `json:"ipMask,omitempty"` +} + +// JobResponse is the properties of the Job Response object. +type JobResponse struct { + autorest.Response `json:"-"` + JobID *string `json:"jobId,omitempty"` + StartTimeUtc *date.TimeRFC1123 `json:"startTimeUtc,omitempty"` + EndTimeUtc *date.TimeRFC1123 `json:"endTimeUtc,omitempty"` + Type JobType `json:"type,omitempty"` + Status JobStatus `json:"status,omitempty"` + FailureReason *string `json:"failureReason,omitempty"` + StatusMessage *string `json:"statusMessage,omitempty"` + ParentJobID *string `json:"parentJobId,omitempty"` +} + +// JobResponseListResult is the JSON-serialized array of JobResponse objects +// with a next link. +type JobResponseListResult struct { + autorest.Response `json:"-"` + Value *[]JobResponse `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// JobResponseListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client JobResponseListResult) JobResponseListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// MessagingEndpointProperties is the properties of the messaging endpoints +// used by this IoT hub. +type MessagingEndpointProperties struct { + LockDurationAsIso8601 *string `json:"lockDurationAsIso8601,omitempty"` + TTLAsIso8601 *string `json:"ttlAsIso8601,omitempty"` + MaxDeliveryCount *int32 `json:"maxDeliveryCount,omitempty"` +} + +// NameAvailabilityInfo is the properties indicating whether a given IoT hub +// name is available. +type NameAvailabilityInfo struct { + autorest.Response `json:"-"` + NameAvailable *bool `json:"nameAvailable,omitempty"` + Reason NameUnavailabilityReason `json:"reason,omitempty"` + Message *string `json:"message,omitempty"` +} + +// OperationInputs is input values. +type OperationInputs struct { + Name *string `json:"Name,omitempty"` +} + +// OperationsMonitoringProperties is the operations monitoring properties for +// the IoT hub. The possible keys to the dictionary are Connections, +// DeviceTelemetry, C2DCommands, DeviceIdentityOperations, +// FileUploadOperations. +type OperationsMonitoringProperties struct { + Events *map[string]*OperationMonitoringLevel `json:"events,omitempty"` +} + +// Properties is the properties of an IoT hub. +type Properties struct { + AuthorizationPolicies *[]SharedAccessSignatureAuthorizationRule `json:"authorizationPolicies,omitempty"` + IPFilterRules *[]IPFilterRule `json:"ipFilterRules,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` + HostName *string `json:"hostName,omitempty"` + EventHubEndpoints *map[string]*EventHubProperties `json:"eventHubEndpoints,omitempty"` + StorageEndpoints *map[string]*StorageEndpointProperties `json:"storageEndpoints,omitempty"` + MessagingEndpoints *map[string]*MessagingEndpointProperties `json:"messagingEndpoints,omitempty"` + EnableFileUploadNotifications *bool `json:"enableFileUploadNotifications,omitempty"` + CloudToDevice *CloudToDeviceProperties `json:"cloudToDevice,omitempty"` + Comments *string `json:"comments,omitempty"` + OperationsMonitoringProperties *OperationsMonitoringProperties `json:"operationsMonitoringProperties,omitempty"` + Features Capabilities `json:"features,omitempty"` +} + +// QuotaMetricInfo is quota metrics properties. +type QuotaMetricInfo struct { + Name *string `json:"Name,omitempty"` + CurrentValue *int64 `json:"CurrentValue,omitempty"` + MaxValue *int64 `json:"MaxValue,omitempty"` +} + +// QuotaMetricInfoListResult is the JSON-serialized array of +// IotHubQuotaMetricInfo objects with a next link. +type QuotaMetricInfoListResult struct { + autorest.Response `json:"-"` + Value *[]QuotaMetricInfo `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// QuotaMetricInfoListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client QuotaMetricInfoListResult) QuotaMetricInfoListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// RegistryStatistics is identity registry statistics. +type RegistryStatistics struct { + autorest.Response `json:"-"` + TotalDeviceCount *int64 `json:"totalDeviceCount,omitempty"` + EnabledDeviceCount *int64 `json:"enabledDeviceCount,omitempty"` + DisabledDeviceCount *int64 `json:"disabledDeviceCount,omitempty"` +} + +// Resource is +type Resource struct { + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` +} + +// SetObject is +type SetObject struct { + autorest.Response `json:"-"` + Value *map[string]interface{} `json:"value,omitempty"` +} + +// SharedAccessSignatureAuthorizationRule is the properties of an IoT hub +// shared access policy. +type SharedAccessSignatureAuthorizationRule struct { + autorest.Response `json:"-"` + KeyName *string `json:"keyName,omitempty"` + PrimaryKey *string `json:"primaryKey,omitempty"` + SecondaryKey *string `json:"secondaryKey,omitempty"` + Rights AccessRights `json:"rights,omitempty"` +} + +// SharedAccessSignatureAuthorizationRuleListResult is the list of shared +// access policies with a next link. +type SharedAccessSignatureAuthorizationRuleListResult struct { + autorest.Response `json:"-"` + Value *[]SharedAccessSignatureAuthorizationRule `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// SharedAccessSignatureAuthorizationRuleListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client SharedAccessSignatureAuthorizationRuleListResult) SharedAccessSignatureAuthorizationRuleListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// SkuDescription is sKU properties. +type SkuDescription struct { + ResourceType *string `json:"resourceType,omitempty"` + Sku *SkuInfo `json:"sku,omitempty"` + Capacity *Capacity `json:"capacity,omitempty"` +} + +// SkuDescriptionListResult is the JSON-serialized array of +// IotHubSkuDescription objects with a next link. +type SkuDescriptionListResult struct { + autorest.Response `json:"-"` + Value *[]SkuDescription `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// SkuDescriptionListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client SkuDescriptionListResult) SkuDescriptionListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// SkuInfo is information about the SKU of the IoT hub. +type SkuInfo struct { + Name Sku `json:"name,omitempty"` + Tier SkuTier `json:"tier,omitempty"` + Capacity *int64 `json:"capacity,omitempty"` +} + +// StorageEndpointProperties is the properties of the Azure Storage endpoint +// for file upload. +type StorageEndpointProperties struct { + SasTTLAsIso8601 *string `json:"sasTtlAsIso8601,omitempty"` + ConnectionString *string `json:"connectionString,omitempty"` + ContainerName *string `json:"containerName,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go new file mode 100755 index 000000000000..83b97042999c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go @@ -0,0 +1,1577 @@ +package iothub + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// ResourceClient is the use this API to manage the IoT hubs in your +// subscription. +type ResourceClient struct { + ManagementClient +} + +// NewResourceClient creates an instance of the ResourceClient client. +func NewResourceClient(subscriptionID string) ResourceClient { + return NewResourceClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewResourceClientWithBaseURI creates an instance of the ResourceClient +// client. +func NewResourceClientWithBaseURI(baseURI string, subscriptionID string) ResourceClient { + return ResourceClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CheckNameAvailability check if an IoT hub name is available. +// +// operationInputs is set the name parameter in the OperationInputs structure +// to the name of the IoT hub to check. +func (client ResourceClient) CheckNameAvailability(operationInputs OperationInputs) (result NameAvailabilityInfo, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: operationInputs, + Constraints: []validation.Constraint{{Target: "operationInputs.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "iothub.ResourceClient", "CheckNameAvailability") + } + + req, err := client.CheckNameAvailabilityPreparer(operationInputs) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CheckNameAvailability", nil, "Failure preparing request") + return + } + + resp, err := client.CheckNameAvailabilitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CheckNameAvailability", resp, "Failure sending request") + return + } + + result, err = client.CheckNameAvailabilityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CheckNameAvailability", resp, "Failure responding to request") + } + + return +} + +// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. +func (client ResourceClient) CheckNameAvailabilityPreparer(operationInputs OperationInputs) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Devices/checkNameAvailability", pathParameters), + autorest.WithJSON(operationInputs), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always +// closes the http.Response Body. +func (client ResourceClient) CheckNameAvailabilityResponder(resp *http.Response) (result NameAvailabilityInfo, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateEventHubConsumerGroup add a consumer group to an Event Hub-compatible +// endpoint in an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the +// name of the Event Hub-compatible endpoint in the IoT hub. name is the name +// of the consumer group to add. +func (client ResourceClient) CreateEventHubConsumerGroup(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (result EventHubConsumerGroupInfo, err error) { + req, err := client.CreateEventHubConsumerGroupPreparer(resourceGroupName, resourceName, eventHubEndpointName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CreateEventHubConsumerGroup", nil, "Failure preparing request") + return + } + + resp, err := client.CreateEventHubConsumerGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CreateEventHubConsumerGroup", resp, "Failure sending request") + return + } + + result, err = client.CreateEventHubConsumerGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CreateEventHubConsumerGroup", resp, "Failure responding to request") + } + + return +} + +// CreateEventHubConsumerGroupPreparer prepares the CreateEventHubConsumerGroup request. +func (client ResourceClient) CreateEventHubConsumerGroupPreparer(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventHubEndpointName": autorest.Encode("path", eventHubEndpointName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups/{name}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// CreateEventHubConsumerGroupSender sends the CreateEventHubConsumerGroup request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) CreateEventHubConsumerGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// CreateEventHubConsumerGroupResponder handles the response to the CreateEventHubConsumerGroup request. The method always +// closes the http.Response Body. +func (client ResourceClient) CreateEventHubConsumerGroupResponder(resp *http.Response) (result EventHubConsumerGroupInfo, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdate create or update the metadata of an Iot hub. The usual +// pattern to modify a property is to retrieve the IoT hub metadata and +// security metadata, and then combine them with the modified values in a new +// body to update the IoT hub. This method may poll for completion. Polling can +// be canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub to create or update. +// iotHubDescription is the IoT hub metadata and security metadata. +func (client ResourceClient) CreateOrUpdate(resourceGroupName string, resourceName string, iotHubDescription Description, cancel <-chan struct{}) (<-chan Description, <-chan error) { + resultChan := make(chan Description, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: iotHubDescription, + Constraints: []validation.Constraint{{Target: "iotHubDescription.Subscriptionid", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "iotHubDescription.Resourcegroup", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "iotHubDescription.Properties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, + {Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}, + {Target: "iotHubDescription.Properties.CloudToDevice.Feedback", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, + {Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}, + }}, + }}, + }}, + {Target: "iotHubDescription.Sku", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "iotHubDescription.Sku.Capacity", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "iothub.ResourceClient", "CreateOrUpdate") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result Description + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, resourceName, iotHubDescription, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ResourceClient) CreateOrUpdatePreparer(resourceGroupName string, resourceName string, iotHubDescription Description, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}", pathParameters), + autorest.WithJSON(iotHubDescription), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ResourceClient) CreateOrUpdateResponder(resp *http.Response) (result Description, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete an IoT hub. This method may poll for completion. Polling can +// be canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub to delete. +func (client ResourceClient) Delete(resourceGroupName string, resourceName string, cancel <-chan struct{}) (<-chan SetObject, <-chan error) { + resultChan := make(chan SetObject, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result SetObject + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, resourceName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// DeletePreparer prepares the Delete request. +func (client ResourceClient) DeletePreparer(resourceGroupName string, resourceName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ResourceClient) DeleteResponder(resp *http.Response) (result SetObject, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK, http.StatusNoContent, http.StatusNotFound), + autorest.ByUnmarshallingJSON(&result.Value), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// DeleteEventHubConsumerGroup delete a consumer group from an Event +// Hub-compatible endpoint in an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the +// name of the Event Hub-compatible endpoint in the IoT hub. name is the name +// of the consumer group to delete. +func (client ResourceClient) DeleteEventHubConsumerGroup(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (result autorest.Response, err error) { + req, err := client.DeleteEventHubConsumerGroupPreparer(resourceGroupName, resourceName, eventHubEndpointName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "DeleteEventHubConsumerGroup", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteEventHubConsumerGroupSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "DeleteEventHubConsumerGroup", resp, "Failure sending request") + return + } + + result, err = client.DeleteEventHubConsumerGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "DeleteEventHubConsumerGroup", resp, "Failure responding to request") + } + + return +} + +// DeleteEventHubConsumerGroupPreparer prepares the DeleteEventHubConsumerGroup request. +func (client ResourceClient) DeleteEventHubConsumerGroupPreparer(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventHubEndpointName": autorest.Encode("path", eventHubEndpointName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups/{name}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// DeleteEventHubConsumerGroupSender sends the DeleteEventHubConsumerGroup request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) DeleteEventHubConsumerGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// DeleteEventHubConsumerGroupResponder handles the response to the DeleteEventHubConsumerGroup request. The method always +// closes the http.Response Body. +func (client ResourceClient) DeleteEventHubConsumerGroupResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// ExportDevices exports all the device identities in the IoT hub identity +// registry to an Azure Storage blob container. For more information, see: +// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. exportDevicesParameters is the +// parameters that specify the export devices operation. +func (client ResourceClient) ExportDevices(resourceGroupName string, resourceName string, exportDevicesParameters ExportDevicesRequest) (result JobResponse, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: exportDevicesParameters, + Constraints: []validation.Constraint{{Target: "exportDevicesParameters.ExportBlobContainerURI", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "exportDevicesParameters.ExcludeKeys", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "iothub.ResourceClient", "ExportDevices") + } + + req, err := client.ExportDevicesPreparer(resourceGroupName, resourceName, exportDevicesParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ExportDevices", nil, "Failure preparing request") + return + } + + resp, err := client.ExportDevicesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ExportDevices", resp, "Failure sending request") + return + } + + result, err = client.ExportDevicesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ExportDevices", resp, "Failure responding to request") + } + + return +} + +// ExportDevicesPreparer prepares the ExportDevices request. +func (client ResourceClient) ExportDevicesPreparer(resourceGroupName string, resourceName string, exportDevicesParameters ExportDevicesRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/exportDevices", pathParameters), + autorest.WithJSON(exportDevicesParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ExportDevicesSender sends the ExportDevices request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) ExportDevicesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ExportDevicesResponder handles the response to the ExportDevices request. The method always +// closes the http.Response Body. +func (client ResourceClient) ExportDevicesResponder(resp *http.Response) (result JobResponse, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Get get the non-security related metadata of an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. +func (client ResourceClient) Get(resourceGroupName string, resourceName string) (result Description, err error) { + req, err := client.GetPreparer(resourceGroupName, resourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ResourceClient) GetPreparer(resourceGroupName string, resourceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ResourceClient) GetResponder(resp *http.Response) (result Description, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetEventHubConsumerGroup get a consumer group from the Event Hub-compatible +// device-to-cloud endpoint for an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the +// name of the Event Hub-compatible endpoint in the IoT hub. name is the name +// of the consumer group to retrieve. +func (client ResourceClient) GetEventHubConsumerGroup(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (result EventHubConsumerGroupInfo, err error) { + req, err := client.GetEventHubConsumerGroupPreparer(resourceGroupName, resourceName, eventHubEndpointName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetEventHubConsumerGroup", nil, "Failure preparing request") + return + } + + resp, err := client.GetEventHubConsumerGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetEventHubConsumerGroup", resp, "Failure sending request") + return + } + + result, err = client.GetEventHubConsumerGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetEventHubConsumerGroup", resp, "Failure responding to request") + } + + return +} + +// GetEventHubConsumerGroupPreparer prepares the GetEventHubConsumerGroup request. +func (client ResourceClient) GetEventHubConsumerGroupPreparer(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventHubEndpointName": autorest.Encode("path", eventHubEndpointName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups/{name}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetEventHubConsumerGroupSender sends the GetEventHubConsumerGroup request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) GetEventHubConsumerGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetEventHubConsumerGroupResponder handles the response to the GetEventHubConsumerGroup request. The method always +// closes the http.Response Body. +func (client ResourceClient) GetEventHubConsumerGroupResponder(resp *http.Response) (result EventHubConsumerGroupInfo, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetJob get the details of a job from an IoT hub. For more information, see: +// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. jobID is the job identifier. +func (client ResourceClient) GetJob(resourceGroupName string, resourceName string, jobID string) (result JobResponse, err error) { + req, err := client.GetJobPreparer(resourceGroupName, resourceName, jobID) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetJob", nil, "Failure preparing request") + return + } + + resp, err := client.GetJobSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetJob", resp, "Failure sending request") + return + } + + result, err = client.GetJobResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetJob", resp, "Failure responding to request") + } + + return +} + +// GetJobPreparer prepares the GetJob request. +func (client ResourceClient) GetJobPreparer(resourceGroupName string, resourceName string, jobID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "jobId": autorest.Encode("path", jobID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/jobs/{jobId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetJobSender sends the GetJob request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) GetJobSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetJobResponder handles the response to the GetJob request. The method always +// closes the http.Response Body. +func (client ResourceClient) GetJobResponder(resp *http.Response) (result JobResponse, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetKeysForKeyName get a shared access policy by name from an IoT hub. For +// more information, see: +// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. keyName is the name of the +// shared access policy. +func (client ResourceClient) GetKeysForKeyName(resourceGroupName string, resourceName string, keyName string) (result SharedAccessSignatureAuthorizationRule, err error) { + req, err := client.GetKeysForKeyNamePreparer(resourceGroupName, resourceName, keyName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetKeysForKeyName", nil, "Failure preparing request") + return + } + + resp, err := client.GetKeysForKeyNameSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetKeysForKeyName", resp, "Failure sending request") + return + } + + result, err = client.GetKeysForKeyNameResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetKeysForKeyName", resp, "Failure responding to request") + } + + return +} + +// GetKeysForKeyNamePreparer prepares the GetKeysForKeyName request. +func (client ResourceClient) GetKeysForKeyNamePreparer(resourceGroupName string, resourceName string, keyName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "keyName": autorest.Encode("path", keyName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/IotHubKeys/{keyName}/listkeys", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetKeysForKeyNameSender sends the GetKeysForKeyName request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) GetKeysForKeyNameSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetKeysForKeyNameResponder handles the response to the GetKeysForKeyName request. The method always +// closes the http.Response Body. +func (client ResourceClient) GetKeysForKeyNameResponder(resp *http.Response) (result SharedAccessSignatureAuthorizationRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetQuotaMetrics get the quota metrics for an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. +func (client ResourceClient) GetQuotaMetrics(resourceGroupName string, resourceName string) (result QuotaMetricInfoListResult, err error) { + req, err := client.GetQuotaMetricsPreparer(resourceGroupName, resourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetQuotaMetrics", nil, "Failure preparing request") + return + } + + resp, err := client.GetQuotaMetricsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetQuotaMetrics", resp, "Failure sending request") + return + } + + result, err = client.GetQuotaMetricsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetQuotaMetrics", resp, "Failure responding to request") + } + + return +} + +// GetQuotaMetricsPreparer prepares the GetQuotaMetrics request. +func (client ResourceClient) GetQuotaMetricsPreparer(resourceGroupName string, resourceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/quotaMetrics", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetQuotaMetricsSender sends the GetQuotaMetrics request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) GetQuotaMetricsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetQuotaMetricsResponder handles the response to the GetQuotaMetrics request. The method always +// closes the http.Response Body. +func (client ResourceClient) GetQuotaMetricsResponder(resp *http.Response) (result QuotaMetricInfoListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetQuotaMetricsNextResults retrieves the next set of results, if any. +func (client ResourceClient) GetQuotaMetricsNextResults(lastResults QuotaMetricInfoListResult) (result QuotaMetricInfoListResult, err error) { + req, err := lastResults.QuotaMetricInfoListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetQuotaMetrics", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.GetQuotaMetricsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetQuotaMetrics", resp, "Failure sending next results request") + } + + result, err = client.GetQuotaMetricsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetQuotaMetrics", resp, "Failure responding to next results request") + } + + return +} + +// GetStats get the statistics from an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. +func (client ResourceClient) GetStats(resourceGroupName string, resourceName string) (result RegistryStatistics, err error) { + req, err := client.GetStatsPreparer(resourceGroupName, resourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetStats", nil, "Failure preparing request") + return + } + + resp, err := client.GetStatsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetStats", resp, "Failure sending request") + return + } + + result, err = client.GetStatsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetStats", resp, "Failure responding to request") + } + + return +} + +// GetStatsPreparer prepares the GetStats request. +func (client ResourceClient) GetStatsPreparer(resourceGroupName string, resourceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/IotHubStats", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetStatsSender sends the GetStats request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) GetStatsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetStatsResponder handles the response to the GetStats request. The method always +// closes the http.Response Body. +func (client ResourceClient) GetStatsResponder(resp *http.Response) (result RegistryStatistics, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetValidSkus get the list of valid SKUs for an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. +func (client ResourceClient) GetValidSkus(resourceGroupName string, resourceName string) (result SkuDescriptionListResult, err error) { + req, err := client.GetValidSkusPreparer(resourceGroupName, resourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetValidSkus", nil, "Failure preparing request") + return + } + + resp, err := client.GetValidSkusSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetValidSkus", resp, "Failure sending request") + return + } + + result, err = client.GetValidSkusResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetValidSkus", resp, "Failure responding to request") + } + + return +} + +// GetValidSkusPreparer prepares the GetValidSkus request. +func (client ResourceClient) GetValidSkusPreparer(resourceGroupName string, resourceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/skus", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetValidSkusSender sends the GetValidSkus request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) GetValidSkusSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetValidSkusResponder handles the response to the GetValidSkus request. The method always +// closes the http.Response Body. +func (client ResourceClient) GetValidSkusResponder(resp *http.Response) (result SkuDescriptionListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetValidSkusNextResults retrieves the next set of results, if any. +func (client ResourceClient) GetValidSkusNextResults(lastResults SkuDescriptionListResult) (result SkuDescriptionListResult, err error) { + req, err := lastResults.SkuDescriptionListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetValidSkus", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.GetValidSkusSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetValidSkus", resp, "Failure sending next results request") + } + + result, err = client.GetValidSkusResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetValidSkus", resp, "Failure responding to next results request") + } + + return +} + +// ImportDevices import, update, or delete device identities in the IoT hub +// identity registry from a blob. For more information, see: +// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. importDevicesParameters is the +// parameters that specify the import devices operation. +func (client ResourceClient) ImportDevices(resourceGroupName string, resourceName string, importDevicesParameters ImportDevicesRequest) (result JobResponse, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: importDevicesParameters, + Constraints: []validation.Constraint{{Target: "importDevicesParameters.InputBlobContainerURI", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "importDevicesParameters.OutputBlobContainerURI", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "iothub.ResourceClient", "ImportDevices") + } + + req, err := client.ImportDevicesPreparer(resourceGroupName, resourceName, importDevicesParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ImportDevices", nil, "Failure preparing request") + return + } + + resp, err := client.ImportDevicesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ImportDevices", resp, "Failure sending request") + return + } + + result, err = client.ImportDevicesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ImportDevices", resp, "Failure responding to request") + } + + return +} + +// ImportDevicesPreparer prepares the ImportDevices request. +func (client ResourceClient) ImportDevicesPreparer(resourceGroupName string, resourceName string, importDevicesParameters ImportDevicesRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/importDevices", pathParameters), + autorest.WithJSON(importDevicesParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ImportDevicesSender sends the ImportDevices request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) ImportDevicesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ImportDevicesResponder handles the response to the ImportDevices request. The method always +// closes the http.Response Body. +func (client ResourceClient) ImportDevicesResponder(resp *http.Response) (result JobResponse, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroup get all the IoT hubs in a resource group. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hubs. +func (client ResourceClient) ListByResourceGroup(resourceGroupName string) (result DescriptionListResult, err error) { + req, err := client.ListByResourceGroupPreparer(resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client ResourceClient) ListByResourceGroupPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client ResourceClient) ListByResourceGroupResponder(resp *http.Response) (result DescriptionListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroupNextResults retrieves the next set of results, if any. +func (client ResourceClient) ListByResourceGroupNextResults(lastResults DescriptionListResult) (result DescriptionListResult, err error) { + req, err := lastResults.DescriptionListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListByResourceGroup", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListByResourceGroup", resp, "Failure sending next results request") + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListByResourceGroup", resp, "Failure responding to next results request") + } + + return +} + +// ListBySubscription get all the IoT hubs in a subscription. +func (client ResourceClient) ListBySubscription() (result DescriptionListResult, err error) { + req, err := client.ListBySubscriptionPreparer() + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListBySubscription", resp, "Failure sending request") + return + } + + result, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListBySubscription", resp, "Failure responding to request") + } + + return +} + +// ListBySubscriptionPreparer prepares the ListBySubscription request. +func (client ResourceClient) ListBySubscriptionPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Devices/IotHubs", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListBySubscriptionSender sends the ListBySubscription request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always +// closes the http.Response Body. +func (client ResourceClient) ListBySubscriptionResponder(resp *http.Response) (result DescriptionListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListBySubscriptionNextResults retrieves the next set of results, if any. +func (client ResourceClient) ListBySubscriptionNextResults(lastResults DescriptionListResult) (result DescriptionListResult, err error) { + req, err := lastResults.DescriptionListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListBySubscription", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListBySubscription", resp, "Failure sending next results request") + } + + result, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListBySubscription", resp, "Failure responding to next results request") + } + + return +} + +// ListEventHubConsumerGroups get a list of the consumer groups in the Event +// Hub-compatible device-to-cloud endpoint in an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the +// name of the Event Hub-compatible endpoint. +func (client ResourceClient) ListEventHubConsumerGroups(resourceGroupName string, resourceName string, eventHubEndpointName string) (result EventHubConsumerGroupsListResult, err error) { + req, err := client.ListEventHubConsumerGroupsPreparer(resourceGroupName, resourceName, eventHubEndpointName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListEventHubConsumerGroups", nil, "Failure preparing request") + return + } + + resp, err := client.ListEventHubConsumerGroupsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListEventHubConsumerGroups", resp, "Failure sending request") + return + } + + result, err = client.ListEventHubConsumerGroupsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListEventHubConsumerGroups", resp, "Failure responding to request") + } + + return +} + +// ListEventHubConsumerGroupsPreparer prepares the ListEventHubConsumerGroups request. +func (client ResourceClient) ListEventHubConsumerGroupsPreparer(resourceGroupName string, resourceName string, eventHubEndpointName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventHubEndpointName": autorest.Encode("path", eventHubEndpointName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListEventHubConsumerGroupsSender sends the ListEventHubConsumerGroups request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) ListEventHubConsumerGroupsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListEventHubConsumerGroupsResponder handles the response to the ListEventHubConsumerGroups request. The method always +// closes the http.Response Body. +func (client ResourceClient) ListEventHubConsumerGroupsResponder(resp *http.Response) (result EventHubConsumerGroupsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListEventHubConsumerGroupsNextResults retrieves the next set of results, if any. +func (client ResourceClient) ListEventHubConsumerGroupsNextResults(lastResults EventHubConsumerGroupsListResult) (result EventHubConsumerGroupsListResult, err error) { + req, err := lastResults.EventHubConsumerGroupsListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListEventHubConsumerGroups", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListEventHubConsumerGroupsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListEventHubConsumerGroups", resp, "Failure sending next results request") + } + + result, err = client.ListEventHubConsumerGroupsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListEventHubConsumerGroups", resp, "Failure responding to next results request") + } + + return +} + +// ListJobs get a list of all the jobs in an IoT hub. For more information, +// see: +// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. +func (client ResourceClient) ListJobs(resourceGroupName string, resourceName string) (result JobResponseListResult, err error) { + req, err := client.ListJobsPreparer(resourceGroupName, resourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListJobs", nil, "Failure preparing request") + return + } + + resp, err := client.ListJobsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListJobs", resp, "Failure sending request") + return + } + + result, err = client.ListJobsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListJobs", resp, "Failure responding to request") + } + + return +} + +// ListJobsPreparer prepares the ListJobs request. +func (client ResourceClient) ListJobsPreparer(resourceGroupName string, resourceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/jobs", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListJobsSender sends the ListJobs request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) ListJobsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListJobsResponder handles the response to the ListJobs request. The method always +// closes the http.Response Body. +func (client ResourceClient) ListJobsResponder(resp *http.Response) (result JobResponseListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListJobsNextResults retrieves the next set of results, if any. +func (client ResourceClient) ListJobsNextResults(lastResults JobResponseListResult) (result JobResponseListResult, err error) { + req, err := lastResults.JobResponseListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListJobs", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListJobsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListJobs", resp, "Failure sending next results request") + } + + result, err = client.ListJobsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListJobs", resp, "Failure responding to next results request") + } + + return +} + +// ListKeys get the security metadata for an IoT hub. For more information, +// see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. +func (client ResourceClient) ListKeys(resourceGroupName string, resourceName string) (result SharedAccessSignatureAuthorizationRuleListResult, err error) { + req, err := client.ListKeysPreparer(resourceGroupName, resourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListKeys", nil, "Failure preparing request") + return + } + + resp, err := client.ListKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListKeys", resp, "Failure sending request") + return + } + + result, err = client.ListKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListKeys", resp, "Failure responding to request") + } + + return +} + +// ListKeysPreparer prepares the ListKeys request. +func (client ResourceClient) ListKeysPreparer(resourceGroupName string, resourceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/listkeys", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListKeysSender sends the ListKeys request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) ListKeysSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListKeysResponder handles the response to the ListKeys request. The method always +// closes the http.Response Body. +func (client ResourceClient) ListKeysResponder(resp *http.Response) (result SharedAccessSignatureAuthorizationRuleListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListKeysNextResults retrieves the next set of results, if any. +func (client ResourceClient) ListKeysNextResults(lastResults SharedAccessSignatureAuthorizationRuleListResult) (result SharedAccessSignatureAuthorizationRuleListResult, err error) { + req, err := lastResults.SharedAccessSignatureAuthorizationRuleListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListKeys", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListKeys", resp, "Failure sending next results request") + } + + result, err = client.ListKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListKeys", resp, "Failure responding to next results request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go new file mode 100755 index 000000000000..d33d9dd5ad26 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go @@ -0,0 +1,28 @@ +package iothub + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0 +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +// UserAgent returns the UserAgent string to use when sending http.Requests. +func UserAgent() string { + return "Azure-SDK-For-Go/v10.3.0-beta arm-iothub/2017-07-01" +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return "v10.3.0-beta" +} diff --git a/vendor/vendor.json b/vendor/vendor.json index 50da0c0e3ea6..3f4425e908a2 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -106,6 +106,12 @@ "version": "=v10.3.0-beta", "versionExact": "v10.3.0-beta" }, + { + "checksumSHA1": "wSLOrUgDpf9pmtZKl2KO3OavrZU=", + "path": "github.com/Azure/azure-sdk-for-go/arm/iothub", + "revision": "dedad7d55bef3a5fd61d3b682bcba0a93cf315e8", + "revisionTime": "2017-08-24T19:57:27Z" + }, { "checksumSHA1": "FloEh78hgEozkpt0y4SPWK23/wI=", "path": "github.com/Azure/azure-sdk-for-go/arm/keyvault", From ee1bf6013988dfcc5c0dab16bd708af3da608429 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 00:37:12 +0530 Subject: [PATCH 02/69] added the config and cleaned up the schema iothub resource schema --- azurerm/config.go | 9 +++ .../resource_arm_iothub_resource_provider.go | 75 +++++++++++++++++++ 2 files changed, 84 insertions(+) diff --git a/azurerm/config.go b/azurerm/config.go index 6458b7c3cdee..01a839958281 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -7,6 +7,8 @@ import ( "net/http" "net/http/httputil" + "github.com/Azure/azure-sdk-for-go/arm/iothub" + "github.com/Azure/azure-sdk-for-go/arm/appinsights" "github.com/Azure/azure-sdk-for-go/arm/automation" "github.com/Azure/azure-sdk-for-go/arm/cdn" @@ -151,6 +153,7 @@ type ArmClient struct { sqlElasticPoolsClient sql.ElasticPoolsClient sqlFirewallRulesClient sql.FirewallRulesClient sqlServersClient sql.ServersClient + iothubResourceClient iothub.ResourceClient } func withRequestLogging() autorest.SendDecorator { @@ -654,6 +657,12 @@ func (c *Config) getArmClient() (*ArmClient, error) { aschc.Sender = sender client.automationScheduleClient = aschc + ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) + setUserAgent(&ihrc.Client) + ihrc.Authorizer = auth + ihrc.Sender = sender + client.iothubResourceClient = ihrc + client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) client.registerDatabases(endpoint, c.SubscriptionID, auth, sender) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index e69de29bb2d1..fb7963da889d 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -0,0 +1,75 @@ +package azurerm + +import ( + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmIothub() *schema.Resource { + return &schema.Resource{ + Create: resourceArmIothubCreate, + Read: resourceArmIothubRead, + Update: resourceArmIothubUpdate, + Delete: resourceArmIothubDelete, + + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + }, + + "name": { + Type: schema.TypeString, + }, + + "type": { + Type: schema.TypeString, + }, + + "location": { + Type: schema.TypeString, + }, + + "subscriptionid": { + Type: schema.TypeString, + }, + + "resourcegroup": { + Type: schema.TypeString, + }, + + "etag": { + Type: schema.TypeString, + }, + + "skuinfo": { + Type: schema.TypeList, + MaxItems: 1, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + }, + + "tier": { + Type: schema.TypeString, + }, + + "capacity": { + Type: schema.TypeInt, + }, + }, + }, + }, + }, + } + +} +func resourceArmIothubCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + iotHubCreateClient := client.iothubResourceClient + resGroup := d.Get("resourceGroupName").(string) + resName := d.Get("resourceName").(string) + + return nil + +} From bc22b50466a9cc417efe2024cb017bcbb869dc28 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 01:38:11 +0530 Subject: [PATCH 03/69] added validation and params in the schemas --- .../resource_arm_iothub_resource_provider.go | 60 ++++++++++++++----- 1 file changed, 45 insertions(+), 15 deletions(-) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index fb7963da889d..9a63ef3b29aa 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -1,7 +1,9 @@ package azurerm import ( + "github.com/Azure/azure-sdk-for-go/arm/iothub" "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" ) func resourceArmIothub() *schema.Resource { @@ -13,31 +15,38 @@ func resourceArmIothub() *schema.Resource { Schema: map[string]*schema.Schema{ "id": { - Type: schema.TypeString, + Type: schema.TypeString, + Computed: true, }, - "name": { - Type: schema.TypeString, + Type: schema.TypeString, + Required: true, }, "type": { - Type: schema.TypeString, + Type: schema.TypeString, + Computed: true, }, "location": { - Type: schema.TypeString, + Type: schema.TypeString, + Required: true, }, - "subscriptionid": { - Type: schema.TypeString, + "subscription_id": { + Type: schema.TypeString, + Required: true, }, - "resourcegroup": { - Type: schema.TypeString, + "resource_group": { + Type: schema.TypeString, + Required: true, }, "etag": { - Type: schema.TypeString, + Type: schema.TypeString, + Optional: true, + Computed: true, }, "skuinfo": { @@ -48,14 +57,25 @@ func resourceArmIothub() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, + ValidateFunc: validation.StringInSlice([]string{ + string(iothub.F1), + string(iothub.S1), + string(iothub.S2), + string(iothub.S3), + }, true), }, "tier": { Type: schema.TypeString, + ValidateFunc: validation.StringInSlice([]string{ + string(iothub.Free), + string(iothub.Standard), + }, true), }, "capacity": { - Type: schema.TypeInt, + Type: schema.TypeInt, + ValidateFunc: validation.IntAtLeast(1), }, }, }, @@ -65,11 +85,21 @@ func resourceArmIothub() *schema.Resource { } func resourceArmIothubCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - iotHubCreateClient := client.iothubResourceClient - resGroup := d.Get("resourceGroupName").(string) - resName := d.Get("resourceName").(string) return nil } + +func resourceArmIothubRead(d *schema.ResourceData, meta interface{}) error { + + return nil +} + +func resourceArmIothubUpdate(d *schema.ResourceData, meta interface{}) error { + + return nil +} + +func resourceArmIothubDelete(d *schema.ResourceData, meta interface{}) error { + return nil +} From f9bf64d7f3fcf9894b727a813102381781ca2f9d Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 02:10:12 +0530 Subject: [PATCH 04/69] added minimal creation method --- .../resource_arm_iothub_resource_provider.go | 63 +++++++++++++++---- 1 file changed, 51 insertions(+), 12 deletions(-) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 9a63ef3b29aa..53f61a2e4b45 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -28,20 +28,14 @@ func resourceArmIothub() *schema.Resource { Computed: true, }, - "location": { - Type: schema.TypeString, - Required: true, - }, + "location": locationSchema(), "subscription_id": { Type: schema.TypeString, Required: true, }, - "resource_group": { - Type: schema.TypeString, - Required: true, - }, + "resource_group_name": resourceGroupNameSchema(), "etag": { Type: schema.TypeString, @@ -49,14 +43,17 @@ func resourceArmIothub() *schema.Resource { Computed: true, }, - "skuinfo": { + "tags": tagsSchema(), + + "sku": { Type: schema.TypeList, MaxItems: 1, Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, + Type: schema.TypeString, + Required: true, ValidateFunc: validation.StringInSlice([]string{ string(iothub.F1), string(iothub.S1), @@ -66,7 +63,8 @@ func resourceArmIothub() *schema.Resource { }, "tier": { - Type: schema.TypeString, + Type: schema.TypeString, + Required: true, ValidateFunc: validation.StringInSlice([]string{ string(iothub.Free), string(iothub.Standard), @@ -75,6 +73,7 @@ func resourceArmIothub() *schema.Resource { "capacity": { Type: schema.TypeInt, + Required: true, ValidateFunc: validation.IntAtLeast(1), }, }, @@ -86,7 +85,47 @@ func resourceArmIothub() *schema.Resource { } func resourceArmIothubCreate(d *schema.ResourceData, meta interface{}) error { - return nil + armClient := meta.(*ArmClient) + iothubClient := armClient.iothubResourceClient + + rg := d.Get("resource_group").(string) + name := d.Get("name").(string) + location := d.Get("location").(string) + subscriptionId := d.Get("subscription_id").(string) + skuInfo := expandAzureRmIotHubSku(d) + + desc := iothub.Description{ + Name: &name, + Location: &location, + Subscriptionid: &subscriptionId, + Sku: &skuInfo, + } + + cancel := make(chan struct{}) + + RespChan, errChan := iothubClient.CreateOrUpdate(rg, name, desc, cancel) + resp := <-RespChan + err := <-errChan + + if err != nil { + return err + } + + d.SetId(*resp.ID) + return resourceArmIothubRead(d, meta) + +} + +func expandAzureRmIotHubSku(d *schema.ResourceData) iothub.SkuInfo { + skuList := d.Get("sku").([]interface{}) + skuMap := skuList[0].(map[string]interface{}) + cap := int64(skuMap["capacity"].(int)) + + return iothub.SkuInfo{ + Name: iothub.Sku(skuMap["name"].(string)), + Tier: iothub.SkuTier(skuMap["tier"].(string)), + Capacity: &cap, + } } From 531319c736be092e2688ac7b24c88d9f2c5a56c1 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 02:19:52 +0530 Subject: [PATCH 05/69] added resource to the provider list --- azurerm/provider.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/azurerm/provider.go b/azurerm/provider.go index ea7b5a255f2a..3dc6945e8099 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -158,6 +158,7 @@ func Provider() terraform.ResourceProvider { "azurerm_virtual_machine_scale_set": resourceArmVirtualMachineScaleSet(), "azurerm_virtual_network": resourceArmVirtualNetwork(), "azurerm_virtual_network_peering": resourceArmVirtualNetworkPeering(), + "azurerm_iothub": resourceArmIothub(), }, } @@ -413,6 +414,7 @@ func determineAzureResourceProvidersToRegister(providerList []resources.Provider "Microsoft.ServiceBus": {}, "Microsoft.Sql": {}, "Microsoft.Storage": {}, + "Microsoft.Devices": {}, } // filter out any providers already registered From 12bd9e03502c89538674e23567b8c361ae796bcf Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 02:51:54 +0530 Subject: [PATCH 06/69] cleaned up the schema a bit and added read --- .../resource_arm_iothub_resource_provider.go | 37 +++++++++++++------ 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 53f61a2e4b45..34320b67bad7 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -14,15 +14,13 @@ func resourceArmIothub() *schema.Resource { Delete: resourceArmIothubDelete, Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, - }, "name": { Type: schema.TypeString, Required: true, + ForceNew: true, }, + // TODO: is this needed "type": { Type: schema.TypeString, Computed: true, @@ -30,11 +28,6 @@ func resourceArmIothub() *schema.Resource { "location": locationSchema(), - "subscription_id": { - Type: schema.TypeString, - Required: true, - }, - "resource_group_name": resourceGroupNameSchema(), "etag": { @@ -91,16 +84,22 @@ func resourceArmIothubCreate(d *schema.ResourceData, meta interface{}) error { rg := d.Get("resource_group").(string) name := d.Get("name").(string) location := d.Get("location").(string) - subscriptionId := d.Get("subscription_id").(string) + subscriptionID := armClient.subscriptionId skuInfo := expandAzureRmIotHubSku(d) desc := iothub.Description{ + Resourcegroup: &rg, Name: &name, Location: &location, - Subscriptionid: &subscriptionId, + Subscriptionid: &subscriptionID, Sku: &skuInfo, } + if etagI, ok := d.GetOk("etag"); ok { + etag := etagI.(string) + desc.Etag = &etag + } + cancel := make(chan struct{}) RespChan, errChan := iothubClient.CreateOrUpdate(rg, name, desc, cancel) @@ -131,6 +130,22 @@ func expandAzureRmIotHubSku(d *schema.ResourceData) iothub.SkuInfo { func resourceArmIothubRead(d *schema.ResourceData, meta interface{}) error { + id, err := parseAzureResourceID(d.Id()) + + if err != nil { + return err + } + + armClient := meta.(*ArmClient) + iothubClient := armClient.iothubResourceClient + desc, err := iothubClient.Get(id.ResourceGroup, id.Path["IotHubs"]) + if err != nil { + return err + } + + d.Set("etag", *desc.Etag) + d.Set("type", *desc.Type) + return nil } From 293ab2cc5086e6036ac2d8e8f38319033b7a958d Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 12:04:07 +0530 Subject: [PATCH 07/69] working read and create method on iothub resource --- azurerm/config.go | 2 +- azurerm/resource_arm_iothub_resource_provider.go | 12 ++++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/azurerm/config.go b/azurerm/config.go index 01a839958281..0fd6fbb14b4b 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -660,7 +660,7 @@ func (c *Config) getArmClient() (*ArmClient, error) { ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) setUserAgent(&ihrc.Client) ihrc.Authorizer = auth - ihrc.Sender = sender + ihrc.Sender = autorest.CreateSender(withRequestLogging()) client.iothubResourceClient = ihrc client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 34320b67bad7..1525028cf6d0 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -81,7 +81,7 @@ func resourceArmIothubCreate(d *schema.ResourceData, meta interface{}) error { armClient := meta.(*ArmClient) iothubClient := armClient.iothubResourceClient - rg := d.Get("resource_group").(string) + rg := d.Get("resource_group_name").(string) name := d.Get("name").(string) location := d.Get("location").(string) subscriptionID := armClient.subscriptionId @@ -102,15 +102,19 @@ func resourceArmIothubCreate(d *schema.ResourceData, meta interface{}) error { cancel := make(chan struct{}) - RespChan, errChan := iothubClient.CreateOrUpdate(rg, name, desc, cancel) - resp := <-RespChan + _, errChan := iothubClient.CreateOrUpdate(rg, name, desc, cancel) err := <-errChan if err != nil { return err } - d.SetId(*resp.ID) + desc, err = iothubClient.Get(rg, name) + if err != nil { + return err + } + + d.SetId(*desc.ID) return resourceArmIothubRead(d, meta) } From bbd14818de74d49e8aa5bb93995329c4965d6d3e Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 14:33:38 +0530 Subject: [PATCH 08/69] added lifecycle methods for iothub --- .../resource_arm_iothub_resource_provider.go | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 1525028cf6d0..75db0b99b351 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -8,12 +8,13 @@ import ( func resourceArmIothub() *schema.Resource { return &schema.Resource{ - Create: resourceArmIothubCreate, + Create: resourceArmIothubCreateAndUpdate, Read: resourceArmIothubRead, - Update: resourceArmIothubUpdate, + Update: resourceArmIothubCreateAndUpdate, Delete: resourceArmIothubDelete, Schema: map[string]*schema.Schema{ + // TODO: use nameAvailabilityInfo for validation "name": { Type: schema.TypeString, Required: true, @@ -76,7 +77,7 @@ func resourceArmIothub() *schema.Resource { } } -func resourceArmIothubCreate(d *schema.ResourceData, meta interface{}) error { +func resourceArmIothubCreateAndUpdate(d *schema.ResourceData, meta interface{}) error { armClient := meta.(*ArmClient) iothubClient := armClient.iothubResourceClient @@ -153,11 +154,18 @@ func resourceArmIothubRead(d *schema.ResourceData, meta interface{}) error { return nil } -func resourceArmIothubUpdate(d *schema.ResourceData, meta interface{}) error { +func resourceArmIothubDelete(d *schema.ResourceData, meta interface{}) error { - return nil -} + id, err := parseAzureResourceID(d.Id()) -func resourceArmIothubDelete(d *schema.ResourceData, meta interface{}) error { - return nil + if err != nil { + return err + } + + armClient := meta.(*ArmClient) + iothubClient := armClient.iothubResourceClient + + _, errChan := iothubClient.Delete(id.ResourceGroup, id.Path["IotHubs"], make(chan struct{})) + err = <-errChan + return err } From 7fda639ca66847945df30563e06b2843058ba159 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 15:22:39 +0530 Subject: [PATCH 09/69] added tags --- azurerm/resource_arm_iothub_resource_provider.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 75db0b99b351..3a9ec2258f68 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -85,6 +85,7 @@ func resourceArmIothubCreateAndUpdate(d *schema.ResourceData, meta interface{}) rg := d.Get("resource_group_name").(string) name := d.Get("name").(string) location := d.Get("location").(string) + subscriptionID := armClient.subscriptionId skuInfo := expandAzureRmIotHubSku(d) @@ -96,6 +97,11 @@ func resourceArmIothubCreateAndUpdate(d *schema.ResourceData, meta interface{}) Sku: &skuInfo, } + if tagsI, ok := d.GetOk("tags"); ok { + tags := tagsI.(map[string]interface{}) + desc.Tags = expandTags(tags) + } + if etagI, ok := d.GetOk("etag"); ok { etag := etagI.(string) desc.Etag = &etag From e58ffdec52de7abef9c2d867133d1201d3b01690 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 16:59:40 +0530 Subject: [PATCH 10/69] basic integration tests added --- .../resource_arm_iothub_resource_provider.go | 1 + ...ource_arm_iothub_resource_provider_test.go | 105 ++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 azurerm/resource_arm_iothub_resource_provider_test.go diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 3a9ec2258f68..9883dd58f090 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -156,6 +156,7 @@ func resourceArmIothubRead(d *schema.ResourceData, meta interface{}) error { d.Set("etag", *desc.Etag) d.Set("type", *desc.Type) + flattenAndSetTags(d, desc.Tags) return nil } diff --git a/azurerm/resource_arm_iothub_resource_provider_test.go b/azurerm/resource_arm_iothub_resource_provider_test.go new file mode 100644 index 000000000000..7ca841d96b31 --- /dev/null +++ b/azurerm/resource_arm_iothub_resource_provider_test.go @@ -0,0 +1,105 @@ +package azurerm + +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +const TestResourceGroup = "girishsandbox" + +func TestAccAzureRMIotHub_basicStandard(t *testing.T) { + name := acctest.RandString(6) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMIothubDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMIotHub_basicStandard(name, TestResourceGroup, testLocation()), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMIothubExists("azurerm_iothub.test"), + ), + }, + }, + }) + +} + +func testCheckAzureRMIothubDestroy(s *terraform.State) error { + + conn := testAccProvider.Meta().(*ArmClient).expressRouteCircuitClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_iothub" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(resourceGroup, name) + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Iothub still exists:\n%#v", resp.ExpressRouteCircuitPropertiesFormat) + } + } + return nil +} +func testCheckAzureRMIothubExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + iothubName := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for IotHub: %s", iothubName) + } + + conn := testAccProvider.Meta().(*ArmClient).iothubResourceClient + + resp, err := conn.Get(resourceGroup, iothubName) + + if err != nil { + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: IotHub %q (resource group: %q) does not exist", iothubName, resourceGroup) + } + + return fmt.Errorf("Bad: Get on iothubResourceClient: %+v", err) + } + + return nil + + } +} + +func testAccAzureRMIotHub_basicStandard(name, rg, location string) string { + return fmt.Sprintf(` + resource "azurerm_iothub" "test" { + name = "%s" + resource_group_name = "%s" + location = "%s" + sku { + name = "S1" + tier = "Standard" + capacity = "1" + } + + tags { + "purpose" = "testing" + } + } + + + `, name, rg, location) +} From b569ba96d2d7c1377ba3437b71fcf3be9133c9c7 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 17:30:19 +0530 Subject: [PATCH 11/69] Added validations for the name and followed naming convention --- azurerm/provider.go | 2 +- .../resource_arm_iothub_resource_provider.go | 38 +++++++++++++------ ...ource_arm_iothub_resource_provider_test.go | 11 +++--- 3 files changed, 33 insertions(+), 18 deletions(-) diff --git a/azurerm/provider.go b/azurerm/provider.go index 3dc6945e8099..fda1c94210d3 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -158,7 +158,7 @@ func Provider() terraform.ResourceProvider { "azurerm_virtual_machine_scale_set": resourceArmVirtualMachineScaleSet(), "azurerm_virtual_network": resourceArmVirtualNetwork(), "azurerm_virtual_network_peering": resourceArmVirtualNetworkPeering(), - "azurerm_iothub": resourceArmIothub(), + "azurerm_iothub": resourceArmIotHub(), }, } diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 9883dd58f090..bacf410b0223 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -1,27 +1,27 @@ package azurerm import ( + "errors" + "github.com/Azure/azure-sdk-for-go/arm/iothub" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" ) -func resourceArmIothub() *schema.Resource { +func resourceArmIotHub() *schema.Resource { return &schema.Resource{ - Create: resourceArmIothubCreateAndUpdate, - Read: resourceArmIothubRead, - Update: resourceArmIothubCreateAndUpdate, - Delete: resourceArmIothubDelete, + Create: resourceArmIotHubCreateAndUpdate, + Read: resourceArmIotHubRead, + Update: resourceArmIotHubCreateAndUpdate, + Delete: resourceArmIotHubDelete, Schema: map[string]*schema.Schema{ - // TODO: use nameAvailabilityInfo for validation "name": { Type: schema.TypeString, Required: true, ForceNew: true, }, - // TODO: is this needed "type": { Type: schema.TypeString, Computed: true, @@ -77,13 +77,27 @@ func resourceArmIothub() *schema.Resource { } } -func resourceArmIothubCreateAndUpdate(d *schema.ResourceData, meta interface{}) error { + +func resourceArmIotHubCreateAndUpdate(d *schema.ResourceData, meta interface{}) error { armClient := meta.(*ArmClient) iothubClient := armClient.iothubResourceClient rg := d.Get("resource_group_name").(string) name := d.Get("name").(string) + + res, err := iothubClient.CheckNameAvailability(iothub.OperationInputs{ + Name: &name, + }) + + if err != nil { + return err + } + + if !*res.NameAvailable { + return errors.New(string(res.Reason)) + } + location := d.Get("location").(string) subscriptionID := armClient.subscriptionId @@ -110,7 +124,7 @@ func resourceArmIothubCreateAndUpdate(d *schema.ResourceData, meta interface{}) cancel := make(chan struct{}) _, errChan := iothubClient.CreateOrUpdate(rg, name, desc, cancel) - err := <-errChan + err = <-errChan if err != nil { return err @@ -122,7 +136,7 @@ func resourceArmIothubCreateAndUpdate(d *schema.ResourceData, meta interface{}) } d.SetId(*desc.ID) - return resourceArmIothubRead(d, meta) + return resourceArmIotHubRead(d, meta) } @@ -139,7 +153,7 @@ func expandAzureRmIotHubSku(d *schema.ResourceData) iothub.SkuInfo { } -func resourceArmIothubRead(d *schema.ResourceData, meta interface{}) error { +func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { id, err := parseAzureResourceID(d.Id()) @@ -161,7 +175,7 @@ func resourceArmIothubRead(d *schema.ResourceData, meta interface{}) error { return nil } -func resourceArmIothubDelete(d *schema.ResourceData, meta interface{}) error { +func resourceArmIotHubDelete(d *schema.ResourceData, meta interface{}) error { id, err := parseAzureResourceID(d.Id()) diff --git a/azurerm/resource_arm_iothub_resource_provider_test.go b/azurerm/resource_arm_iothub_resource_provider_test.go index 7ca841d96b31..67eaefe7e8b0 100644 --- a/azurerm/resource_arm_iothub_resource_provider_test.go +++ b/azurerm/resource_arm_iothub_resource_provider_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform/terraform" ) +// change this to use ephemeral dynamic resource groups const TestResourceGroup = "girishsandbox" func TestAccAzureRMIotHub_basicStandard(t *testing.T) { @@ -17,12 +18,12 @@ func TestAccAzureRMIotHub_basicStandard(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, - CheckDestroy: testCheckAzureRMIothubDestroy, + CheckDestroy: testCheckAzureRMIotHubDestroy, Steps: []resource.TestStep{ { Config: testAccAzureRMIotHub_basicStandard(name, TestResourceGroup, testLocation()), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMIothubExists("azurerm_iothub.test"), + testCheckAzureRMIotHubExists("azurerm_iothub.test"), ), }, }, @@ -30,7 +31,7 @@ func TestAccAzureRMIotHub_basicStandard(t *testing.T) { } -func testCheckAzureRMIothubDestroy(s *terraform.State) error { +func testCheckAzureRMIotHubDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*ArmClient).expressRouteCircuitClient @@ -49,12 +50,12 @@ func testCheckAzureRMIothubDestroy(s *terraform.State) error { } if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Iothub still exists:\n%#v", resp.ExpressRouteCircuitPropertiesFormat) + return fmt.Errorf("IotHub still exists:\n%#v", resp.ExpressRouteCircuitPropertiesFormat) } } return nil } -func testCheckAzureRMIothubExists(name string) resource.TestCheckFunc { +func testCheckAzureRMIotHubExists(name string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] if !ok { From 95b677aacf052c004fb87ce7905e2d47a637a941 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Mon, 9 Oct 2017 21:55:29 +0530 Subject: [PATCH 12/69] updated the iothub vendor dependency --- .../azure-sdk-for-go/arm/iothub/client.go | 10 +- .../azure-sdk-for-go/arm/iothub/models.go | 266 ++++++--- .../azure-sdk-for-go/arm/iothub/operations.go | 165 ++++++ .../azure-sdk-for-go/arm/iothub/resource.go | 532 ++++++++++++++---- .../azure-sdk-for-go/arm/iothub/version.go | 6 +- vendor/vendor.json | 6 +- 6 files changed, 771 insertions(+), 214 deletions(-) create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/operations.go diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go index b54c132eeeee..f2461d01d9f2 100755 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go @@ -1,7 +1,6 @@ -// Package iothub implements the Azure ARM Iothub service API version -// 2016-02-03. +// Package iothub implements the Azure ARM Iothub service API version 2017-07-01. // -// Use this API to manage the IoT hubs in your subscription. +// Use this API to manage the IoT hubs in your Azure subscription. package iothub // Copyright (c) Microsoft and contributors. All rights reserved. @@ -18,9 +17,8 @@ package iothub // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/Azure/go-autorest/autorest" diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go index 6fa4abb25319..0fcfdf7fecc1 100755 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go @@ -14,9 +14,8 @@ package iothub // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/Azure/go-autorest/autorest" @@ -33,43 +32,36 @@ const ( DeviceConnect AccessRights = "DeviceConnect" // RegistryRead specifies the registry read state for access rights. RegistryRead AccessRights = "RegistryRead" - // RegistryReadDeviceConnect specifies the registry read device connect - // state for access rights. + // RegistryReadDeviceConnect specifies the registry read device connect state for access rights. RegistryReadDeviceConnect AccessRights = "RegistryRead, DeviceConnect" - // RegistryReadRegistryWrite specifies the registry read registry write - // state for access rights. + // RegistryReadRegistryWrite specifies the registry read registry write state for access rights. RegistryReadRegistryWrite AccessRights = "RegistryRead, RegistryWrite" - // RegistryReadRegistryWriteDeviceConnect specifies the registry read - // registry write device connect state for access rights. + // RegistryReadRegistryWriteDeviceConnect specifies the registry read registry write device connect state for access + // rights. RegistryReadRegistryWriteDeviceConnect AccessRights = "RegistryRead, RegistryWrite, DeviceConnect" - // RegistryReadRegistryWriteServiceConnect specifies the registry read - // registry write service connect state for access rights. + // RegistryReadRegistryWriteServiceConnect specifies the registry read registry write service connect state for access + // rights. RegistryReadRegistryWriteServiceConnect AccessRights = "RegistryRead, RegistryWrite, ServiceConnect" - // RegistryReadRegistryWriteServiceConnectDeviceConnect specifies the - // registry read registry write service connect device connect state for - // access rights. + // RegistryReadRegistryWriteServiceConnectDeviceConnect specifies the registry read registry write service connect + // device connect state for access rights. RegistryReadRegistryWriteServiceConnectDeviceConnect AccessRights = "RegistryRead, RegistryWrite, ServiceConnect, DeviceConnect" - // RegistryReadServiceConnect specifies the registry read service connect - // state for access rights. + // RegistryReadServiceConnect specifies the registry read service connect state for access rights. RegistryReadServiceConnect AccessRights = "RegistryRead, ServiceConnect" - // RegistryReadServiceConnectDeviceConnect specifies the registry read - // service connect device connect state for access rights. + // RegistryReadServiceConnectDeviceConnect specifies the registry read service connect device connect state for access + // rights. RegistryReadServiceConnectDeviceConnect AccessRights = "RegistryRead, ServiceConnect, DeviceConnect" // RegistryWrite specifies the registry write state for access rights. RegistryWrite AccessRights = "RegistryWrite" - // RegistryWriteDeviceConnect specifies the registry write device connect - // state for access rights. + // RegistryWriteDeviceConnect specifies the registry write device connect state for access rights. RegistryWriteDeviceConnect AccessRights = "RegistryWrite, DeviceConnect" - // RegistryWriteServiceConnect specifies the registry write service connect - // state for access rights. + // RegistryWriteServiceConnect specifies the registry write service connect state for access rights. RegistryWriteServiceConnect AccessRights = "RegistryWrite, ServiceConnect" - // RegistryWriteServiceConnectDeviceConnect specifies the registry write - // service connect device connect state for access rights. + // RegistryWriteServiceConnectDeviceConnect specifies the registry write service connect device connect state for + // access rights. RegistryWriteServiceConnectDeviceConnect AccessRights = "RegistryWrite, ServiceConnect, DeviceConnect" // ServiceConnect specifies the service connect state for access rights. ServiceConnect AccessRights = "ServiceConnect" - // ServiceConnectDeviceConnect specifies the service connect device connect - // state for access rights. + // ServiceConnectDeviceConnect specifies the service connect device connect state for access rights. ServiceConnectDeviceConnect AccessRights = "ServiceConnect, DeviceConnect" ) @@ -119,67 +111,69 @@ const ( JobTypeBackup JobType = "backup" // JobTypeExport specifies the job type export state for job type. JobTypeExport JobType = "export" - // JobTypeFactoryResetDevice specifies the job type factory reset device - // state for job type. + // JobTypeFactoryResetDevice specifies the job type factory reset device state for job type. JobTypeFactoryResetDevice JobType = "factoryResetDevice" - // JobTypeFirmwareUpdate specifies the job type firmware update state for - // job type. + // JobTypeFirmwareUpdate specifies the job type firmware update state for job type. JobTypeFirmwareUpdate JobType = "firmwareUpdate" // JobTypeImport specifies the job type import state for job type. JobTypeImport JobType = "import" - // JobTypeReadDeviceProperties specifies the job type read device - // properties state for job type. + // JobTypeReadDeviceProperties specifies the job type read device properties state for job type. JobTypeReadDeviceProperties JobType = "readDeviceProperties" - // JobTypeRebootDevice specifies the job type reboot device state for job - // type. + // JobTypeRebootDevice specifies the job type reboot device state for job type. JobTypeRebootDevice JobType = "rebootDevice" // JobTypeUnknown specifies the job type unknown state for job type. JobTypeUnknown JobType = "unknown" - // JobTypeUpdateDeviceConfiguration specifies the job type update device - // configuration state for job type. + // JobTypeUpdateDeviceConfiguration specifies the job type update device configuration state for job type. JobTypeUpdateDeviceConfiguration JobType = "updateDeviceConfiguration" - // JobTypeWriteDeviceProperties specifies the job type write device - // properties state for job type. + // JobTypeWriteDeviceProperties specifies the job type write device properties state for job type. JobTypeWriteDeviceProperties JobType = "writeDeviceProperties" ) -// NameUnavailabilityReason enumerates the values for name unavailability -// reason. +// NameUnavailabilityReason enumerates the values for name unavailability reason. type NameUnavailabilityReason string const ( - // AlreadyExists specifies the already exists state for name unavailability - // reason. + // AlreadyExists specifies the already exists state for name unavailability reason. AlreadyExists NameUnavailabilityReason = "AlreadyExists" // Invalid specifies the invalid state for name unavailability reason. Invalid NameUnavailabilityReason = "Invalid" ) -// OperationMonitoringLevel enumerates the values for operation monitoring -// level. +// OperationMonitoringLevel enumerates the values for operation monitoring level. type OperationMonitoringLevel string const ( - // OperationMonitoringLevelError specifies the operation monitoring level - // error state for operation monitoring level. + // OperationMonitoringLevelError specifies the operation monitoring level error state for operation monitoring level. OperationMonitoringLevelError OperationMonitoringLevel = "Error" - // OperationMonitoringLevelErrorInformation specifies the operation - // monitoring level error information state for operation monitoring level. + // OperationMonitoringLevelErrorInformation specifies the operation monitoring level error information state for + // operation monitoring level. OperationMonitoringLevelErrorInformation OperationMonitoringLevel = "Error, Information" - // OperationMonitoringLevelInformation specifies the operation monitoring - // level information state for operation monitoring level. + // OperationMonitoringLevelInformation specifies the operation monitoring level information state for operation + // monitoring level. OperationMonitoringLevelInformation OperationMonitoringLevel = "Information" - // OperationMonitoringLevelNone specifies the operation monitoring level - // none state for operation monitoring level. + // OperationMonitoringLevelNone specifies the operation monitoring level none state for operation monitoring level. OperationMonitoringLevelNone OperationMonitoringLevel = "None" ) +// RoutingSource enumerates the values for routing source. +type RoutingSource string + +const ( + // DeviceJobLifecycleEvents specifies the device job lifecycle events state for routing source. + DeviceJobLifecycleEvents RoutingSource = "DeviceJobLifecycleEvents" + // DeviceLifecycleEvents specifies the device lifecycle events state for routing source. + DeviceLifecycleEvents RoutingSource = "DeviceLifecycleEvents" + // DeviceMessages specifies the device messages state for routing source. + DeviceMessages RoutingSource = "DeviceMessages" + // TwinChangeEvents specifies the twin change events state for routing source. + TwinChangeEvents RoutingSource = "TwinChangeEvents" +) + // ScaleType enumerates the values for scale type. type ScaleType string const ( - // ScaleTypeAutomatic specifies the scale type automatic state for scale - // type. + // ScaleTypeAutomatic specifies the scale type automatic state for scale type. ScaleTypeAutomatic ScaleType = "Automatic" // ScaleTypeManual specifies the scale type manual state for scale type. ScaleTypeManual ScaleType = "Manual" @@ -241,8 +235,7 @@ type Description struct { Sku *SkuInfo `json:"sku,omitempty"` } -// DescriptionListResult is the JSON-serialized array of IotHubDescription -// objects with a next link. +// DescriptionListResult is the JSON-serialized array of IotHubDescription objects with a next link. type DescriptionListResult struct { autorest.Response `json:"-"` Value *[]Description `json:"value,omitempty"` @@ -269,8 +262,7 @@ type ErrorDetails struct { Details *string `json:"Details,omitempty"` } -// EventHubConsumerGroupInfo is the properties of the EventHubConsumerGroupInfo -// object. +// EventHubConsumerGroupInfo is the properties of the EventHubConsumerGroupInfo object. type EventHubConsumerGroupInfo struct { autorest.Response `json:"-"` Tags *map[string]*string `json:"tags,omitempty"` @@ -278,8 +270,8 @@ type EventHubConsumerGroupInfo struct { Name *string `json:"name,omitempty"` } -// EventHubConsumerGroupsListResult is the JSON-serialized array of Event -// Hub-compatible consumer group names with a next link. +// EventHubConsumerGroupsListResult is the JSON-serialized array of Event Hub-compatible consumer group names with a +// next link. type EventHubConsumerGroupsListResult struct { autorest.Response `json:"-"` Value *[]string `json:"value,omitempty"` @@ -298,8 +290,7 @@ func (client EventHubConsumerGroupsListResult) EventHubConsumerGroupsListResultP autorest.WithBaseURL(to.String(client.NextLink))) } -// EventHubProperties is the properties of the provisioned Event Hub-compatible -// endpoint used by the IoT hub. +// EventHubProperties is the properties of the provisioned Event Hub-compatible endpoint used by the IoT hub. type EventHubProperties struct { RetentionTimeInDays *int64 `json:"retentionTimeInDays,omitempty"` PartitionCount *int32 `json:"partitionCount,omitempty"` @@ -308,23 +299,29 @@ type EventHubProperties struct { Endpoint *string `json:"endpoint,omitempty"` } -// ExportDevicesRequest is use to provide parameters when requesting an export -// of all devices in the IoT hub. +// ExportDevicesRequest is use to provide parameters when requesting an export of all devices in the IoT hub. type ExportDevicesRequest struct { ExportBlobContainerURI *string `json:"ExportBlobContainerUri,omitempty"` ExcludeKeys *bool `json:"ExcludeKeys,omitempty"` } -// FeedbackProperties is the properties of the feedback queue for -// cloud-to-device messages. +// FallbackRouteProperties is the properties of the fallback route. IoT Hub uses these properties when it routes +// messages to the fallback endpoint. +type FallbackRouteProperties struct { + Source *string `json:"source,omitempty"` + Condition *string `json:"condition,omitempty"` + EndpointNames *[]string `json:"endpointNames,omitempty"` + IsEnabled *bool `json:"isEnabled,omitempty"` +} + +// FeedbackProperties is the properties of the feedback queue for cloud-to-device messages. type FeedbackProperties struct { LockDurationAsIso8601 *string `json:"lockDurationAsIso8601,omitempty"` TTLAsIso8601 *string `json:"ttlAsIso8601,omitempty"` MaxDeliveryCount *int32 `json:"maxDeliveryCount,omitempty"` } -// ImportDevicesRequest is use to provide parameters when requesting an import -// of all devices in the hub. +// ImportDevicesRequest is use to provide parameters when requesting an import of all devices in the hub. type ImportDevicesRequest struct { InputBlobContainerURI *string `json:"InputBlobContainerUri,omitempty"` OutputBlobContainerURI *string `json:"OutputBlobContainerUri,omitempty"` @@ -350,8 +347,7 @@ type JobResponse struct { ParentJobID *string `json:"parentJobId,omitempty"` } -// JobResponseListResult is the JSON-serialized array of JobResponse objects -// with a next link. +// JobResponseListResult is the JSON-serialized array of JobResponse objects with a next link. type JobResponseListResult struct { autorest.Response `json:"-"` Value *[]JobResponse `json:"value,omitempty"` @@ -370,16 +366,14 @@ func (client JobResponseListResult) JobResponseListResultPreparer() (*http.Reque autorest.WithBaseURL(to.String(client.NextLink))) } -// MessagingEndpointProperties is the properties of the messaging endpoints -// used by this IoT hub. +// MessagingEndpointProperties is the properties of the messaging endpoints used by this IoT hub. type MessagingEndpointProperties struct { LockDurationAsIso8601 *string `json:"lockDurationAsIso8601,omitempty"` TTLAsIso8601 *string `json:"ttlAsIso8601,omitempty"` MaxDeliveryCount *int32 `json:"maxDeliveryCount,omitempty"` } -// NameAvailabilityInfo is the properties indicating whether a given IoT hub -// name is available. +// NameAvailabilityInfo is the properties indicating whether a given IoT hub name is available. type NameAvailabilityInfo struct { autorest.Response `json:"-"` NameAvailable *bool `json:"nameAvailable,omitempty"` @@ -387,15 +381,47 @@ type NameAvailabilityInfo struct { Message *string `json:"message,omitempty"` } +// Operation is ioT Hub REST API operation +type Operation struct { + Name *string `json:"name,omitempty"` + Display *OperationDisplay `json:"display,omitempty"` +} + +// OperationDisplay is the object that represents the operation. +type OperationDisplay struct { + Provider *string `json:"provider,omitempty"` + Resource *string `json:"resource,omitempty"` + Operation *string `json:"operation,omitempty"` +} + // OperationInputs is input values. type OperationInputs struct { Name *string `json:"Name,omitempty"` } -// OperationsMonitoringProperties is the operations monitoring properties for -// the IoT hub. The possible keys to the dictionary are Connections, -// DeviceTelemetry, C2DCommands, DeviceIdentityOperations, -// FileUploadOperations. +// OperationListResult is result of the request to list IoT Hub operations. It contains a list of operations and a URL +// link to get the next set of results. +type OperationListResult struct { + autorest.Response `json:"-"` + Value *[]Operation `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// OperationListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client OperationListResult) OperationListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// OperationsMonitoringProperties is the operations monitoring properties for the IoT hub. The possible keys to the +// dictionary are Connections, DeviceTelemetry, C2DCommands, DeviceIdentityOperations, FileUploadOperations, Routes, +// D2CTwinOperations, C2DTwinOperations, TwinQueries, JobsOperations, DirectMethods. type OperationsMonitoringProperties struct { Events *map[string]*OperationMonitoringLevel `json:"events,omitempty"` } @@ -407,6 +433,7 @@ type Properties struct { ProvisioningState *string `json:"provisioningState,omitempty"` HostName *string `json:"hostName,omitempty"` EventHubEndpoints *map[string]*EventHubProperties `json:"eventHubEndpoints,omitempty"` + Routing *RoutingProperties `json:"routing,omitempty"` StorageEndpoints *map[string]*StorageEndpointProperties `json:"storageEndpoints,omitempty"` MessagingEndpoints *map[string]*MessagingEndpointProperties `json:"messagingEndpoints,omitempty"` EnableFileUploadNotifications *bool `json:"enableFileUploadNotifications,omitempty"` @@ -423,8 +450,7 @@ type QuotaMetricInfo struct { MaxValue *int64 `json:"MaxValue,omitempty"` } -// QuotaMetricInfoListResult is the JSON-serialized array of -// IotHubQuotaMetricInfo objects with a next link. +// QuotaMetricInfoListResult is the JSON-serialized array of IotHubQuotaMetricInfo objects with a next link. type QuotaMetricInfoListResult struct { autorest.Response `json:"-"` Value *[]QuotaMetricInfo `json:"value,omitempty"` @@ -451,7 +477,7 @@ type RegistryStatistics struct { DisabledDeviceCount *int64 `json:"disabledDeviceCount,omitempty"` } -// Resource is +// Resource is the common properties of an Azure resource. type Resource struct { ID *string `json:"id,omitempty"` Name *string `json:"name,omitempty"` @@ -460,14 +486,77 @@ type Resource struct { Tags *map[string]*string `json:"tags,omitempty"` } +// RouteProperties is the properties of a routing rule that your IoT hub uses to route messages to endpoints. +type RouteProperties struct { + Name *string `json:"name,omitempty"` + Source RoutingSource `json:"source,omitempty"` + Condition *string `json:"condition,omitempty"` + EndpointNames *[]string `json:"endpointNames,omitempty"` + IsEnabled *bool `json:"isEnabled,omitempty"` +} + +// RoutingEndpoints is the properties related to the custom endpoints to which your IoT hub routes messages based on +// the routing rules. A maximum of 10 custom endpoints are allowed across all endpoint types for paid hubs and only 1 +// custom endpoint is allowed across all endpoint types for free hubs. +type RoutingEndpoints struct { + ServiceBusQueues *[]RoutingServiceBusQueueEndpointProperties `json:"serviceBusQueues,omitempty"` + ServiceBusTopics *[]RoutingServiceBusTopicEndpointProperties `json:"serviceBusTopics,omitempty"` + EventHubs *[]RoutingEventHubProperties `json:"eventHubs,omitempty"` + StorageContainers *[]RoutingStorageContainerProperties `json:"storageContainers,omitempty"` +} + +// RoutingEventHubProperties is the properties related to an event hub endpoint. +type RoutingEventHubProperties struct { + ConnectionString *string `json:"connectionString,omitempty"` + Name *string `json:"name,omitempty"` + SubscriptionID *string `json:"subscriptionId,omitempty"` + ResourceGroup *string `json:"resourceGroup,omitempty"` +} + +// RoutingProperties is the routing related properties of the IoT hub. See: +// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging +type RoutingProperties struct { + Endpoints *RoutingEndpoints `json:"endpoints,omitempty"` + Routes *[]RouteProperties `json:"routes,omitempty"` + FallbackRoute *FallbackRouteProperties `json:"fallbackRoute,omitempty"` +} + +// RoutingServiceBusQueueEndpointProperties is the properties related to service bus queue endpoint types. +type RoutingServiceBusQueueEndpointProperties struct { + ConnectionString *string `json:"connectionString,omitempty"` + Name *string `json:"name,omitempty"` + SubscriptionID *string `json:"subscriptionId,omitempty"` + ResourceGroup *string `json:"resourceGroup,omitempty"` +} + +// RoutingServiceBusTopicEndpointProperties is the properties related to service bus topic endpoint types. +type RoutingServiceBusTopicEndpointProperties struct { + ConnectionString *string `json:"connectionString,omitempty"` + Name *string `json:"name,omitempty"` + SubscriptionID *string `json:"subscriptionId,omitempty"` + ResourceGroup *string `json:"resourceGroup,omitempty"` +} + +// RoutingStorageContainerProperties is the properties related to a storage container endpoint. +type RoutingStorageContainerProperties struct { + ConnectionString *string `json:"connectionString,omitempty"` + Name *string `json:"name,omitempty"` + SubscriptionID *string `json:"subscriptionId,omitempty"` + ResourceGroup *string `json:"resourceGroup,omitempty"` + ContainerName *string `json:"containerName,omitempty"` + FileNameFormat *string `json:"fileNameFormat,omitempty"` + BatchFrequencyInSeconds *int32 `json:"batchFrequencyInSeconds,omitempty"` + MaxChunkSizeInBytes *int32 `json:"maxChunkSizeInBytes,omitempty"` + Encoding *string `json:"encoding,omitempty"` +} + // SetObject is type SetObject struct { autorest.Response `json:"-"` Value *map[string]interface{} `json:"value,omitempty"` } -// SharedAccessSignatureAuthorizationRule is the properties of an IoT hub -// shared access policy. +// SharedAccessSignatureAuthorizationRule is the properties of an IoT hub shared access policy. type SharedAccessSignatureAuthorizationRule struct { autorest.Response `json:"-"` KeyName *string `json:"keyName,omitempty"` @@ -476,8 +565,7 @@ type SharedAccessSignatureAuthorizationRule struct { Rights AccessRights `json:"rights,omitempty"` } -// SharedAccessSignatureAuthorizationRuleListResult is the list of shared -// access policies with a next link. +// SharedAccessSignatureAuthorizationRuleListResult is the list of shared access policies with a next link. type SharedAccessSignatureAuthorizationRuleListResult struct { autorest.Response `json:"-"` Value *[]SharedAccessSignatureAuthorizationRule `json:"value,omitempty"` @@ -496,15 +584,14 @@ func (client SharedAccessSignatureAuthorizationRuleListResult) SharedAccessSigna autorest.WithBaseURL(to.String(client.NextLink))) } -// SkuDescription is sKU properties. +// SkuDescription is SKU properties. type SkuDescription struct { ResourceType *string `json:"resourceType,omitempty"` Sku *SkuInfo `json:"sku,omitempty"` Capacity *Capacity `json:"capacity,omitempty"` } -// SkuDescriptionListResult is the JSON-serialized array of -// IotHubSkuDescription objects with a next link. +// SkuDescriptionListResult is the JSON-serialized array of IotHubSkuDescription objects with a next link. type SkuDescriptionListResult struct { autorest.Response `json:"-"` Value *[]SkuDescription `json:"value,omitempty"` @@ -530,8 +617,7 @@ type SkuInfo struct { Capacity *int64 `json:"capacity,omitempty"` } -// StorageEndpointProperties is the properties of the Azure Storage endpoint -// for file upload. +// StorageEndpointProperties is the properties of the Azure Storage endpoint for file upload. type StorageEndpointProperties struct { SasTTLAsIso8601 *string `json:"sasTtlAsIso8601,omitempty"` ConnectionString *string `json:"connectionString,omitempty"` diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/operations.go new file mode 100644 index 000000000000..ae4d1bf0cc4e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/operations.go @@ -0,0 +1,165 @@ +package iothub + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// OperationsClient is the use this API to manage the IoT hubs in your Azure subscription. +type OperationsClient struct { + ManagementClient +} + +// NewOperationsClient creates an instance of the OperationsClient client. +func NewOperationsClient(subscriptionID string) OperationsClient { + return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client. +func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { + return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List lists all of the available IoT Hub REST API operations. +func (client OperationsClient) List() (result OperationListResult, err error) { + req, err := client.ListPreparer() + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.OperationsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.OperationsClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.OperationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client OperationsClient) ListPreparer() (*http.Request, error) { + const APIVersion = "2017-07-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.Devices/operations"), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client OperationsClient) ListResponder(resp *http.Response) (result OperationListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client OperationsClient) ListNextResults(lastResults OperationListResult) (result OperationListResult, err error) { + req, err := lastResults.OperationListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.OperationsClient", "List", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.OperationsClient", "List", resp, "Failure sending next results request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.OperationsClient", "List", resp, "Failure responding to next results request") + } + + return +} + +// ListComplete gets all elements from the list without paging. +func (client OperationsClient) ListComplete(cancel <-chan struct{}) (<-chan Operation, <-chan error) { + resultChan := make(chan Operation) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.List() + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.ListNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go index 83b97042999c..defcf95911f1 100755 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go @@ -14,9 +14,8 @@ package iothub // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/Azure/go-autorest/autorest" @@ -25,8 +24,7 @@ import ( "net/http" ) -// ResourceClient is the use this API to manage the IoT hubs in your -// subscription. +// ResourceClient is the use this API to manage the IoT hubs in your Azure subscription. type ResourceClient struct { ManagementClient } @@ -36,16 +34,14 @@ func NewResourceClient(subscriptionID string) ResourceClient { return NewResourceClientWithBaseURI(DefaultBaseURI, subscriptionID) } -// NewResourceClientWithBaseURI creates an instance of the ResourceClient -// client. +// NewResourceClientWithBaseURI creates an instance of the ResourceClient client. func NewResourceClientWithBaseURI(baseURI string, subscriptionID string) ResourceClient { return ResourceClient{NewWithBaseURI(baseURI, subscriptionID)} } // CheckNameAvailability check if an IoT hub name is available. // -// operationInputs is set the name parameter in the OperationInputs structure -// to the name of the IoT hub to check. +// operationInputs is set the name parameter in the OperationInputs structure to the name of the IoT hub to check. func (client ResourceClient) CheckNameAvailability(operationInputs OperationInputs) (result NameAvailabilityInfo, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: operationInputs, @@ -80,7 +76,7 @@ func (client ResourceClient) CheckNameAvailabilityPreparer(operationInputs Opera "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -114,13 +110,11 @@ func (client ResourceClient) CheckNameAvailabilityResponder(resp *http.Response) return } -// CreateEventHubConsumerGroup add a consumer group to an Event Hub-compatible -// endpoint in an IoT hub. +// CreateEventHubConsumerGroup add a consumer group to an Event Hub-compatible endpoint in an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the -// name of the Event Hub-compatible endpoint in the IoT hub. name is the name -// of the consumer group to add. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. eventHubEndpointName is the name of the Event Hub-compatible endpoint in the IoT hub. name is the name of the +// consumer group to add. func (client ResourceClient) CreateEventHubConsumerGroup(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (result EventHubConsumerGroupInfo, err error) { req, err := client.CreateEventHubConsumerGroupPreparer(resourceGroupName, resourceName, eventHubEndpointName, name) if err != nil { @@ -153,7 +147,7 @@ func (client ResourceClient) CreateEventHubConsumerGroupPreparer(resourceGroupNa "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -185,16 +179,13 @@ func (client ResourceClient) CreateEventHubConsumerGroupResponder(resp *http.Res return } -// CreateOrUpdate create or update the metadata of an Iot hub. The usual -// pattern to modify a property is to retrieve the IoT hub metadata and -// security metadata, and then combine them with the modified values in a new -// body to update the IoT hub. This method may poll for completion. Polling can -// be canceled by passing the cancel channel argument. The channel will be used -// to cancel polling and any outstanding HTTP requests. +// CreateOrUpdate create or update the metadata of an Iot hub. The usual pattern to modify a property is to retrieve +// the IoT hub metadata and security metadata, and then combine them with the modified values in a new body to update +// the IoT hub. This method may poll for completion. Polling can be canceled by passing the cancel channel argument. +// The channel will be used to cancel polling and any outstanding HTTP requests. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub to create or update. -// iotHubDescription is the IoT hub metadata and security metadata. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub to create or update. iotHubDescription is the IoT hub metadata and security metadata. func (client ResourceClient) CreateOrUpdate(resourceGroupName string, resourceName string, iotHubDescription Description, cancel <-chan struct{}) (<-chan Description, <-chan error) { resultChan := make(chan Description, 1) errChan := make(chan error, 1) @@ -203,18 +194,28 @@ func (client ResourceClient) CreateOrUpdate(resourceGroupName string, resourceNa Constraints: []validation.Constraint{{Target: "iotHubDescription.Subscriptionid", Name: validation.Null, Rule: true, Chain: nil}, {Target: "iotHubDescription.Resourcegroup", Name: validation.Null, Rule: true, Chain: nil}, {Target: "iotHubDescription.Properties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, - {Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, - }}, - {Target: "iotHubDescription.Properties.CloudToDevice.Feedback", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, - {Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing.FallbackRoute", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing.FallbackRoute.Source", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "iotHubDescription.Properties.Routing.FallbackRoute.EndpointNames", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing.FallbackRoute.EndpointNames", Name: validation.MaxItems, Rule: 1, Chain: nil}, + {Target: "iotHubDescription.Properties.Routing.FallbackRoute.EndpointNames", Name: validation.MinItems, Rule: 1, Chain: nil}, }}, - }}, + {Target: "iotHubDescription.Properties.Routing.FallbackRoute.IsEnabled", Name: validation.Null, Rule: true, Chain: nil}, + }}, }}, + {Target: "iotHubDescription.Properties.CloudToDevice", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, + {Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}, + {Target: "iotHubDescription.Properties.CloudToDevice.Feedback", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, + {Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}, + }}, + }}, }}, {Target: "iotHubDescription.Sku", Name: validation.Null, Rule: true, Chain: []validation.Constraint{{Target: "iotHubDescription.Sku.Capacity", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { @@ -228,8 +229,10 @@ func (client ResourceClient) CreateOrUpdate(resourceGroupName string, resourceNa var err error var result Description defer func() { + if err != nil { + errChan <- err + } resultChan <- result - errChan <- err close(resultChan) close(errChan) }() @@ -262,7 +265,7 @@ func (client ResourceClient) CreateOrUpdatePreparer(resourceGroupName string, re "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -298,12 +301,11 @@ func (client ResourceClient) CreateOrUpdateResponder(resp *http.Response) (resul return } -// Delete delete an IoT hub. This method may poll for completion. Polling can -// be canceled by passing the cancel channel argument. The channel will be used -// to cancel polling and any outstanding HTTP requests. +// Delete delete an IoT hub. This method may poll for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding HTTP requests. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub to delete. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub to delete. func (client ResourceClient) Delete(resourceGroupName string, resourceName string, cancel <-chan struct{}) (<-chan SetObject, <-chan error) { resultChan := make(chan SetObject, 1) errChan := make(chan error, 1) @@ -311,8 +313,10 @@ func (client ResourceClient) Delete(resourceGroupName string, resourceName strin var err error var result SetObject defer func() { + if err != nil { + errChan <- err + } resultChan <- result - errChan <- err close(resultChan) close(errChan) }() @@ -345,7 +349,7 @@ func (client ResourceClient) DeletePreparer(resourceGroupName string, resourceNa "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -379,13 +383,11 @@ func (client ResourceClient) DeleteResponder(resp *http.Response) (result SetObj return } -// DeleteEventHubConsumerGroup delete a consumer group from an Event -// Hub-compatible endpoint in an IoT hub. +// DeleteEventHubConsumerGroup delete a consumer group from an Event Hub-compatible endpoint in an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the -// name of the Event Hub-compatible endpoint in the IoT hub. name is the name -// of the consumer group to delete. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. eventHubEndpointName is the name of the Event Hub-compatible endpoint in the IoT hub. name is the name of the +// consumer group to delete. func (client ResourceClient) DeleteEventHubConsumerGroup(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (result autorest.Response, err error) { req, err := client.DeleteEventHubConsumerGroupPreparer(resourceGroupName, resourceName, eventHubEndpointName, name) if err != nil { @@ -418,7 +420,7 @@ func (client ResourceClient) DeleteEventHubConsumerGroupPreparer(resourceGroupNa "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -449,13 +451,12 @@ func (client ResourceClient) DeleteEventHubConsumerGroupResponder(resp *http.Res return } -// ExportDevices exports all the device identities in the IoT hub identity -// registry to an Azure Storage blob container. For more information, see: +// ExportDevices exports all the device identities in the IoT hub identity registry to an Azure Storage blob container. +// For more information, see: // https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. exportDevicesParameters is the -// parameters that specify the export devices operation. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. exportDevicesParameters is the parameters that specify the export devices operation. func (client ResourceClient) ExportDevices(resourceGroupName string, resourceName string, exportDevicesParameters ExportDevicesRequest) (result JobResponse, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: exportDevicesParameters, @@ -493,7 +494,7 @@ func (client ResourceClient) ExportDevicesPreparer(resourceGroupName string, res "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -529,8 +530,8 @@ func (client ResourceClient) ExportDevicesResponder(resp *http.Response) (result // Get get the non-security related metadata of an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. func (client ResourceClient) Get(resourceGroupName string, resourceName string) (result Description, err error) { req, err := client.GetPreparer(resourceGroupName, resourceName) if err != nil { @@ -561,7 +562,7 @@ func (client ResourceClient) GetPreparer(resourceGroupName string, resourceName "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -593,13 +594,11 @@ func (client ResourceClient) GetResponder(resp *http.Response) (result Descripti return } -// GetEventHubConsumerGroup get a consumer group from the Event Hub-compatible -// device-to-cloud endpoint for an IoT hub. +// GetEventHubConsumerGroup get a consumer group from the Event Hub-compatible device-to-cloud endpoint for an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the -// name of the Event Hub-compatible endpoint in the IoT hub. name is the name -// of the consumer group to retrieve. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. eventHubEndpointName is the name of the Event Hub-compatible endpoint in the IoT hub. name is the name of the +// consumer group to retrieve. func (client ResourceClient) GetEventHubConsumerGroup(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (result EventHubConsumerGroupInfo, err error) { req, err := client.GetEventHubConsumerGroupPreparer(resourceGroupName, resourceName, eventHubEndpointName, name) if err != nil { @@ -632,7 +631,7 @@ func (client ResourceClient) GetEventHubConsumerGroupPreparer(resourceGroupName "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -667,8 +666,8 @@ func (client ResourceClient) GetEventHubConsumerGroupResponder(resp *http.Respon // GetJob get the details of a job from an IoT hub. For more information, see: // https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. jobID is the job identifier. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. jobID is the job identifier. func (client ResourceClient) GetJob(resourceGroupName string, resourceName string, jobID string) (result JobResponse, err error) { req, err := client.GetJobPreparer(resourceGroupName, resourceName, jobID) if err != nil { @@ -700,7 +699,7 @@ func (client ResourceClient) GetJobPreparer(resourceGroupName string, resourceNa "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -732,13 +731,11 @@ func (client ResourceClient) GetJobResponder(resp *http.Response) (result JobRes return } -// GetKeysForKeyName get a shared access policy by name from an IoT hub. For -// more information, see: +// GetKeysForKeyName get a shared access policy by name from an IoT hub. For more information, see: // https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. keyName is the name of the -// shared access policy. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. keyName is the name of the shared access policy. func (client ResourceClient) GetKeysForKeyName(resourceGroupName string, resourceName string, keyName string) (result SharedAccessSignatureAuthorizationRule, err error) { req, err := client.GetKeysForKeyNamePreparer(resourceGroupName, resourceName, keyName) if err != nil { @@ -770,7 +767,7 @@ func (client ResourceClient) GetKeysForKeyNamePreparer(resourceGroupName string, "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -804,8 +801,8 @@ func (client ResourceClient) GetKeysForKeyNameResponder(resp *http.Response) (re // GetQuotaMetrics get the quota metrics for an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. func (client ResourceClient) GetQuotaMetrics(resourceGroupName string, resourceName string) (result QuotaMetricInfoListResult, err error) { req, err := client.GetQuotaMetricsPreparer(resourceGroupName, resourceName) if err != nil { @@ -836,7 +833,7 @@ func (client ResourceClient) GetQuotaMetricsPreparer(resourceGroupName string, r "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -892,10 +889,55 @@ func (client ResourceClient) GetQuotaMetricsNextResults(lastResults QuotaMetricI return } +// GetQuotaMetricsComplete gets all elements from the list without paging. +func (client ResourceClient) GetQuotaMetricsComplete(resourceGroupName string, resourceName string, cancel <-chan struct{}) (<-chan QuotaMetricInfo, <-chan error) { + resultChan := make(chan QuotaMetricInfo) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.GetQuotaMetrics(resourceGroupName, resourceName) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.GetQuotaMetricsNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} + // GetStats get the statistics from an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. func (client ResourceClient) GetStats(resourceGroupName string, resourceName string) (result RegistryStatistics, err error) { req, err := client.GetStatsPreparer(resourceGroupName, resourceName) if err != nil { @@ -926,7 +968,7 @@ func (client ResourceClient) GetStatsPreparer(resourceGroupName string, resource "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -960,8 +1002,8 @@ func (client ResourceClient) GetStatsResponder(resp *http.Response) (result Regi // GetValidSkus get the list of valid SKUs for an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. func (client ResourceClient) GetValidSkus(resourceGroupName string, resourceName string) (result SkuDescriptionListResult, err error) { req, err := client.GetValidSkusPreparer(resourceGroupName, resourceName) if err != nil { @@ -992,7 +1034,7 @@ func (client ResourceClient) GetValidSkusPreparer(resourceGroupName string, reso "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1048,13 +1090,57 @@ func (client ResourceClient) GetValidSkusNextResults(lastResults SkuDescriptionL return } -// ImportDevices import, update, or delete device identities in the IoT hub -// identity registry from a blob. For more information, see: +// GetValidSkusComplete gets all elements from the list without paging. +func (client ResourceClient) GetValidSkusComplete(resourceGroupName string, resourceName string, cancel <-chan struct{}) (<-chan SkuDescription, <-chan error) { + resultChan := make(chan SkuDescription) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.GetValidSkus(resourceGroupName, resourceName) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.GetValidSkusNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} + +// ImportDevices import, update, or delete device identities in the IoT hub identity registry from a blob. For more +// information, see: // https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. importDevicesParameters is the -// parameters that specify the import devices operation. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. importDevicesParameters is the parameters that specify the import devices operation. func (client ResourceClient) ImportDevices(resourceGroupName string, resourceName string, importDevicesParameters ImportDevicesRequest) (result JobResponse, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: importDevicesParameters, @@ -1092,7 +1178,7 @@ func (client ResourceClient) ImportDevicesPreparer(resourceGroupName string, res "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1128,8 +1214,7 @@ func (client ResourceClient) ImportDevicesResponder(resp *http.Response) (result // ListByResourceGroup get all the IoT hubs in a resource group. // -// resourceGroupName is the name of the resource group that contains the IoT -// hubs. +// resourceGroupName is the name of the resource group that contains the IoT hubs. func (client ResourceClient) ListByResourceGroup(resourceGroupName string) (result DescriptionListResult, err error) { req, err := client.ListByResourceGroupPreparer(resourceGroupName) if err != nil { @@ -1159,7 +1244,7 @@ func (client ResourceClient) ListByResourceGroupPreparer(resourceGroupName strin "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1215,6 +1300,51 @@ func (client ResourceClient) ListByResourceGroupNextResults(lastResults Descript return } +// ListByResourceGroupComplete gets all elements from the list without paging. +func (client ResourceClient) ListByResourceGroupComplete(resourceGroupName string, cancel <-chan struct{}) (<-chan Description, <-chan error) { + resultChan := make(chan Description) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.ListByResourceGroup(resourceGroupName) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.ListByResourceGroupNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} + // ListBySubscription get all the IoT hubs in a subscription. func (client ResourceClient) ListBySubscription() (result DescriptionListResult, err error) { req, err := client.ListBySubscriptionPreparer() @@ -1244,7 +1374,7 @@ func (client ResourceClient) ListBySubscriptionPreparer() (*http.Request, error) "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1300,12 +1430,56 @@ func (client ResourceClient) ListBySubscriptionNextResults(lastResults Descripti return } -// ListEventHubConsumerGroups get a list of the consumer groups in the Event -// Hub-compatible device-to-cloud endpoint in an IoT hub. +// ListBySubscriptionComplete gets all elements from the list without paging. +func (client ResourceClient) ListBySubscriptionComplete(cancel <-chan struct{}) (<-chan Description, <-chan error) { + resultChan := make(chan Description) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.ListBySubscription() + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.ListBySubscriptionNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} + +// ListEventHubConsumerGroups get a list of the consumer groups in the Event Hub-compatible device-to-cloud endpoint in +// an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the -// name of the Event Hub-compatible endpoint. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. eventHubEndpointName is the name of the Event Hub-compatible endpoint. func (client ResourceClient) ListEventHubConsumerGroups(resourceGroupName string, resourceName string, eventHubEndpointName string) (result EventHubConsumerGroupsListResult, err error) { req, err := client.ListEventHubConsumerGroupsPreparer(resourceGroupName, resourceName, eventHubEndpointName) if err != nil { @@ -1337,7 +1511,7 @@ func (client ResourceClient) ListEventHubConsumerGroupsPreparer(resourceGroupNam "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1393,12 +1567,56 @@ func (client ResourceClient) ListEventHubConsumerGroupsNextResults(lastResults E return } -// ListJobs get a list of all the jobs in an IoT hub. For more information, -// see: +// ListEventHubConsumerGroupsComplete gets all elements from the list without paging. +func (client ResourceClient) ListEventHubConsumerGroupsComplete(resourceGroupName string, resourceName string, eventHubEndpointName string, cancel <-chan struct{}) (<-chan string, <-chan error) { + resultChan := make(chan string) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.ListEventHubConsumerGroups(resourceGroupName, resourceName, eventHubEndpointName) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.ListEventHubConsumerGroupsNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} + +// ListJobs get a list of all the jobs in an IoT hub. For more information, see: // https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. func (client ResourceClient) ListJobs(resourceGroupName string, resourceName string) (result JobResponseListResult, err error) { req, err := client.ListJobsPreparer(resourceGroupName, resourceName) if err != nil { @@ -1429,7 +1647,7 @@ func (client ResourceClient) ListJobsPreparer(resourceGroupName string, resource "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1485,11 +1703,56 @@ func (client ResourceClient) ListJobsNextResults(lastResults JobResponseListResu return } -// ListKeys get the security metadata for an IoT hub. For more information, -// see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. +// ListJobsComplete gets all elements from the list without paging. +func (client ResourceClient) ListJobsComplete(resourceGroupName string, resourceName string, cancel <-chan struct{}) (<-chan JobResponse, <-chan error) { + resultChan := make(chan JobResponse) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.ListJobs(resourceGroupName, resourceName) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.ListJobsNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} + +// ListKeys get the security metadata for an IoT hub. For more information, see: +// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. func (client ResourceClient) ListKeys(resourceGroupName string, resourceName string) (result SharedAccessSignatureAuthorizationRuleListResult, err error) { req, err := client.ListKeysPreparer(resourceGroupName, resourceName) if err != nil { @@ -1520,7 +1783,7 @@ func (client ResourceClient) ListKeysPreparer(resourceGroupName string, resource "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1575,3 +1838,48 @@ func (client ResourceClient) ListKeysNextResults(lastResults SharedAccessSignatu return } + +// ListKeysComplete gets all elements from the list without paging. +func (client ResourceClient) ListKeysComplete(resourceGroupName string, resourceName string, cancel <-chan struct{}) (<-chan SharedAccessSignatureAuthorizationRule, <-chan error) { + resultChan := make(chan SharedAccessSignatureAuthorizationRule) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.ListKeys(resourceGroupName, resourceName) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.ListKeysNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go index d33d9dd5ad26..71c1b6e27286 100755 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go @@ -14,15 +14,15 @@ package iothub // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0 +// Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { - return "Azure-SDK-For-Go/v10.3.0-beta arm-iothub/2017-07-01" + return "Azure-SDK-For-Go/v11.0.0-beta arm-iothub/2017-07-01" } // Version returns the semantic version (see http://semver.org) of the client. func Version() string { - return "v10.3.0-beta" + return "v11.0.0-beta" } diff --git a/vendor/vendor.json b/vendor/vendor.json index 3f4425e908a2..34e635781fca 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -107,10 +107,10 @@ "versionExact": "v10.3.0-beta" }, { - "checksumSHA1": "wSLOrUgDpf9pmtZKl2KO3OavrZU=", + "checksumSHA1": "NCPG/4kLZlxz92cQE4NMyORU94k=", "path": "github.com/Azure/azure-sdk-for-go/arm/iothub", - "revision": "dedad7d55bef3a5fd61d3b682bcba0a93cf315e8", - "revisionTime": "2017-08-24T19:57:27Z" + "revision": "9f366792afa3e0ddaecdc860e793ba9d75e76c27", + "revisionTime": "2017-10-06T23:46:41Z" }, { "checksumSHA1": "FloEh78hgEozkpt0y4SPWK23/wI=", From 6d8a41d40d52628604b0fdb0d8058d15dd222925 Mon Sep 17 00:00:00 2001 From: girishramnani Date: Wed, 11 Oct 2017 13:43:33 +0530 Subject: [PATCH 13/69] Added keys to the lifecycle and schema --- .../resource_arm_iothub_resource_provider.go | 81 +++++++++++++++---- ...ource_arm_iothub_resource_provider_test.go | 1 - 2 files changed, 65 insertions(+), 17 deletions(-) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index bacf410b0223..643a34f7f9d1 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -21,24 +21,10 @@ func resourceArmIotHub() *schema.Resource { Required: true, ForceNew: true, }, - - "type": { - Type: schema.TypeString, - Computed: true, - }, - + "tags": tagsSchema(), "location": locationSchema(), "resource_group_name": resourceGroupNameSchema(), - - "etag": { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "tags": tagsSchema(), - "sku": { Type: schema.TypeList, MaxItems: 1, @@ -73,6 +59,47 @@ func resourceArmIotHub() *schema.Resource { }, }, }, + + "type": { + Type: schema.TypeString, + Computed: true, + }, + + "etag": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "hostname": { + Type: schema.TypeString, + Computed: true, + }, + + "shared_access_policy": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key_name": { + Type: schema.TypeString, + Computed: true, + }, + "primary_key": { + Type: schema.TypeString, + Computed: true, + }, + "secondary_key": { + Type: schema.TypeString, + Computed: true, + }, + "permissions": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, }, } @@ -163,11 +190,33 @@ func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { armClient := meta.(*ArmClient) iothubClient := armClient.iothubResourceClient - desc, err := iothubClient.Get(id.ResourceGroup, id.Path["IotHubs"]) + iothubName := id.Path["IotHubs"] + desc, err := iothubClient.Get(id.ResourceGroup, iothubName) + + if err != nil { + return err + } + + properties := desc.Properties + + keysResp, err := iothubClient.ListKeys(id.ResourceGroup, iothubName) + + var keys []map[string]interface{} + for _, key := range *keysResp.Value { + keyMap := make(map[string]interface{}) + keyMap["key_name"] = key.KeyName + keyMap["primary_key"] = key.PrimaryKey + keyMap["secondary_key"] = key.SecondaryKey + keyMap["permissions"] = string(key.Rights) + keys = append(keys, keyMap) + } + if err != nil { return err } + d.Set("shared_access_policy", keys) + d.Set("hostname", *properties.HostName) d.Set("etag", *desc.Etag) d.Set("type", *desc.Type) flattenAndSetTags(d, desc.Tags) diff --git a/azurerm/resource_arm_iothub_resource_provider_test.go b/azurerm/resource_arm_iothub_resource_provider_test.go index 67eaefe7e8b0..3a21fd6bbf25 100644 --- a/azurerm/resource_arm_iothub_resource_provider_test.go +++ b/azurerm/resource_arm_iothub_resource_provider_test.go @@ -70,7 +70,6 @@ func testCheckAzureRMIotHubExists(name string) resource.TestCheckFunc { conn := testAccProvider.Meta().(*ArmClient).iothubResourceClient resp, err := conn.Get(resourceGroup, iothubName) - if err != nil { if resp.StatusCode == http.StatusNotFound { return fmt.Errorf("Bad: IotHub %q (resource group: %q) does not exist", iothubName, resourceGroup) From 5dd8cef221a8907045d73df9951fc73db99da771 Mon Sep 17 00:00:00 2001 From: girishramnani Date: Wed, 11 Oct 2017 14:29:39 +0530 Subject: [PATCH 14/69] resolved a keys struct related bug --- azurerm/resource_arm_iothub_resource_provider.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 643a34f7f9d1..fdeb8a006eb4 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -2,6 +2,7 @@ package azurerm import ( "errors" + "log" "github.com/Azure/azure-sdk-for-go/arm/iothub" "github.com/hashicorp/terraform/helper/schema" @@ -204,9 +205,9 @@ func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { var keys []map[string]interface{} for _, key := range *keysResp.Value { keyMap := make(map[string]interface{}) - keyMap["key_name"] = key.KeyName - keyMap["primary_key"] = key.PrimaryKey - keyMap["secondary_key"] = key.SecondaryKey + keyMap["key_name"] = *key.KeyName + keyMap["primary_key"] = *key.PrimaryKey + keyMap["secondary_key"] = *key.SecondaryKey keyMap["permissions"] = string(key.Rights) keys = append(keys, keyMap) } @@ -214,6 +215,7 @@ func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { if err != nil { return err } + log.Println("[GIRISH]", keys) d.Set("shared_access_policy", keys) d.Set("hostname", *properties.HostName) From 677794f1148dff997bbad0b99d240249867b7648 Mon Sep 17 00:00:00 2001 From: girishramnani Date: Thu, 12 Oct 2017 13:22:25 +0530 Subject: [PATCH 15/69] Added documentation for iothub --- website/azurerm.erb | 11 +++++ website/docs/r/iothub.html.markdown | 66 +++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 website/docs/r/iothub.html.markdown diff --git a/website/azurerm.erb b/website/azurerm.erb index bbdb325507b3..a0513c7126ee 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -497,9 +497,20 @@ + > + IotHub Resources + + +
  • Azure Service Management Provider »
  • + + <% end %> diff --git a/website/docs/r/iothub.html.markdown b/website/docs/r/iothub.html.markdown new file mode 100644 index 000000000000..474a0087e3eb --- /dev/null +++ b/website/docs/r/iothub.html.markdown @@ -0,0 +1,66 @@ +--- +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_iothub" +sidebar_current: "docs-azurerm-resource-iothub" +description: |- + Creates a new IotHub resource +--- + +# azurerm\_iothub + +Creates a new IotHub + +## Example Usage + +```hcl +resource "azurerm_resource_group" "test" { + name = "resourceGroup1" + location = "West US" +} + + +resource "azurerm_iothub" "test" { + name = "test" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "westus" + sku { + name = "S1" + tier = "Standard" + capacity = "1" + } + + tags { + "purpose" = "testing" + } + } + + +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Specifies the name of the IotHub resource. Changing this forces a new resource to be created. + +* `resource_group_name` - (Required) The name of the resource group under which the IotHub resource has to be created. Changing this forces a new resource to be created. + +* `location` - (Required) Specifies the supported Azure location where the resource has to be createc. Changing this forces a new resource to be created. + +* `sku` - (Required) Specifies the capacity and tier of the IotHub. + +* `tags` - (Optional) A mapping of tags to assign to the resource. + +## Attributes Reference + +The following attributes are exported: + +* `id` - The IotHub ID. + +* `etag` - The etag of IotHub Resource. + +* `hostname` - The hostname of the IotHub Resource. + +* `shared_access_policy` - The list of access policy which contain access keys and permissions. + + From f2acf202d1164fa3b6bd8b99951ba712883506a6 Mon Sep 17 00:00:00 2001 From: girishramnani Date: Sun, 15 Oct 2017 19:32:10 +0530 Subject: [PATCH 16/69] Added importer in the iothub resource group As the refresh function ( read lifecyle ) of the iothub resource is only dependent on the id of the resource to genarate the state StatePassthrough method is used --- azurerm/resource_arm_iothub_resource_provider.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index fdeb8a006eb4..295065eecc4e 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -15,6 +15,9 @@ func resourceArmIotHub() *schema.Resource { Read: resourceArmIotHubRead, Update: resourceArmIotHubCreateAndUpdate, Delete: resourceArmIotHubDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, Schema: map[string]*schema.Schema{ "name": { From 0a1b3fca0b357f789ddca11f60f90023b1b2282b Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Tue, 19 Dec 2017 17:41:51 -0600 Subject: [PATCH 17/69] Iothub consumer group initial commit Signed-off-by: shelley.bess --- azurerm/resource_arm_iothub_consumer_group.go | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 azurerm/resource_arm_iothub_consumer_group.go diff --git a/azurerm/resource_arm_iothub_consumer_group.go b/azurerm/resource_arm_iothub_consumer_group.go new file mode 100644 index 000000000000..9c8aaf8efc02 --- /dev/null +++ b/azurerm/resource_arm_iothub_consumer_group.go @@ -0,0 +1,120 @@ +package azurerm + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmIotHubConsumerGroup() *schema.Resource { + return &schema.Resource{ + Create: resourceArmIotHubConsumerGroupCreate, + Read: resourceArmIotHubConsumerGroupRead, + Delete: resourceArmIotHubConsumerGroupDelete, + + Schema: map[string]*schema.Schema{ + "consumer_group_name": { + Type: schema.TypeString, + Required: true, + }, + "resource_group_name": { + Type: schema.TypeString, + Required: true, + }, + "iotHub_name": { + Type: schema.TypeString, + Required: true, + }, + "event_hub_endpoint": { + Type: schema.TypeString, + Required: true, + }, + }, + } +} + +func resourceArmIotHubConsumerGroupCreate(d *schema.ResourceData, meta interface{}) error { + armClient := meta.(*ArmClient) + iothubClient := armClient.iothubResourceClient + log.Printf("[INFO} preparing arguments for AzureRM IoTHub Consumer Group creation.") + + groupName := d.Get("consumer_group_name").(string) + resourceGroup := d.Get("resource_group_name").(string) + iotHubName := d.Get("iotHub_name").(string) + eventhubEndpoint := d.Get("event_hub_endpoint").(string) + + _, err := iothubClient.CreateEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) + if err != nil { + return err + } + + check, err := iothubClient.GetEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) + if err != nil { + return err + } + + if check.ID == nil { + return fmt.Errorf("Cannot read IoTHub Consumer Group %s (resource group %s) ID", groupName, resourceGroup) + } + + d.SetId(*check.ID) + + return resourceArmIotHubConsumerGroupRead(d, meta) +} + +func resourceArmIotHubConsumerGroupRead(d *schema.ResourceData, meta interface{}) error { + armClient := meta.(*ArmClient) + iothubClient := armClient.iothubResourceClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + + resourceGroup := id.ResourceGroup + groupName := id.Path["consumergroups"] + iotHubName := id.Path["resourcename"] + eventhubEndpoint := id.Path["eventhubs"] + + resp, err := iothubClient.GetEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + d.SetId("") + return nil + } + return fmt.Errorf("Error making read request on Azure IoTHub Consumer Group %s: %+v", groupName, err) + } + + d.Set("consumer_group_name", groupName) + d.Set("resource_group_name", resourceGroup) + d.Set("iotHub_name", iotHubName) + d.Set("event_hub_endpoint", eventhubEndpoint) + + return nil +} + +func resourceArmIotHubConsumerGroupDelete(d *schema.ResourceData, meta interface{}) error { + armClient := meta.(*ArmClient) + iothubClient := armClient.iothubResourceClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + + resourceGroup := id.ResourceGroup + groupName := id.Path["consumergroups"] + iotHubName := id.Path["resourcename"] + eventhubEndpoint := id.Path["eventhubs"] + + resp, err := iothubClient.DeleteEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) + if err != nil { + if !utils.ResponseWasNotFound(resp) { + return fmt.Errorf("Error issuing Azure ARM delete request of IoTHub Consumer Group '%s' : %+v", groupName, err) + } + } + + return nil +} From ffac304a9595f96f3762c744ea952ba53a002b0b Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Thu, 28 Sep 2017 11:49:35 +0530 Subject: [PATCH 18/69] added iothub dependency --- .gitignore | 2 + .../resource_arm_iothub_resource_provider.go | 0 .../azure-sdk-for-go/arm/iothub/client.go | 53 + .../azure-sdk-for-go/arm/iothub/models.go | 539 ++++++ .../azure-sdk-for-go/arm/iothub/resource.go | 1577 +++++++++++++++++ .../azure-sdk-for-go/arm/iothub/version.go | 28 + vendor/vendor.json | 12 + 7 files changed, 2211 insertions(+) create mode 100644 azurerm/resource_arm_iothub_resource_provider.go create mode 100755 vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go create mode 100755 vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go create mode 100755 vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go create mode 100755 vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go diff --git a/.gitignore b/.gitignore index 759d64580fcd..5f873cf88e6c 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,5 @@ website/vendor # Test exclusions !command/test-fixtures/**/*.tfstate !command/test-fixtures/**/.terraform/ + +.env.sh diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go new file mode 100755 index 000000000000..b54c132eeeee --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go @@ -0,0 +1,53 @@ +// Package iothub implements the Azure ARM Iothub service API version +// 2016-02-03. +// +// Use this API to manage the IoT hubs in your subscription. +package iothub + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" +) + +const ( + // DefaultBaseURI is the default URI used for the service Iothub + DefaultBaseURI = "https://management.azure.com" +) + +// ManagementClient is the base client for Iothub. +type ManagementClient struct { + autorest.Client + BaseURI string + SubscriptionID string +} + +// New creates an instance of the ManagementClient client. +func New(subscriptionID string) ManagementClient { + return NewWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewWithBaseURI creates an instance of the ManagementClient client. +func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { + return ManagementClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: baseURI, + SubscriptionID: subscriptionID, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go new file mode 100755 index 000000000000..6fa4abb25319 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go @@ -0,0 +1,539 @@ +package iothub + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" + "github.com/Azure/go-autorest/autorest/to" + "net/http" +) + +// AccessRights enumerates the values for access rights. +type AccessRights string + +const ( + // DeviceConnect specifies the device connect state for access rights. + DeviceConnect AccessRights = "DeviceConnect" + // RegistryRead specifies the registry read state for access rights. + RegistryRead AccessRights = "RegistryRead" + // RegistryReadDeviceConnect specifies the registry read device connect + // state for access rights. + RegistryReadDeviceConnect AccessRights = "RegistryRead, DeviceConnect" + // RegistryReadRegistryWrite specifies the registry read registry write + // state for access rights. + RegistryReadRegistryWrite AccessRights = "RegistryRead, RegistryWrite" + // RegistryReadRegistryWriteDeviceConnect specifies the registry read + // registry write device connect state for access rights. + RegistryReadRegistryWriteDeviceConnect AccessRights = "RegistryRead, RegistryWrite, DeviceConnect" + // RegistryReadRegistryWriteServiceConnect specifies the registry read + // registry write service connect state for access rights. + RegistryReadRegistryWriteServiceConnect AccessRights = "RegistryRead, RegistryWrite, ServiceConnect" + // RegistryReadRegistryWriteServiceConnectDeviceConnect specifies the + // registry read registry write service connect device connect state for + // access rights. + RegistryReadRegistryWriteServiceConnectDeviceConnect AccessRights = "RegistryRead, RegistryWrite, ServiceConnect, DeviceConnect" + // RegistryReadServiceConnect specifies the registry read service connect + // state for access rights. + RegistryReadServiceConnect AccessRights = "RegistryRead, ServiceConnect" + // RegistryReadServiceConnectDeviceConnect specifies the registry read + // service connect device connect state for access rights. + RegistryReadServiceConnectDeviceConnect AccessRights = "RegistryRead, ServiceConnect, DeviceConnect" + // RegistryWrite specifies the registry write state for access rights. + RegistryWrite AccessRights = "RegistryWrite" + // RegistryWriteDeviceConnect specifies the registry write device connect + // state for access rights. + RegistryWriteDeviceConnect AccessRights = "RegistryWrite, DeviceConnect" + // RegistryWriteServiceConnect specifies the registry write service connect + // state for access rights. + RegistryWriteServiceConnect AccessRights = "RegistryWrite, ServiceConnect" + // RegistryWriteServiceConnectDeviceConnect specifies the registry write + // service connect device connect state for access rights. + RegistryWriteServiceConnectDeviceConnect AccessRights = "RegistryWrite, ServiceConnect, DeviceConnect" + // ServiceConnect specifies the service connect state for access rights. + ServiceConnect AccessRights = "ServiceConnect" + // ServiceConnectDeviceConnect specifies the service connect device connect + // state for access rights. + ServiceConnectDeviceConnect AccessRights = "ServiceConnect, DeviceConnect" +) + +// Capabilities enumerates the values for capabilities. +type Capabilities string + +const ( + // DeviceManagement specifies the device management state for capabilities. + DeviceManagement Capabilities = "DeviceManagement" + // None specifies the none state for capabilities. + None Capabilities = "None" +) + +// IPFilterActionType enumerates the values for ip filter action type. +type IPFilterActionType string + +const ( + // Accept specifies the accept state for ip filter action type. + Accept IPFilterActionType = "Accept" + // Reject specifies the reject state for ip filter action type. + Reject IPFilterActionType = "Reject" +) + +// JobStatus enumerates the values for job status. +type JobStatus string + +const ( + // Cancelled specifies the cancelled state for job status. + Cancelled JobStatus = "cancelled" + // Completed specifies the completed state for job status. + Completed JobStatus = "completed" + // Enqueued specifies the enqueued state for job status. + Enqueued JobStatus = "enqueued" + // Failed specifies the failed state for job status. + Failed JobStatus = "failed" + // Running specifies the running state for job status. + Running JobStatus = "running" + // Unknown specifies the unknown state for job status. + Unknown JobStatus = "unknown" +) + +// JobType enumerates the values for job type. +type JobType string + +const ( + // JobTypeBackup specifies the job type backup state for job type. + JobTypeBackup JobType = "backup" + // JobTypeExport specifies the job type export state for job type. + JobTypeExport JobType = "export" + // JobTypeFactoryResetDevice specifies the job type factory reset device + // state for job type. + JobTypeFactoryResetDevice JobType = "factoryResetDevice" + // JobTypeFirmwareUpdate specifies the job type firmware update state for + // job type. + JobTypeFirmwareUpdate JobType = "firmwareUpdate" + // JobTypeImport specifies the job type import state for job type. + JobTypeImport JobType = "import" + // JobTypeReadDeviceProperties specifies the job type read device + // properties state for job type. + JobTypeReadDeviceProperties JobType = "readDeviceProperties" + // JobTypeRebootDevice specifies the job type reboot device state for job + // type. + JobTypeRebootDevice JobType = "rebootDevice" + // JobTypeUnknown specifies the job type unknown state for job type. + JobTypeUnknown JobType = "unknown" + // JobTypeUpdateDeviceConfiguration specifies the job type update device + // configuration state for job type. + JobTypeUpdateDeviceConfiguration JobType = "updateDeviceConfiguration" + // JobTypeWriteDeviceProperties specifies the job type write device + // properties state for job type. + JobTypeWriteDeviceProperties JobType = "writeDeviceProperties" +) + +// NameUnavailabilityReason enumerates the values for name unavailability +// reason. +type NameUnavailabilityReason string + +const ( + // AlreadyExists specifies the already exists state for name unavailability + // reason. + AlreadyExists NameUnavailabilityReason = "AlreadyExists" + // Invalid specifies the invalid state for name unavailability reason. + Invalid NameUnavailabilityReason = "Invalid" +) + +// OperationMonitoringLevel enumerates the values for operation monitoring +// level. +type OperationMonitoringLevel string + +const ( + // OperationMonitoringLevelError specifies the operation monitoring level + // error state for operation monitoring level. + OperationMonitoringLevelError OperationMonitoringLevel = "Error" + // OperationMonitoringLevelErrorInformation specifies the operation + // monitoring level error information state for operation monitoring level. + OperationMonitoringLevelErrorInformation OperationMonitoringLevel = "Error, Information" + // OperationMonitoringLevelInformation specifies the operation monitoring + // level information state for operation monitoring level. + OperationMonitoringLevelInformation OperationMonitoringLevel = "Information" + // OperationMonitoringLevelNone specifies the operation monitoring level + // none state for operation monitoring level. + OperationMonitoringLevelNone OperationMonitoringLevel = "None" +) + +// ScaleType enumerates the values for scale type. +type ScaleType string + +const ( + // ScaleTypeAutomatic specifies the scale type automatic state for scale + // type. + ScaleTypeAutomatic ScaleType = "Automatic" + // ScaleTypeManual specifies the scale type manual state for scale type. + ScaleTypeManual ScaleType = "Manual" + // ScaleTypeNone specifies the scale type none state for scale type. + ScaleTypeNone ScaleType = "None" +) + +// Sku enumerates the values for sku. +type Sku string + +const ( + // F1 specifies the f1 state for sku. + F1 Sku = "F1" + // S1 specifies the s1 state for sku. + S1 Sku = "S1" + // S2 specifies the s2 state for sku. + S2 Sku = "S2" + // S3 specifies the s3 state for sku. + S3 Sku = "S3" +) + +// SkuTier enumerates the values for sku tier. +type SkuTier string + +const ( + // Free specifies the free state for sku tier. + Free SkuTier = "Free" + // Standard specifies the standard state for sku tier. + Standard SkuTier = "Standard" +) + +// Capacity is ioT Hub capacity information. +type Capacity struct { + Minimum *int64 `json:"minimum,omitempty"` + Maximum *int64 `json:"maximum,omitempty"` + Default *int64 `json:"default,omitempty"` + ScaleType ScaleType `json:"scaleType,omitempty"` +} + +// CloudToDeviceProperties is the IoT hub cloud-to-device messaging properties. +type CloudToDeviceProperties struct { + MaxDeliveryCount *int32 `json:"maxDeliveryCount,omitempty"` + DefaultTTLAsIso8601 *string `json:"defaultTtlAsIso8601,omitempty"` + Feedback *FeedbackProperties `json:"feedback,omitempty"` +} + +// Description is the description of the IoT hub. +type Description struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` + Subscriptionid *string `json:"subscriptionid,omitempty"` + Resourcegroup *string `json:"resourcegroup,omitempty"` + Etag *string `json:"etag,omitempty"` + Properties *Properties `json:"properties,omitempty"` + Sku *SkuInfo `json:"sku,omitempty"` +} + +// DescriptionListResult is the JSON-serialized array of IotHubDescription +// objects with a next link. +type DescriptionListResult struct { + autorest.Response `json:"-"` + Value *[]Description `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// DescriptionListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client DescriptionListResult) DescriptionListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// ErrorDetails is error details. +type ErrorDetails struct { + Code *string `json:"Code,omitempty"` + HTTPStatusCode *string `json:"HttpStatusCode,omitempty"` + Message *string `json:"Message,omitempty"` + Details *string `json:"Details,omitempty"` +} + +// EventHubConsumerGroupInfo is the properties of the EventHubConsumerGroupInfo +// object. +type EventHubConsumerGroupInfo struct { + autorest.Response `json:"-"` + Tags *map[string]*string `json:"tags,omitempty"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` +} + +// EventHubConsumerGroupsListResult is the JSON-serialized array of Event +// Hub-compatible consumer group names with a next link. +type EventHubConsumerGroupsListResult struct { + autorest.Response `json:"-"` + Value *[]string `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// EventHubConsumerGroupsListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client EventHubConsumerGroupsListResult) EventHubConsumerGroupsListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// EventHubProperties is the properties of the provisioned Event Hub-compatible +// endpoint used by the IoT hub. +type EventHubProperties struct { + RetentionTimeInDays *int64 `json:"retentionTimeInDays,omitempty"` + PartitionCount *int32 `json:"partitionCount,omitempty"` + PartitionIds *[]string `json:"partitionIds,omitempty"` + Path *string `json:"path,omitempty"` + Endpoint *string `json:"endpoint,omitempty"` +} + +// ExportDevicesRequest is use to provide parameters when requesting an export +// of all devices in the IoT hub. +type ExportDevicesRequest struct { + ExportBlobContainerURI *string `json:"ExportBlobContainerUri,omitempty"` + ExcludeKeys *bool `json:"ExcludeKeys,omitempty"` +} + +// FeedbackProperties is the properties of the feedback queue for +// cloud-to-device messages. +type FeedbackProperties struct { + LockDurationAsIso8601 *string `json:"lockDurationAsIso8601,omitempty"` + TTLAsIso8601 *string `json:"ttlAsIso8601,omitempty"` + MaxDeliveryCount *int32 `json:"maxDeliveryCount,omitempty"` +} + +// ImportDevicesRequest is use to provide parameters when requesting an import +// of all devices in the hub. +type ImportDevicesRequest struct { + InputBlobContainerURI *string `json:"InputBlobContainerUri,omitempty"` + OutputBlobContainerURI *string `json:"OutputBlobContainerUri,omitempty"` +} + +// IPFilterRule is the IP filter rules for the IoT hub. +type IPFilterRule struct { + FilterName *string `json:"filterName,omitempty"` + Action IPFilterActionType `json:"action,omitempty"` + IPMask *string `json:"ipMask,omitempty"` +} + +// JobResponse is the properties of the Job Response object. +type JobResponse struct { + autorest.Response `json:"-"` + JobID *string `json:"jobId,omitempty"` + StartTimeUtc *date.TimeRFC1123 `json:"startTimeUtc,omitempty"` + EndTimeUtc *date.TimeRFC1123 `json:"endTimeUtc,omitempty"` + Type JobType `json:"type,omitempty"` + Status JobStatus `json:"status,omitempty"` + FailureReason *string `json:"failureReason,omitempty"` + StatusMessage *string `json:"statusMessage,omitempty"` + ParentJobID *string `json:"parentJobId,omitempty"` +} + +// JobResponseListResult is the JSON-serialized array of JobResponse objects +// with a next link. +type JobResponseListResult struct { + autorest.Response `json:"-"` + Value *[]JobResponse `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// JobResponseListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client JobResponseListResult) JobResponseListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// MessagingEndpointProperties is the properties of the messaging endpoints +// used by this IoT hub. +type MessagingEndpointProperties struct { + LockDurationAsIso8601 *string `json:"lockDurationAsIso8601,omitempty"` + TTLAsIso8601 *string `json:"ttlAsIso8601,omitempty"` + MaxDeliveryCount *int32 `json:"maxDeliveryCount,omitempty"` +} + +// NameAvailabilityInfo is the properties indicating whether a given IoT hub +// name is available. +type NameAvailabilityInfo struct { + autorest.Response `json:"-"` + NameAvailable *bool `json:"nameAvailable,omitempty"` + Reason NameUnavailabilityReason `json:"reason,omitempty"` + Message *string `json:"message,omitempty"` +} + +// OperationInputs is input values. +type OperationInputs struct { + Name *string `json:"Name,omitempty"` +} + +// OperationsMonitoringProperties is the operations monitoring properties for +// the IoT hub. The possible keys to the dictionary are Connections, +// DeviceTelemetry, C2DCommands, DeviceIdentityOperations, +// FileUploadOperations. +type OperationsMonitoringProperties struct { + Events *map[string]*OperationMonitoringLevel `json:"events,omitempty"` +} + +// Properties is the properties of an IoT hub. +type Properties struct { + AuthorizationPolicies *[]SharedAccessSignatureAuthorizationRule `json:"authorizationPolicies,omitempty"` + IPFilterRules *[]IPFilterRule `json:"ipFilterRules,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` + HostName *string `json:"hostName,omitempty"` + EventHubEndpoints *map[string]*EventHubProperties `json:"eventHubEndpoints,omitempty"` + StorageEndpoints *map[string]*StorageEndpointProperties `json:"storageEndpoints,omitempty"` + MessagingEndpoints *map[string]*MessagingEndpointProperties `json:"messagingEndpoints,omitempty"` + EnableFileUploadNotifications *bool `json:"enableFileUploadNotifications,omitempty"` + CloudToDevice *CloudToDeviceProperties `json:"cloudToDevice,omitempty"` + Comments *string `json:"comments,omitempty"` + OperationsMonitoringProperties *OperationsMonitoringProperties `json:"operationsMonitoringProperties,omitempty"` + Features Capabilities `json:"features,omitempty"` +} + +// QuotaMetricInfo is quota metrics properties. +type QuotaMetricInfo struct { + Name *string `json:"Name,omitempty"` + CurrentValue *int64 `json:"CurrentValue,omitempty"` + MaxValue *int64 `json:"MaxValue,omitempty"` +} + +// QuotaMetricInfoListResult is the JSON-serialized array of +// IotHubQuotaMetricInfo objects with a next link. +type QuotaMetricInfoListResult struct { + autorest.Response `json:"-"` + Value *[]QuotaMetricInfo `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// QuotaMetricInfoListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client QuotaMetricInfoListResult) QuotaMetricInfoListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// RegistryStatistics is identity registry statistics. +type RegistryStatistics struct { + autorest.Response `json:"-"` + TotalDeviceCount *int64 `json:"totalDeviceCount,omitempty"` + EnabledDeviceCount *int64 `json:"enabledDeviceCount,omitempty"` + DisabledDeviceCount *int64 `json:"disabledDeviceCount,omitempty"` +} + +// Resource is +type Resource struct { + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` +} + +// SetObject is +type SetObject struct { + autorest.Response `json:"-"` + Value *map[string]interface{} `json:"value,omitempty"` +} + +// SharedAccessSignatureAuthorizationRule is the properties of an IoT hub +// shared access policy. +type SharedAccessSignatureAuthorizationRule struct { + autorest.Response `json:"-"` + KeyName *string `json:"keyName,omitempty"` + PrimaryKey *string `json:"primaryKey,omitempty"` + SecondaryKey *string `json:"secondaryKey,omitempty"` + Rights AccessRights `json:"rights,omitempty"` +} + +// SharedAccessSignatureAuthorizationRuleListResult is the list of shared +// access policies with a next link. +type SharedAccessSignatureAuthorizationRuleListResult struct { + autorest.Response `json:"-"` + Value *[]SharedAccessSignatureAuthorizationRule `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// SharedAccessSignatureAuthorizationRuleListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client SharedAccessSignatureAuthorizationRuleListResult) SharedAccessSignatureAuthorizationRuleListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// SkuDescription is sKU properties. +type SkuDescription struct { + ResourceType *string `json:"resourceType,omitempty"` + Sku *SkuInfo `json:"sku,omitempty"` + Capacity *Capacity `json:"capacity,omitempty"` +} + +// SkuDescriptionListResult is the JSON-serialized array of +// IotHubSkuDescription objects with a next link. +type SkuDescriptionListResult struct { + autorest.Response `json:"-"` + Value *[]SkuDescription `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// SkuDescriptionListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client SkuDescriptionListResult) SkuDescriptionListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// SkuInfo is information about the SKU of the IoT hub. +type SkuInfo struct { + Name Sku `json:"name,omitempty"` + Tier SkuTier `json:"tier,omitempty"` + Capacity *int64 `json:"capacity,omitempty"` +} + +// StorageEndpointProperties is the properties of the Azure Storage endpoint +// for file upload. +type StorageEndpointProperties struct { + SasTTLAsIso8601 *string `json:"sasTtlAsIso8601,omitempty"` + ConnectionString *string `json:"connectionString,omitempty"` + ContainerName *string `json:"containerName,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go new file mode 100755 index 000000000000..83b97042999c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go @@ -0,0 +1,1577 @@ +package iothub + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// ResourceClient is the use this API to manage the IoT hubs in your +// subscription. +type ResourceClient struct { + ManagementClient +} + +// NewResourceClient creates an instance of the ResourceClient client. +func NewResourceClient(subscriptionID string) ResourceClient { + return NewResourceClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewResourceClientWithBaseURI creates an instance of the ResourceClient +// client. +func NewResourceClientWithBaseURI(baseURI string, subscriptionID string) ResourceClient { + return ResourceClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CheckNameAvailability check if an IoT hub name is available. +// +// operationInputs is set the name parameter in the OperationInputs structure +// to the name of the IoT hub to check. +func (client ResourceClient) CheckNameAvailability(operationInputs OperationInputs) (result NameAvailabilityInfo, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: operationInputs, + Constraints: []validation.Constraint{{Target: "operationInputs.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "iothub.ResourceClient", "CheckNameAvailability") + } + + req, err := client.CheckNameAvailabilityPreparer(operationInputs) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CheckNameAvailability", nil, "Failure preparing request") + return + } + + resp, err := client.CheckNameAvailabilitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CheckNameAvailability", resp, "Failure sending request") + return + } + + result, err = client.CheckNameAvailabilityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CheckNameAvailability", resp, "Failure responding to request") + } + + return +} + +// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. +func (client ResourceClient) CheckNameAvailabilityPreparer(operationInputs OperationInputs) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Devices/checkNameAvailability", pathParameters), + autorest.WithJSON(operationInputs), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always +// closes the http.Response Body. +func (client ResourceClient) CheckNameAvailabilityResponder(resp *http.Response) (result NameAvailabilityInfo, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateEventHubConsumerGroup add a consumer group to an Event Hub-compatible +// endpoint in an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the +// name of the Event Hub-compatible endpoint in the IoT hub. name is the name +// of the consumer group to add. +func (client ResourceClient) CreateEventHubConsumerGroup(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (result EventHubConsumerGroupInfo, err error) { + req, err := client.CreateEventHubConsumerGroupPreparer(resourceGroupName, resourceName, eventHubEndpointName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CreateEventHubConsumerGroup", nil, "Failure preparing request") + return + } + + resp, err := client.CreateEventHubConsumerGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CreateEventHubConsumerGroup", resp, "Failure sending request") + return + } + + result, err = client.CreateEventHubConsumerGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CreateEventHubConsumerGroup", resp, "Failure responding to request") + } + + return +} + +// CreateEventHubConsumerGroupPreparer prepares the CreateEventHubConsumerGroup request. +func (client ResourceClient) CreateEventHubConsumerGroupPreparer(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventHubEndpointName": autorest.Encode("path", eventHubEndpointName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups/{name}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// CreateEventHubConsumerGroupSender sends the CreateEventHubConsumerGroup request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) CreateEventHubConsumerGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// CreateEventHubConsumerGroupResponder handles the response to the CreateEventHubConsumerGroup request. The method always +// closes the http.Response Body. +func (client ResourceClient) CreateEventHubConsumerGroupResponder(resp *http.Response) (result EventHubConsumerGroupInfo, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdate create or update the metadata of an Iot hub. The usual +// pattern to modify a property is to retrieve the IoT hub metadata and +// security metadata, and then combine them with the modified values in a new +// body to update the IoT hub. This method may poll for completion. Polling can +// be canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub to create or update. +// iotHubDescription is the IoT hub metadata and security metadata. +func (client ResourceClient) CreateOrUpdate(resourceGroupName string, resourceName string, iotHubDescription Description, cancel <-chan struct{}) (<-chan Description, <-chan error) { + resultChan := make(chan Description, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: iotHubDescription, + Constraints: []validation.Constraint{{Target: "iotHubDescription.Subscriptionid", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "iotHubDescription.Resourcegroup", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "iotHubDescription.Properties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, + {Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}, + {Target: "iotHubDescription.Properties.CloudToDevice.Feedback", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, + {Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}, + }}, + }}, + }}, + {Target: "iotHubDescription.Sku", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "iotHubDescription.Sku.Capacity", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "iothub.ResourceClient", "CreateOrUpdate") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result Description + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, resourceName, iotHubDescription, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ResourceClient) CreateOrUpdatePreparer(resourceGroupName string, resourceName string, iotHubDescription Description, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}", pathParameters), + autorest.WithJSON(iotHubDescription), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client ResourceClient) CreateOrUpdateResponder(resp *http.Response) (result Description, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete delete an IoT hub. This method may poll for completion. Polling can +// be canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub to delete. +func (client ResourceClient) Delete(resourceGroupName string, resourceName string, cancel <-chan struct{}) (<-chan SetObject, <-chan error) { + resultChan := make(chan SetObject, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result SetObject + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, resourceName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// DeletePreparer prepares the Delete request. +func (client ResourceClient) DeletePreparer(resourceGroupName string, resourceName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ResourceClient) DeleteResponder(resp *http.Response) (result SetObject, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK, http.StatusNoContent, http.StatusNotFound), + autorest.ByUnmarshallingJSON(&result.Value), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// DeleteEventHubConsumerGroup delete a consumer group from an Event +// Hub-compatible endpoint in an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the +// name of the Event Hub-compatible endpoint in the IoT hub. name is the name +// of the consumer group to delete. +func (client ResourceClient) DeleteEventHubConsumerGroup(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (result autorest.Response, err error) { + req, err := client.DeleteEventHubConsumerGroupPreparer(resourceGroupName, resourceName, eventHubEndpointName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "DeleteEventHubConsumerGroup", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteEventHubConsumerGroupSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "DeleteEventHubConsumerGroup", resp, "Failure sending request") + return + } + + result, err = client.DeleteEventHubConsumerGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "DeleteEventHubConsumerGroup", resp, "Failure responding to request") + } + + return +} + +// DeleteEventHubConsumerGroupPreparer prepares the DeleteEventHubConsumerGroup request. +func (client ResourceClient) DeleteEventHubConsumerGroupPreparer(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventHubEndpointName": autorest.Encode("path", eventHubEndpointName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups/{name}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// DeleteEventHubConsumerGroupSender sends the DeleteEventHubConsumerGroup request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) DeleteEventHubConsumerGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// DeleteEventHubConsumerGroupResponder handles the response to the DeleteEventHubConsumerGroup request. The method always +// closes the http.Response Body. +func (client ResourceClient) DeleteEventHubConsumerGroupResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// ExportDevices exports all the device identities in the IoT hub identity +// registry to an Azure Storage blob container. For more information, see: +// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. exportDevicesParameters is the +// parameters that specify the export devices operation. +func (client ResourceClient) ExportDevices(resourceGroupName string, resourceName string, exportDevicesParameters ExportDevicesRequest) (result JobResponse, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: exportDevicesParameters, + Constraints: []validation.Constraint{{Target: "exportDevicesParameters.ExportBlobContainerURI", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "exportDevicesParameters.ExcludeKeys", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "iothub.ResourceClient", "ExportDevices") + } + + req, err := client.ExportDevicesPreparer(resourceGroupName, resourceName, exportDevicesParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ExportDevices", nil, "Failure preparing request") + return + } + + resp, err := client.ExportDevicesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ExportDevices", resp, "Failure sending request") + return + } + + result, err = client.ExportDevicesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ExportDevices", resp, "Failure responding to request") + } + + return +} + +// ExportDevicesPreparer prepares the ExportDevices request. +func (client ResourceClient) ExportDevicesPreparer(resourceGroupName string, resourceName string, exportDevicesParameters ExportDevicesRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/exportDevices", pathParameters), + autorest.WithJSON(exportDevicesParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ExportDevicesSender sends the ExportDevices request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) ExportDevicesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ExportDevicesResponder handles the response to the ExportDevices request. The method always +// closes the http.Response Body. +func (client ResourceClient) ExportDevicesResponder(resp *http.Response) (result JobResponse, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Get get the non-security related metadata of an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. +func (client ResourceClient) Get(resourceGroupName string, resourceName string) (result Description, err error) { + req, err := client.GetPreparer(resourceGroupName, resourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ResourceClient) GetPreparer(resourceGroupName string, resourceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ResourceClient) GetResponder(resp *http.Response) (result Description, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetEventHubConsumerGroup get a consumer group from the Event Hub-compatible +// device-to-cloud endpoint for an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the +// name of the Event Hub-compatible endpoint in the IoT hub. name is the name +// of the consumer group to retrieve. +func (client ResourceClient) GetEventHubConsumerGroup(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (result EventHubConsumerGroupInfo, err error) { + req, err := client.GetEventHubConsumerGroupPreparer(resourceGroupName, resourceName, eventHubEndpointName, name) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetEventHubConsumerGroup", nil, "Failure preparing request") + return + } + + resp, err := client.GetEventHubConsumerGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetEventHubConsumerGroup", resp, "Failure sending request") + return + } + + result, err = client.GetEventHubConsumerGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetEventHubConsumerGroup", resp, "Failure responding to request") + } + + return +} + +// GetEventHubConsumerGroupPreparer prepares the GetEventHubConsumerGroup request. +func (client ResourceClient) GetEventHubConsumerGroupPreparer(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventHubEndpointName": autorest.Encode("path", eventHubEndpointName), + "name": autorest.Encode("path", name), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups/{name}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetEventHubConsumerGroupSender sends the GetEventHubConsumerGroup request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) GetEventHubConsumerGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetEventHubConsumerGroupResponder handles the response to the GetEventHubConsumerGroup request. The method always +// closes the http.Response Body. +func (client ResourceClient) GetEventHubConsumerGroupResponder(resp *http.Response) (result EventHubConsumerGroupInfo, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetJob get the details of a job from an IoT hub. For more information, see: +// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. jobID is the job identifier. +func (client ResourceClient) GetJob(resourceGroupName string, resourceName string, jobID string) (result JobResponse, err error) { + req, err := client.GetJobPreparer(resourceGroupName, resourceName, jobID) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetJob", nil, "Failure preparing request") + return + } + + resp, err := client.GetJobSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetJob", resp, "Failure sending request") + return + } + + result, err = client.GetJobResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetJob", resp, "Failure responding to request") + } + + return +} + +// GetJobPreparer prepares the GetJob request. +func (client ResourceClient) GetJobPreparer(resourceGroupName string, resourceName string, jobID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "jobId": autorest.Encode("path", jobID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/jobs/{jobId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetJobSender sends the GetJob request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) GetJobSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetJobResponder handles the response to the GetJob request. The method always +// closes the http.Response Body. +func (client ResourceClient) GetJobResponder(resp *http.Response) (result JobResponse, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetKeysForKeyName get a shared access policy by name from an IoT hub. For +// more information, see: +// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. keyName is the name of the +// shared access policy. +func (client ResourceClient) GetKeysForKeyName(resourceGroupName string, resourceName string, keyName string) (result SharedAccessSignatureAuthorizationRule, err error) { + req, err := client.GetKeysForKeyNamePreparer(resourceGroupName, resourceName, keyName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetKeysForKeyName", nil, "Failure preparing request") + return + } + + resp, err := client.GetKeysForKeyNameSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetKeysForKeyName", resp, "Failure sending request") + return + } + + result, err = client.GetKeysForKeyNameResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetKeysForKeyName", resp, "Failure responding to request") + } + + return +} + +// GetKeysForKeyNamePreparer prepares the GetKeysForKeyName request. +func (client ResourceClient) GetKeysForKeyNamePreparer(resourceGroupName string, resourceName string, keyName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "keyName": autorest.Encode("path", keyName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/IotHubKeys/{keyName}/listkeys", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetKeysForKeyNameSender sends the GetKeysForKeyName request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) GetKeysForKeyNameSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetKeysForKeyNameResponder handles the response to the GetKeysForKeyName request. The method always +// closes the http.Response Body. +func (client ResourceClient) GetKeysForKeyNameResponder(resp *http.Response) (result SharedAccessSignatureAuthorizationRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetQuotaMetrics get the quota metrics for an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. +func (client ResourceClient) GetQuotaMetrics(resourceGroupName string, resourceName string) (result QuotaMetricInfoListResult, err error) { + req, err := client.GetQuotaMetricsPreparer(resourceGroupName, resourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetQuotaMetrics", nil, "Failure preparing request") + return + } + + resp, err := client.GetQuotaMetricsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetQuotaMetrics", resp, "Failure sending request") + return + } + + result, err = client.GetQuotaMetricsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetQuotaMetrics", resp, "Failure responding to request") + } + + return +} + +// GetQuotaMetricsPreparer prepares the GetQuotaMetrics request. +func (client ResourceClient) GetQuotaMetricsPreparer(resourceGroupName string, resourceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/quotaMetrics", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetQuotaMetricsSender sends the GetQuotaMetrics request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) GetQuotaMetricsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetQuotaMetricsResponder handles the response to the GetQuotaMetrics request. The method always +// closes the http.Response Body. +func (client ResourceClient) GetQuotaMetricsResponder(resp *http.Response) (result QuotaMetricInfoListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetQuotaMetricsNextResults retrieves the next set of results, if any. +func (client ResourceClient) GetQuotaMetricsNextResults(lastResults QuotaMetricInfoListResult) (result QuotaMetricInfoListResult, err error) { + req, err := lastResults.QuotaMetricInfoListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetQuotaMetrics", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.GetQuotaMetricsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetQuotaMetrics", resp, "Failure sending next results request") + } + + result, err = client.GetQuotaMetricsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetQuotaMetrics", resp, "Failure responding to next results request") + } + + return +} + +// GetStats get the statistics from an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. +func (client ResourceClient) GetStats(resourceGroupName string, resourceName string) (result RegistryStatistics, err error) { + req, err := client.GetStatsPreparer(resourceGroupName, resourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetStats", nil, "Failure preparing request") + return + } + + resp, err := client.GetStatsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetStats", resp, "Failure sending request") + return + } + + result, err = client.GetStatsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetStats", resp, "Failure responding to request") + } + + return +} + +// GetStatsPreparer prepares the GetStats request. +func (client ResourceClient) GetStatsPreparer(resourceGroupName string, resourceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/IotHubStats", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetStatsSender sends the GetStats request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) GetStatsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetStatsResponder handles the response to the GetStats request. The method always +// closes the http.Response Body. +func (client ResourceClient) GetStatsResponder(resp *http.Response) (result RegistryStatistics, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetValidSkus get the list of valid SKUs for an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. +func (client ResourceClient) GetValidSkus(resourceGroupName string, resourceName string) (result SkuDescriptionListResult, err error) { + req, err := client.GetValidSkusPreparer(resourceGroupName, resourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetValidSkus", nil, "Failure preparing request") + return + } + + resp, err := client.GetValidSkusSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetValidSkus", resp, "Failure sending request") + return + } + + result, err = client.GetValidSkusResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetValidSkus", resp, "Failure responding to request") + } + + return +} + +// GetValidSkusPreparer prepares the GetValidSkus request. +func (client ResourceClient) GetValidSkusPreparer(resourceGroupName string, resourceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/skus", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetValidSkusSender sends the GetValidSkus request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) GetValidSkusSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetValidSkusResponder handles the response to the GetValidSkus request. The method always +// closes the http.Response Body. +func (client ResourceClient) GetValidSkusResponder(resp *http.Response) (result SkuDescriptionListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetValidSkusNextResults retrieves the next set of results, if any. +func (client ResourceClient) GetValidSkusNextResults(lastResults SkuDescriptionListResult) (result SkuDescriptionListResult, err error) { + req, err := lastResults.SkuDescriptionListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetValidSkus", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.GetValidSkusSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetValidSkus", resp, "Failure sending next results request") + } + + result, err = client.GetValidSkusResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "GetValidSkus", resp, "Failure responding to next results request") + } + + return +} + +// ImportDevices import, update, or delete device identities in the IoT hub +// identity registry from a blob. For more information, see: +// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. importDevicesParameters is the +// parameters that specify the import devices operation. +func (client ResourceClient) ImportDevices(resourceGroupName string, resourceName string, importDevicesParameters ImportDevicesRequest) (result JobResponse, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: importDevicesParameters, + Constraints: []validation.Constraint{{Target: "importDevicesParameters.InputBlobContainerURI", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "importDevicesParameters.OutputBlobContainerURI", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "iothub.ResourceClient", "ImportDevices") + } + + req, err := client.ImportDevicesPreparer(resourceGroupName, resourceName, importDevicesParameters) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ImportDevices", nil, "Failure preparing request") + return + } + + resp, err := client.ImportDevicesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ImportDevices", resp, "Failure sending request") + return + } + + result, err = client.ImportDevicesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ImportDevices", resp, "Failure responding to request") + } + + return +} + +// ImportDevicesPreparer prepares the ImportDevices request. +func (client ResourceClient) ImportDevicesPreparer(resourceGroupName string, resourceName string, importDevicesParameters ImportDevicesRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/importDevices", pathParameters), + autorest.WithJSON(importDevicesParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ImportDevicesSender sends the ImportDevices request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) ImportDevicesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ImportDevicesResponder handles the response to the ImportDevices request. The method always +// closes the http.Response Body. +func (client ResourceClient) ImportDevicesResponder(resp *http.Response) (result JobResponse, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroup get all the IoT hubs in a resource group. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hubs. +func (client ResourceClient) ListByResourceGroup(resourceGroupName string) (result DescriptionListResult, err error) { + req, err := client.ListByResourceGroupPreparer(resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client ResourceClient) ListByResourceGroupPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client ResourceClient) ListByResourceGroupResponder(resp *http.Response) (result DescriptionListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroupNextResults retrieves the next set of results, if any. +func (client ResourceClient) ListByResourceGroupNextResults(lastResults DescriptionListResult) (result DescriptionListResult, err error) { + req, err := lastResults.DescriptionListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListByResourceGroup", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListByResourceGroup", resp, "Failure sending next results request") + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListByResourceGroup", resp, "Failure responding to next results request") + } + + return +} + +// ListBySubscription get all the IoT hubs in a subscription. +func (client ResourceClient) ListBySubscription() (result DescriptionListResult, err error) { + req, err := client.ListBySubscriptionPreparer() + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListBySubscription", nil, "Failure preparing request") + return + } + + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListBySubscription", resp, "Failure sending request") + return + } + + result, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListBySubscription", resp, "Failure responding to request") + } + + return +} + +// ListBySubscriptionPreparer prepares the ListBySubscription request. +func (client ResourceClient) ListBySubscriptionPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Devices/IotHubs", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListBySubscriptionSender sends the ListBySubscription request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always +// closes the http.Response Body. +func (client ResourceClient) ListBySubscriptionResponder(resp *http.Response) (result DescriptionListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListBySubscriptionNextResults retrieves the next set of results, if any. +func (client ResourceClient) ListBySubscriptionNextResults(lastResults DescriptionListResult) (result DescriptionListResult, err error) { + req, err := lastResults.DescriptionListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListBySubscription", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListBySubscriptionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListBySubscription", resp, "Failure sending next results request") + } + + result, err = client.ListBySubscriptionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListBySubscription", resp, "Failure responding to next results request") + } + + return +} + +// ListEventHubConsumerGroups get a list of the consumer groups in the Event +// Hub-compatible device-to-cloud endpoint in an IoT hub. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the +// name of the Event Hub-compatible endpoint. +func (client ResourceClient) ListEventHubConsumerGroups(resourceGroupName string, resourceName string, eventHubEndpointName string) (result EventHubConsumerGroupsListResult, err error) { + req, err := client.ListEventHubConsumerGroupsPreparer(resourceGroupName, resourceName, eventHubEndpointName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListEventHubConsumerGroups", nil, "Failure preparing request") + return + } + + resp, err := client.ListEventHubConsumerGroupsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListEventHubConsumerGroups", resp, "Failure sending request") + return + } + + result, err = client.ListEventHubConsumerGroupsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListEventHubConsumerGroups", resp, "Failure responding to request") + } + + return +} + +// ListEventHubConsumerGroupsPreparer prepares the ListEventHubConsumerGroups request. +func (client ResourceClient) ListEventHubConsumerGroupsPreparer(resourceGroupName string, resourceName string, eventHubEndpointName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "eventHubEndpointName": autorest.Encode("path", eventHubEndpointName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/eventHubEndpoints/{eventHubEndpointName}/ConsumerGroups", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListEventHubConsumerGroupsSender sends the ListEventHubConsumerGroups request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) ListEventHubConsumerGroupsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListEventHubConsumerGroupsResponder handles the response to the ListEventHubConsumerGroups request. The method always +// closes the http.Response Body. +func (client ResourceClient) ListEventHubConsumerGroupsResponder(resp *http.Response) (result EventHubConsumerGroupsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListEventHubConsumerGroupsNextResults retrieves the next set of results, if any. +func (client ResourceClient) ListEventHubConsumerGroupsNextResults(lastResults EventHubConsumerGroupsListResult) (result EventHubConsumerGroupsListResult, err error) { + req, err := lastResults.EventHubConsumerGroupsListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListEventHubConsumerGroups", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListEventHubConsumerGroupsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListEventHubConsumerGroups", resp, "Failure sending next results request") + } + + result, err = client.ListEventHubConsumerGroupsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListEventHubConsumerGroups", resp, "Failure responding to next results request") + } + + return +} + +// ListJobs get a list of all the jobs in an IoT hub. For more information, +// see: +// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. +func (client ResourceClient) ListJobs(resourceGroupName string, resourceName string) (result JobResponseListResult, err error) { + req, err := client.ListJobsPreparer(resourceGroupName, resourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListJobs", nil, "Failure preparing request") + return + } + + resp, err := client.ListJobsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListJobs", resp, "Failure sending request") + return + } + + result, err = client.ListJobsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListJobs", resp, "Failure responding to request") + } + + return +} + +// ListJobsPreparer prepares the ListJobs request. +func (client ResourceClient) ListJobsPreparer(resourceGroupName string, resourceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/jobs", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListJobsSender sends the ListJobs request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) ListJobsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListJobsResponder handles the response to the ListJobs request. The method always +// closes the http.Response Body. +func (client ResourceClient) ListJobsResponder(resp *http.Response) (result JobResponseListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListJobsNextResults retrieves the next set of results, if any. +func (client ResourceClient) ListJobsNextResults(lastResults JobResponseListResult) (result JobResponseListResult, err error) { + req, err := lastResults.JobResponseListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListJobs", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListJobsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListJobs", resp, "Failure sending next results request") + } + + result, err = client.ListJobsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListJobs", resp, "Failure responding to next results request") + } + + return +} + +// ListKeys get the security metadata for an IoT hub. For more information, +// see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. +// +// resourceGroupName is the name of the resource group that contains the IoT +// hub. resourceName is the name of the IoT hub. +func (client ResourceClient) ListKeys(resourceGroupName string, resourceName string) (result SharedAccessSignatureAuthorizationRuleListResult, err error) { + req, err := client.ListKeysPreparer(resourceGroupName, resourceName) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListKeys", nil, "Failure preparing request") + return + } + + resp, err := client.ListKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListKeys", resp, "Failure sending request") + return + } + + result, err = client.ListKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListKeys", resp, "Failure responding to request") + } + + return +} + +// ListKeysPreparer prepares the ListKeys request. +func (client ResourceClient) ListKeysPreparer(resourceGroupName string, resourceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "resourceName": autorest.Encode("path", resourceName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-02-03" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/listkeys", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListKeysSender sends the ListKeys request. The method will close the +// http.Response Body if it receives an error. +func (client ResourceClient) ListKeysSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListKeysResponder handles the response to the ListKeys request. The method always +// closes the http.Response Body. +func (client ResourceClient) ListKeysResponder(resp *http.Response) (result SharedAccessSignatureAuthorizationRuleListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListKeysNextResults retrieves the next set of results, if any. +func (client ResourceClient) ListKeysNextResults(lastResults SharedAccessSignatureAuthorizationRuleListResult) (result SharedAccessSignatureAuthorizationRuleListResult, err error) { + req, err := lastResults.SharedAccessSignatureAuthorizationRuleListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListKeys", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListKeys", resp, "Failure sending next results request") + } + + result, err = client.ListKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.ResourceClient", "ListKeys", resp, "Failure responding to next results request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go new file mode 100755 index 000000000000..d33d9dd5ad26 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go @@ -0,0 +1,28 @@ +package iothub + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0 +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +// UserAgent returns the UserAgent string to use when sending http.Requests. +func UserAgent() string { + return "Azure-SDK-For-Go/v10.3.0-beta arm-iothub/2017-07-01" +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return "v10.3.0-beta" +} diff --git a/vendor/vendor.json b/vendor/vendor.json index c713a5e3d24f..52115e9ca680 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -115,7 +115,19 @@ "versionExact": "v11.1.0-beta" }, { +<<<<<<< HEAD "checksumSHA1": "ALyRCjT78W2bC4r8R/wexKF8ASQ=", +||||||| merged common ancestors + "checksumSHA1": "FloEh78hgEozkpt0y4SPWK23/wI=", +======= + "checksumSHA1": "wSLOrUgDpf9pmtZKl2KO3OavrZU=", + "path": "github.com/Azure/azure-sdk-for-go/arm/iothub", + "revision": "dedad7d55bef3a5fd61d3b682bcba0a93cf315e8", + "revisionTime": "2017-08-24T19:57:27Z" + }, + { + "checksumSHA1": "FloEh78hgEozkpt0y4SPWK23/wI=", +>>>>>>> added iothub dependency "path": "github.com/Azure/azure-sdk-for-go/arm/keyvault", "revision": "80f6cbcb1d6295ebb8fbeb5afab826a94aa67d11", "revisionTime": "2017-10-06T17:43:09Z", From 3d76c7a19b262aa3712f036857d7e953c428ade8 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 00:37:12 +0530 Subject: [PATCH 19/69] added the config and cleaned up the schema iothub resource schema --- azurerm/config.go | 17 +++++ .../resource_arm_iothub_resource_provider.go | 75 +++++++++++++++++++ 2 files changed, 92 insertions(+) diff --git a/azurerm/config.go b/azurerm/config.go index a9a5096d0708..1001dcad19ff 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -7,6 +7,8 @@ import ( "net/http" "net/http/httputil" + "github.com/Azure/azure-sdk-for-go/arm/iothub" + "github.com/Azure/azure-sdk-for-go/arm/appinsights" "github.com/Azure/azure-sdk-for-go/arm/authorization" "github.com/Azure/azure-sdk-for-go/arm/automation" @@ -157,6 +159,7 @@ type ArmClient struct { sqlElasticPoolsClient sql.ElasticPoolsClient sqlFirewallRulesClient sql.FirewallRulesClient sqlServersClient sql.ServersClient + iothubResourceClient iothub.ResourceClient } func withRequestLogging() autorest.SendDecorator { @@ -649,7 +652,21 @@ func (c *Config) getArmClient() (*ArmClient, error) { aschc.Sender = sender client.automationScheduleClient = aschc +<<<<<<< HEAD client.registerAuthentication(endpoint, graphEndpoint, c.SubscriptionID, c.TenantID, auth, graphAuth, sender) +||||||| merged common ancestors + client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) + +======= + ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) + setUserAgent(&ihrc.Client) + ihrc.Authorizer = auth + ihrc.Sender = sender + client.iothubResourceClient = ihrc + + client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) + +>>>>>>> added the config and cleaned up the schema iothub resource schema client.registerDatabases(endpoint, c.SubscriptionID, auth, sender) client.registerDisks(endpoint, c.SubscriptionID, auth, sender) client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index e69de29bb2d1..fb7963da889d 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -0,0 +1,75 @@ +package azurerm + +import ( + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmIothub() *schema.Resource { + return &schema.Resource{ + Create: resourceArmIothubCreate, + Read: resourceArmIothubRead, + Update: resourceArmIothubUpdate, + Delete: resourceArmIothubDelete, + + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + }, + + "name": { + Type: schema.TypeString, + }, + + "type": { + Type: schema.TypeString, + }, + + "location": { + Type: schema.TypeString, + }, + + "subscriptionid": { + Type: schema.TypeString, + }, + + "resourcegroup": { + Type: schema.TypeString, + }, + + "etag": { + Type: schema.TypeString, + }, + + "skuinfo": { + Type: schema.TypeList, + MaxItems: 1, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + }, + + "tier": { + Type: schema.TypeString, + }, + + "capacity": { + Type: schema.TypeInt, + }, + }, + }, + }, + }, + } + +} +func resourceArmIothubCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + iotHubCreateClient := client.iothubResourceClient + resGroup := d.Get("resourceGroupName").(string) + resName := d.Get("resourceName").(string) + + return nil + +} From 1ebedec1acb03bf3e78d86fcb004e8c52d94a495 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 01:38:11 +0530 Subject: [PATCH 20/69] added validation and params in the schemas --- .../resource_arm_iothub_resource_provider.go | 60 ++++++++++++++----- 1 file changed, 45 insertions(+), 15 deletions(-) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index fb7963da889d..9a63ef3b29aa 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -1,7 +1,9 @@ package azurerm import ( + "github.com/Azure/azure-sdk-for-go/arm/iothub" "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" ) func resourceArmIothub() *schema.Resource { @@ -13,31 +15,38 @@ func resourceArmIothub() *schema.Resource { Schema: map[string]*schema.Schema{ "id": { - Type: schema.TypeString, + Type: schema.TypeString, + Computed: true, }, - "name": { - Type: schema.TypeString, + Type: schema.TypeString, + Required: true, }, "type": { - Type: schema.TypeString, + Type: schema.TypeString, + Computed: true, }, "location": { - Type: schema.TypeString, + Type: schema.TypeString, + Required: true, }, - "subscriptionid": { - Type: schema.TypeString, + "subscription_id": { + Type: schema.TypeString, + Required: true, }, - "resourcegroup": { - Type: schema.TypeString, + "resource_group": { + Type: schema.TypeString, + Required: true, }, "etag": { - Type: schema.TypeString, + Type: schema.TypeString, + Optional: true, + Computed: true, }, "skuinfo": { @@ -48,14 +57,25 @@ func resourceArmIothub() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, + ValidateFunc: validation.StringInSlice([]string{ + string(iothub.F1), + string(iothub.S1), + string(iothub.S2), + string(iothub.S3), + }, true), }, "tier": { Type: schema.TypeString, + ValidateFunc: validation.StringInSlice([]string{ + string(iothub.Free), + string(iothub.Standard), + }, true), }, "capacity": { - Type: schema.TypeInt, + Type: schema.TypeInt, + ValidateFunc: validation.IntAtLeast(1), }, }, }, @@ -65,11 +85,21 @@ func resourceArmIothub() *schema.Resource { } func resourceArmIothubCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - iotHubCreateClient := client.iothubResourceClient - resGroup := d.Get("resourceGroupName").(string) - resName := d.Get("resourceName").(string) return nil } + +func resourceArmIothubRead(d *schema.ResourceData, meta interface{}) error { + + return nil +} + +func resourceArmIothubUpdate(d *schema.ResourceData, meta interface{}) error { + + return nil +} + +func resourceArmIothubDelete(d *schema.ResourceData, meta interface{}) error { + return nil +} From 838271c365203ac82639a960961413a9331006f8 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 02:10:12 +0530 Subject: [PATCH 21/69] added minimal creation method --- .../resource_arm_iothub_resource_provider.go | 63 +++++++++++++++---- 1 file changed, 51 insertions(+), 12 deletions(-) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 9a63ef3b29aa..53f61a2e4b45 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -28,20 +28,14 @@ func resourceArmIothub() *schema.Resource { Computed: true, }, - "location": { - Type: schema.TypeString, - Required: true, - }, + "location": locationSchema(), "subscription_id": { Type: schema.TypeString, Required: true, }, - "resource_group": { - Type: schema.TypeString, - Required: true, - }, + "resource_group_name": resourceGroupNameSchema(), "etag": { Type: schema.TypeString, @@ -49,14 +43,17 @@ func resourceArmIothub() *schema.Resource { Computed: true, }, - "skuinfo": { + "tags": tagsSchema(), + + "sku": { Type: schema.TypeList, MaxItems: 1, Required: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, + Type: schema.TypeString, + Required: true, ValidateFunc: validation.StringInSlice([]string{ string(iothub.F1), string(iothub.S1), @@ -66,7 +63,8 @@ func resourceArmIothub() *schema.Resource { }, "tier": { - Type: schema.TypeString, + Type: schema.TypeString, + Required: true, ValidateFunc: validation.StringInSlice([]string{ string(iothub.Free), string(iothub.Standard), @@ -75,6 +73,7 @@ func resourceArmIothub() *schema.Resource { "capacity": { Type: schema.TypeInt, + Required: true, ValidateFunc: validation.IntAtLeast(1), }, }, @@ -86,7 +85,47 @@ func resourceArmIothub() *schema.Resource { } func resourceArmIothubCreate(d *schema.ResourceData, meta interface{}) error { - return nil + armClient := meta.(*ArmClient) + iothubClient := armClient.iothubResourceClient + + rg := d.Get("resource_group").(string) + name := d.Get("name").(string) + location := d.Get("location").(string) + subscriptionId := d.Get("subscription_id").(string) + skuInfo := expandAzureRmIotHubSku(d) + + desc := iothub.Description{ + Name: &name, + Location: &location, + Subscriptionid: &subscriptionId, + Sku: &skuInfo, + } + + cancel := make(chan struct{}) + + RespChan, errChan := iothubClient.CreateOrUpdate(rg, name, desc, cancel) + resp := <-RespChan + err := <-errChan + + if err != nil { + return err + } + + d.SetId(*resp.ID) + return resourceArmIothubRead(d, meta) + +} + +func expandAzureRmIotHubSku(d *schema.ResourceData) iothub.SkuInfo { + skuList := d.Get("sku").([]interface{}) + skuMap := skuList[0].(map[string]interface{}) + cap := int64(skuMap["capacity"].(int)) + + return iothub.SkuInfo{ + Name: iothub.Sku(skuMap["name"].(string)), + Tier: iothub.SkuTier(skuMap["tier"].(string)), + Capacity: &cap, + } } From f378215de61c7f102fb7ba80b7f9b91c7423c171 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 02:19:52 +0530 Subject: [PATCH 22/69] added resource to the provider list --- azurerm/provider.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/azurerm/provider.go b/azurerm/provider.go index c159bc32029f..63e4d7695829 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -169,6 +169,7 @@ func Provider() terraform.ResourceProvider { "azurerm_virtual_machine_scale_set": resourceArmVirtualMachineScaleSet(), "azurerm_virtual_network": resourceArmVirtualNetwork(), "azurerm_virtual_network_peering": resourceArmVirtualNetworkPeering(), + "azurerm_iothub": resourceArmIothub(), }, } @@ -426,6 +427,7 @@ func determineAzureResourceProvidersToRegister(providerList []resources.Provider "Microsoft.ServiceBus": {}, "Microsoft.Sql": {}, "Microsoft.Storage": {}, + "Microsoft.Devices": {}, } // filter out any providers already registered From 77c92ff9e4fedfc9a6afe5b486b906d53547dc57 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 02:51:54 +0530 Subject: [PATCH 23/69] cleaned up the schema a bit and added read --- .../resource_arm_iothub_resource_provider.go | 37 +++++++++++++------ 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 53f61a2e4b45..34320b67bad7 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -14,15 +14,13 @@ func resourceArmIothub() *schema.Resource { Delete: resourceArmIothubDelete, Schema: map[string]*schema.Schema{ - "id": { - Type: schema.TypeString, - Computed: true, - }, "name": { Type: schema.TypeString, Required: true, + ForceNew: true, }, + // TODO: is this needed "type": { Type: schema.TypeString, Computed: true, @@ -30,11 +28,6 @@ func resourceArmIothub() *schema.Resource { "location": locationSchema(), - "subscription_id": { - Type: schema.TypeString, - Required: true, - }, - "resource_group_name": resourceGroupNameSchema(), "etag": { @@ -91,16 +84,22 @@ func resourceArmIothubCreate(d *schema.ResourceData, meta interface{}) error { rg := d.Get("resource_group").(string) name := d.Get("name").(string) location := d.Get("location").(string) - subscriptionId := d.Get("subscription_id").(string) + subscriptionID := armClient.subscriptionId skuInfo := expandAzureRmIotHubSku(d) desc := iothub.Description{ + Resourcegroup: &rg, Name: &name, Location: &location, - Subscriptionid: &subscriptionId, + Subscriptionid: &subscriptionID, Sku: &skuInfo, } + if etagI, ok := d.GetOk("etag"); ok { + etag := etagI.(string) + desc.Etag = &etag + } + cancel := make(chan struct{}) RespChan, errChan := iothubClient.CreateOrUpdate(rg, name, desc, cancel) @@ -131,6 +130,22 @@ func expandAzureRmIotHubSku(d *schema.ResourceData) iothub.SkuInfo { func resourceArmIothubRead(d *schema.ResourceData, meta interface{}) error { + id, err := parseAzureResourceID(d.Id()) + + if err != nil { + return err + } + + armClient := meta.(*ArmClient) + iothubClient := armClient.iothubResourceClient + desc, err := iothubClient.Get(id.ResourceGroup, id.Path["IotHubs"]) + if err != nil { + return err + } + + d.Set("etag", *desc.Etag) + d.Set("type", *desc.Type) + return nil } From 14aaec9ca806a9aa60d0375591ed3ca1c042898b Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 12:04:07 +0530 Subject: [PATCH 24/69] working read and create method on iothub resource --- azurerm/config.go | 2 +- azurerm/resource_arm_iothub_resource_provider.go | 12 ++++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/azurerm/config.go b/azurerm/config.go index 1001dcad19ff..54c77c37838d 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -661,7 +661,7 @@ func (c *Config) getArmClient() (*ArmClient, error) { ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) setUserAgent(&ihrc.Client) ihrc.Authorizer = auth - ihrc.Sender = sender + ihrc.Sender = autorest.CreateSender(withRequestLogging()) client.iothubResourceClient = ihrc client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 34320b67bad7..1525028cf6d0 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -81,7 +81,7 @@ func resourceArmIothubCreate(d *schema.ResourceData, meta interface{}) error { armClient := meta.(*ArmClient) iothubClient := armClient.iothubResourceClient - rg := d.Get("resource_group").(string) + rg := d.Get("resource_group_name").(string) name := d.Get("name").(string) location := d.Get("location").(string) subscriptionID := armClient.subscriptionId @@ -102,15 +102,19 @@ func resourceArmIothubCreate(d *schema.ResourceData, meta interface{}) error { cancel := make(chan struct{}) - RespChan, errChan := iothubClient.CreateOrUpdate(rg, name, desc, cancel) - resp := <-RespChan + _, errChan := iothubClient.CreateOrUpdate(rg, name, desc, cancel) err := <-errChan if err != nil { return err } - d.SetId(*resp.ID) + desc, err = iothubClient.Get(rg, name) + if err != nil { + return err + } + + d.SetId(*desc.ID) return resourceArmIothubRead(d, meta) } From ff6e44d3a81505df08c7d30bcef291eb43a03753 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 14:33:38 +0530 Subject: [PATCH 25/69] added lifecycle methods for iothub --- .../resource_arm_iothub_resource_provider.go | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 1525028cf6d0..75db0b99b351 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -8,12 +8,13 @@ import ( func resourceArmIothub() *schema.Resource { return &schema.Resource{ - Create: resourceArmIothubCreate, + Create: resourceArmIothubCreateAndUpdate, Read: resourceArmIothubRead, - Update: resourceArmIothubUpdate, + Update: resourceArmIothubCreateAndUpdate, Delete: resourceArmIothubDelete, Schema: map[string]*schema.Schema{ + // TODO: use nameAvailabilityInfo for validation "name": { Type: schema.TypeString, Required: true, @@ -76,7 +77,7 @@ func resourceArmIothub() *schema.Resource { } } -func resourceArmIothubCreate(d *schema.ResourceData, meta interface{}) error { +func resourceArmIothubCreateAndUpdate(d *schema.ResourceData, meta interface{}) error { armClient := meta.(*ArmClient) iothubClient := armClient.iothubResourceClient @@ -153,11 +154,18 @@ func resourceArmIothubRead(d *schema.ResourceData, meta interface{}) error { return nil } -func resourceArmIothubUpdate(d *schema.ResourceData, meta interface{}) error { +func resourceArmIothubDelete(d *schema.ResourceData, meta interface{}) error { - return nil -} + id, err := parseAzureResourceID(d.Id()) -func resourceArmIothubDelete(d *schema.ResourceData, meta interface{}) error { - return nil + if err != nil { + return err + } + + armClient := meta.(*ArmClient) + iothubClient := armClient.iothubResourceClient + + _, errChan := iothubClient.Delete(id.ResourceGroup, id.Path["IotHubs"], make(chan struct{})) + err = <-errChan + return err } From c7d4aab3ab0bcbda0fd117e2bf6e6ec2d6022c1c Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 15:22:39 +0530 Subject: [PATCH 26/69] added tags --- azurerm/resource_arm_iothub_resource_provider.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 75db0b99b351..3a9ec2258f68 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -85,6 +85,7 @@ func resourceArmIothubCreateAndUpdate(d *schema.ResourceData, meta interface{}) rg := d.Get("resource_group_name").(string) name := d.Get("name").(string) location := d.Get("location").(string) + subscriptionID := armClient.subscriptionId skuInfo := expandAzureRmIotHubSku(d) @@ -96,6 +97,11 @@ func resourceArmIothubCreateAndUpdate(d *schema.ResourceData, meta interface{}) Sku: &skuInfo, } + if tagsI, ok := d.GetOk("tags"); ok { + tags := tagsI.(map[string]interface{}) + desc.Tags = expandTags(tags) + } + if etagI, ok := d.GetOk("etag"); ok { etag := etagI.(string) desc.Etag = &etag From 9b6a7dc568d5a021ec734c909e46199d8b616f45 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 16:59:40 +0530 Subject: [PATCH 27/69] basic integration tests added --- .../resource_arm_iothub_resource_provider.go | 1 + ...ource_arm_iothub_resource_provider_test.go | 105 ++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 azurerm/resource_arm_iothub_resource_provider_test.go diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 3a9ec2258f68..9883dd58f090 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -156,6 +156,7 @@ func resourceArmIothubRead(d *schema.ResourceData, meta interface{}) error { d.Set("etag", *desc.Etag) d.Set("type", *desc.Type) + flattenAndSetTags(d, desc.Tags) return nil } diff --git a/azurerm/resource_arm_iothub_resource_provider_test.go b/azurerm/resource_arm_iothub_resource_provider_test.go new file mode 100644 index 000000000000..7ca841d96b31 --- /dev/null +++ b/azurerm/resource_arm_iothub_resource_provider_test.go @@ -0,0 +1,105 @@ +package azurerm + +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +const TestResourceGroup = "girishsandbox" + +func TestAccAzureRMIotHub_basicStandard(t *testing.T) { + name := acctest.RandString(6) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMIothubDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMIotHub_basicStandard(name, TestResourceGroup, testLocation()), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMIothubExists("azurerm_iothub.test"), + ), + }, + }, + }) + +} + +func testCheckAzureRMIothubDestroy(s *terraform.State) error { + + conn := testAccProvider.Meta().(*ArmClient).expressRouteCircuitClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_iothub" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(resourceGroup, name) + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Iothub still exists:\n%#v", resp.ExpressRouteCircuitPropertiesFormat) + } + } + return nil +} +func testCheckAzureRMIothubExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + iothubName := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for IotHub: %s", iothubName) + } + + conn := testAccProvider.Meta().(*ArmClient).iothubResourceClient + + resp, err := conn.Get(resourceGroup, iothubName) + + if err != nil { + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: IotHub %q (resource group: %q) does not exist", iothubName, resourceGroup) + } + + return fmt.Errorf("Bad: Get on iothubResourceClient: %+v", err) + } + + return nil + + } +} + +func testAccAzureRMIotHub_basicStandard(name, rg, location string) string { + return fmt.Sprintf(` + resource "azurerm_iothub" "test" { + name = "%s" + resource_group_name = "%s" + location = "%s" + sku { + name = "S1" + tier = "Standard" + capacity = "1" + } + + tags { + "purpose" = "testing" + } + } + + + `, name, rg, location) +} From 93c67b34c8965b1514e015d76a22c5180588ebb6 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Fri, 29 Sep 2017 17:30:19 +0530 Subject: [PATCH 28/69] Added validations for the name and followed naming convention --- azurerm/provider.go | 2 +- .../resource_arm_iothub_resource_provider.go | 38 +++++++++++++------ ...ource_arm_iothub_resource_provider_test.go | 11 +++--- 3 files changed, 33 insertions(+), 18 deletions(-) diff --git a/azurerm/provider.go b/azurerm/provider.go index 63e4d7695829..e0e019ba609b 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -169,7 +169,7 @@ func Provider() terraform.ResourceProvider { "azurerm_virtual_machine_scale_set": resourceArmVirtualMachineScaleSet(), "azurerm_virtual_network": resourceArmVirtualNetwork(), "azurerm_virtual_network_peering": resourceArmVirtualNetworkPeering(), - "azurerm_iothub": resourceArmIothub(), + "azurerm_iothub": resourceArmIotHub(), }, } diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 9883dd58f090..bacf410b0223 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -1,27 +1,27 @@ package azurerm import ( + "errors" + "github.com/Azure/azure-sdk-for-go/arm/iothub" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" ) -func resourceArmIothub() *schema.Resource { +func resourceArmIotHub() *schema.Resource { return &schema.Resource{ - Create: resourceArmIothubCreateAndUpdate, - Read: resourceArmIothubRead, - Update: resourceArmIothubCreateAndUpdate, - Delete: resourceArmIothubDelete, + Create: resourceArmIotHubCreateAndUpdate, + Read: resourceArmIotHubRead, + Update: resourceArmIotHubCreateAndUpdate, + Delete: resourceArmIotHubDelete, Schema: map[string]*schema.Schema{ - // TODO: use nameAvailabilityInfo for validation "name": { Type: schema.TypeString, Required: true, ForceNew: true, }, - // TODO: is this needed "type": { Type: schema.TypeString, Computed: true, @@ -77,13 +77,27 @@ func resourceArmIothub() *schema.Resource { } } -func resourceArmIothubCreateAndUpdate(d *schema.ResourceData, meta interface{}) error { + +func resourceArmIotHubCreateAndUpdate(d *schema.ResourceData, meta interface{}) error { armClient := meta.(*ArmClient) iothubClient := armClient.iothubResourceClient rg := d.Get("resource_group_name").(string) name := d.Get("name").(string) + + res, err := iothubClient.CheckNameAvailability(iothub.OperationInputs{ + Name: &name, + }) + + if err != nil { + return err + } + + if !*res.NameAvailable { + return errors.New(string(res.Reason)) + } + location := d.Get("location").(string) subscriptionID := armClient.subscriptionId @@ -110,7 +124,7 @@ func resourceArmIothubCreateAndUpdate(d *schema.ResourceData, meta interface{}) cancel := make(chan struct{}) _, errChan := iothubClient.CreateOrUpdate(rg, name, desc, cancel) - err := <-errChan + err = <-errChan if err != nil { return err @@ -122,7 +136,7 @@ func resourceArmIothubCreateAndUpdate(d *schema.ResourceData, meta interface{}) } d.SetId(*desc.ID) - return resourceArmIothubRead(d, meta) + return resourceArmIotHubRead(d, meta) } @@ -139,7 +153,7 @@ func expandAzureRmIotHubSku(d *schema.ResourceData) iothub.SkuInfo { } -func resourceArmIothubRead(d *schema.ResourceData, meta interface{}) error { +func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { id, err := parseAzureResourceID(d.Id()) @@ -161,7 +175,7 @@ func resourceArmIothubRead(d *schema.ResourceData, meta interface{}) error { return nil } -func resourceArmIothubDelete(d *schema.ResourceData, meta interface{}) error { +func resourceArmIotHubDelete(d *schema.ResourceData, meta interface{}) error { id, err := parseAzureResourceID(d.Id()) diff --git a/azurerm/resource_arm_iothub_resource_provider_test.go b/azurerm/resource_arm_iothub_resource_provider_test.go index 7ca841d96b31..67eaefe7e8b0 100644 --- a/azurerm/resource_arm_iothub_resource_provider_test.go +++ b/azurerm/resource_arm_iothub_resource_provider_test.go @@ -10,6 +10,7 @@ import ( "github.com/hashicorp/terraform/terraform" ) +// change this to use ephemeral dynamic resource groups const TestResourceGroup = "girishsandbox" func TestAccAzureRMIotHub_basicStandard(t *testing.T) { @@ -17,12 +18,12 @@ func TestAccAzureRMIotHub_basicStandard(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, - CheckDestroy: testCheckAzureRMIothubDestroy, + CheckDestroy: testCheckAzureRMIotHubDestroy, Steps: []resource.TestStep{ { Config: testAccAzureRMIotHub_basicStandard(name, TestResourceGroup, testLocation()), Check: resource.ComposeTestCheckFunc( - testCheckAzureRMIothubExists("azurerm_iothub.test"), + testCheckAzureRMIotHubExists("azurerm_iothub.test"), ), }, }, @@ -30,7 +31,7 @@ func TestAccAzureRMIotHub_basicStandard(t *testing.T) { } -func testCheckAzureRMIothubDestroy(s *terraform.State) error { +func testCheckAzureRMIotHubDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*ArmClient).expressRouteCircuitClient @@ -49,12 +50,12 @@ func testCheckAzureRMIothubDestroy(s *terraform.State) error { } if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Iothub still exists:\n%#v", resp.ExpressRouteCircuitPropertiesFormat) + return fmt.Errorf("IotHub still exists:\n%#v", resp.ExpressRouteCircuitPropertiesFormat) } } return nil } -func testCheckAzureRMIothubExists(name string) resource.TestCheckFunc { +func testCheckAzureRMIotHubExists(name string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] if !ok { From d6f58e7600176e97e0b3ed957a895f629443ac88 Mon Sep 17 00:00:00 2001 From: Girish Ramnani Date: Mon, 9 Oct 2017 21:55:29 +0530 Subject: [PATCH 29/69] updated the iothub vendor dependency --- .../azure-sdk-for-go/arm/iothub/client.go | 10 +- .../azure-sdk-for-go/arm/iothub/models.go | 266 ++++++--- .../azure-sdk-for-go/arm/iothub/operations.go | 165 ++++++ .../azure-sdk-for-go/arm/iothub/resource.go | 532 ++++++++++++++---- .../azure-sdk-for-go/arm/iothub/version.go | 6 +- vendor/vendor.json | 10 +- 6 files changed, 776 insertions(+), 213 deletions(-) create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/operations.go diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go index b54c132eeeee..f2461d01d9f2 100755 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/client.go @@ -1,7 +1,6 @@ -// Package iothub implements the Azure ARM Iothub service API version -// 2016-02-03. +// Package iothub implements the Azure ARM Iothub service API version 2017-07-01. // -// Use this API to manage the IoT hubs in your subscription. +// Use this API to manage the IoT hubs in your Azure subscription. package iothub // Copyright (c) Microsoft and contributors. All rights reserved. @@ -18,9 +17,8 @@ package iothub // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/Azure/go-autorest/autorest" diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go index 6fa4abb25319..0fcfdf7fecc1 100755 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/models.go @@ -14,9 +14,8 @@ package iothub // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/Azure/go-autorest/autorest" @@ -33,43 +32,36 @@ const ( DeviceConnect AccessRights = "DeviceConnect" // RegistryRead specifies the registry read state for access rights. RegistryRead AccessRights = "RegistryRead" - // RegistryReadDeviceConnect specifies the registry read device connect - // state for access rights. + // RegistryReadDeviceConnect specifies the registry read device connect state for access rights. RegistryReadDeviceConnect AccessRights = "RegistryRead, DeviceConnect" - // RegistryReadRegistryWrite specifies the registry read registry write - // state for access rights. + // RegistryReadRegistryWrite specifies the registry read registry write state for access rights. RegistryReadRegistryWrite AccessRights = "RegistryRead, RegistryWrite" - // RegistryReadRegistryWriteDeviceConnect specifies the registry read - // registry write device connect state for access rights. + // RegistryReadRegistryWriteDeviceConnect specifies the registry read registry write device connect state for access + // rights. RegistryReadRegistryWriteDeviceConnect AccessRights = "RegistryRead, RegistryWrite, DeviceConnect" - // RegistryReadRegistryWriteServiceConnect specifies the registry read - // registry write service connect state for access rights. + // RegistryReadRegistryWriteServiceConnect specifies the registry read registry write service connect state for access + // rights. RegistryReadRegistryWriteServiceConnect AccessRights = "RegistryRead, RegistryWrite, ServiceConnect" - // RegistryReadRegistryWriteServiceConnectDeviceConnect specifies the - // registry read registry write service connect device connect state for - // access rights. + // RegistryReadRegistryWriteServiceConnectDeviceConnect specifies the registry read registry write service connect + // device connect state for access rights. RegistryReadRegistryWriteServiceConnectDeviceConnect AccessRights = "RegistryRead, RegistryWrite, ServiceConnect, DeviceConnect" - // RegistryReadServiceConnect specifies the registry read service connect - // state for access rights. + // RegistryReadServiceConnect specifies the registry read service connect state for access rights. RegistryReadServiceConnect AccessRights = "RegistryRead, ServiceConnect" - // RegistryReadServiceConnectDeviceConnect specifies the registry read - // service connect device connect state for access rights. + // RegistryReadServiceConnectDeviceConnect specifies the registry read service connect device connect state for access + // rights. RegistryReadServiceConnectDeviceConnect AccessRights = "RegistryRead, ServiceConnect, DeviceConnect" // RegistryWrite specifies the registry write state for access rights. RegistryWrite AccessRights = "RegistryWrite" - // RegistryWriteDeviceConnect specifies the registry write device connect - // state for access rights. + // RegistryWriteDeviceConnect specifies the registry write device connect state for access rights. RegistryWriteDeviceConnect AccessRights = "RegistryWrite, DeviceConnect" - // RegistryWriteServiceConnect specifies the registry write service connect - // state for access rights. + // RegistryWriteServiceConnect specifies the registry write service connect state for access rights. RegistryWriteServiceConnect AccessRights = "RegistryWrite, ServiceConnect" - // RegistryWriteServiceConnectDeviceConnect specifies the registry write - // service connect device connect state for access rights. + // RegistryWriteServiceConnectDeviceConnect specifies the registry write service connect device connect state for + // access rights. RegistryWriteServiceConnectDeviceConnect AccessRights = "RegistryWrite, ServiceConnect, DeviceConnect" // ServiceConnect specifies the service connect state for access rights. ServiceConnect AccessRights = "ServiceConnect" - // ServiceConnectDeviceConnect specifies the service connect device connect - // state for access rights. + // ServiceConnectDeviceConnect specifies the service connect device connect state for access rights. ServiceConnectDeviceConnect AccessRights = "ServiceConnect, DeviceConnect" ) @@ -119,67 +111,69 @@ const ( JobTypeBackup JobType = "backup" // JobTypeExport specifies the job type export state for job type. JobTypeExport JobType = "export" - // JobTypeFactoryResetDevice specifies the job type factory reset device - // state for job type. + // JobTypeFactoryResetDevice specifies the job type factory reset device state for job type. JobTypeFactoryResetDevice JobType = "factoryResetDevice" - // JobTypeFirmwareUpdate specifies the job type firmware update state for - // job type. + // JobTypeFirmwareUpdate specifies the job type firmware update state for job type. JobTypeFirmwareUpdate JobType = "firmwareUpdate" // JobTypeImport specifies the job type import state for job type. JobTypeImport JobType = "import" - // JobTypeReadDeviceProperties specifies the job type read device - // properties state for job type. + // JobTypeReadDeviceProperties specifies the job type read device properties state for job type. JobTypeReadDeviceProperties JobType = "readDeviceProperties" - // JobTypeRebootDevice specifies the job type reboot device state for job - // type. + // JobTypeRebootDevice specifies the job type reboot device state for job type. JobTypeRebootDevice JobType = "rebootDevice" // JobTypeUnknown specifies the job type unknown state for job type. JobTypeUnknown JobType = "unknown" - // JobTypeUpdateDeviceConfiguration specifies the job type update device - // configuration state for job type. + // JobTypeUpdateDeviceConfiguration specifies the job type update device configuration state for job type. JobTypeUpdateDeviceConfiguration JobType = "updateDeviceConfiguration" - // JobTypeWriteDeviceProperties specifies the job type write device - // properties state for job type. + // JobTypeWriteDeviceProperties specifies the job type write device properties state for job type. JobTypeWriteDeviceProperties JobType = "writeDeviceProperties" ) -// NameUnavailabilityReason enumerates the values for name unavailability -// reason. +// NameUnavailabilityReason enumerates the values for name unavailability reason. type NameUnavailabilityReason string const ( - // AlreadyExists specifies the already exists state for name unavailability - // reason. + // AlreadyExists specifies the already exists state for name unavailability reason. AlreadyExists NameUnavailabilityReason = "AlreadyExists" // Invalid specifies the invalid state for name unavailability reason. Invalid NameUnavailabilityReason = "Invalid" ) -// OperationMonitoringLevel enumerates the values for operation monitoring -// level. +// OperationMonitoringLevel enumerates the values for operation monitoring level. type OperationMonitoringLevel string const ( - // OperationMonitoringLevelError specifies the operation monitoring level - // error state for operation monitoring level. + // OperationMonitoringLevelError specifies the operation monitoring level error state for operation monitoring level. OperationMonitoringLevelError OperationMonitoringLevel = "Error" - // OperationMonitoringLevelErrorInformation specifies the operation - // monitoring level error information state for operation monitoring level. + // OperationMonitoringLevelErrorInformation specifies the operation monitoring level error information state for + // operation monitoring level. OperationMonitoringLevelErrorInformation OperationMonitoringLevel = "Error, Information" - // OperationMonitoringLevelInformation specifies the operation monitoring - // level information state for operation monitoring level. + // OperationMonitoringLevelInformation specifies the operation monitoring level information state for operation + // monitoring level. OperationMonitoringLevelInformation OperationMonitoringLevel = "Information" - // OperationMonitoringLevelNone specifies the operation monitoring level - // none state for operation monitoring level. + // OperationMonitoringLevelNone specifies the operation monitoring level none state for operation monitoring level. OperationMonitoringLevelNone OperationMonitoringLevel = "None" ) +// RoutingSource enumerates the values for routing source. +type RoutingSource string + +const ( + // DeviceJobLifecycleEvents specifies the device job lifecycle events state for routing source. + DeviceJobLifecycleEvents RoutingSource = "DeviceJobLifecycleEvents" + // DeviceLifecycleEvents specifies the device lifecycle events state for routing source. + DeviceLifecycleEvents RoutingSource = "DeviceLifecycleEvents" + // DeviceMessages specifies the device messages state for routing source. + DeviceMessages RoutingSource = "DeviceMessages" + // TwinChangeEvents specifies the twin change events state for routing source. + TwinChangeEvents RoutingSource = "TwinChangeEvents" +) + // ScaleType enumerates the values for scale type. type ScaleType string const ( - // ScaleTypeAutomatic specifies the scale type automatic state for scale - // type. + // ScaleTypeAutomatic specifies the scale type automatic state for scale type. ScaleTypeAutomatic ScaleType = "Automatic" // ScaleTypeManual specifies the scale type manual state for scale type. ScaleTypeManual ScaleType = "Manual" @@ -241,8 +235,7 @@ type Description struct { Sku *SkuInfo `json:"sku,omitempty"` } -// DescriptionListResult is the JSON-serialized array of IotHubDescription -// objects with a next link. +// DescriptionListResult is the JSON-serialized array of IotHubDescription objects with a next link. type DescriptionListResult struct { autorest.Response `json:"-"` Value *[]Description `json:"value,omitempty"` @@ -269,8 +262,7 @@ type ErrorDetails struct { Details *string `json:"Details,omitempty"` } -// EventHubConsumerGroupInfo is the properties of the EventHubConsumerGroupInfo -// object. +// EventHubConsumerGroupInfo is the properties of the EventHubConsumerGroupInfo object. type EventHubConsumerGroupInfo struct { autorest.Response `json:"-"` Tags *map[string]*string `json:"tags,omitempty"` @@ -278,8 +270,8 @@ type EventHubConsumerGroupInfo struct { Name *string `json:"name,omitempty"` } -// EventHubConsumerGroupsListResult is the JSON-serialized array of Event -// Hub-compatible consumer group names with a next link. +// EventHubConsumerGroupsListResult is the JSON-serialized array of Event Hub-compatible consumer group names with a +// next link. type EventHubConsumerGroupsListResult struct { autorest.Response `json:"-"` Value *[]string `json:"value,omitempty"` @@ -298,8 +290,7 @@ func (client EventHubConsumerGroupsListResult) EventHubConsumerGroupsListResultP autorest.WithBaseURL(to.String(client.NextLink))) } -// EventHubProperties is the properties of the provisioned Event Hub-compatible -// endpoint used by the IoT hub. +// EventHubProperties is the properties of the provisioned Event Hub-compatible endpoint used by the IoT hub. type EventHubProperties struct { RetentionTimeInDays *int64 `json:"retentionTimeInDays,omitempty"` PartitionCount *int32 `json:"partitionCount,omitempty"` @@ -308,23 +299,29 @@ type EventHubProperties struct { Endpoint *string `json:"endpoint,omitempty"` } -// ExportDevicesRequest is use to provide parameters when requesting an export -// of all devices in the IoT hub. +// ExportDevicesRequest is use to provide parameters when requesting an export of all devices in the IoT hub. type ExportDevicesRequest struct { ExportBlobContainerURI *string `json:"ExportBlobContainerUri,omitempty"` ExcludeKeys *bool `json:"ExcludeKeys,omitempty"` } -// FeedbackProperties is the properties of the feedback queue for -// cloud-to-device messages. +// FallbackRouteProperties is the properties of the fallback route. IoT Hub uses these properties when it routes +// messages to the fallback endpoint. +type FallbackRouteProperties struct { + Source *string `json:"source,omitempty"` + Condition *string `json:"condition,omitempty"` + EndpointNames *[]string `json:"endpointNames,omitempty"` + IsEnabled *bool `json:"isEnabled,omitempty"` +} + +// FeedbackProperties is the properties of the feedback queue for cloud-to-device messages. type FeedbackProperties struct { LockDurationAsIso8601 *string `json:"lockDurationAsIso8601,omitempty"` TTLAsIso8601 *string `json:"ttlAsIso8601,omitempty"` MaxDeliveryCount *int32 `json:"maxDeliveryCount,omitempty"` } -// ImportDevicesRequest is use to provide parameters when requesting an import -// of all devices in the hub. +// ImportDevicesRequest is use to provide parameters when requesting an import of all devices in the hub. type ImportDevicesRequest struct { InputBlobContainerURI *string `json:"InputBlobContainerUri,omitempty"` OutputBlobContainerURI *string `json:"OutputBlobContainerUri,omitempty"` @@ -350,8 +347,7 @@ type JobResponse struct { ParentJobID *string `json:"parentJobId,omitempty"` } -// JobResponseListResult is the JSON-serialized array of JobResponse objects -// with a next link. +// JobResponseListResult is the JSON-serialized array of JobResponse objects with a next link. type JobResponseListResult struct { autorest.Response `json:"-"` Value *[]JobResponse `json:"value,omitempty"` @@ -370,16 +366,14 @@ func (client JobResponseListResult) JobResponseListResultPreparer() (*http.Reque autorest.WithBaseURL(to.String(client.NextLink))) } -// MessagingEndpointProperties is the properties of the messaging endpoints -// used by this IoT hub. +// MessagingEndpointProperties is the properties of the messaging endpoints used by this IoT hub. type MessagingEndpointProperties struct { LockDurationAsIso8601 *string `json:"lockDurationAsIso8601,omitempty"` TTLAsIso8601 *string `json:"ttlAsIso8601,omitempty"` MaxDeliveryCount *int32 `json:"maxDeliveryCount,omitempty"` } -// NameAvailabilityInfo is the properties indicating whether a given IoT hub -// name is available. +// NameAvailabilityInfo is the properties indicating whether a given IoT hub name is available. type NameAvailabilityInfo struct { autorest.Response `json:"-"` NameAvailable *bool `json:"nameAvailable,omitempty"` @@ -387,15 +381,47 @@ type NameAvailabilityInfo struct { Message *string `json:"message,omitempty"` } +// Operation is ioT Hub REST API operation +type Operation struct { + Name *string `json:"name,omitempty"` + Display *OperationDisplay `json:"display,omitempty"` +} + +// OperationDisplay is the object that represents the operation. +type OperationDisplay struct { + Provider *string `json:"provider,omitempty"` + Resource *string `json:"resource,omitempty"` + Operation *string `json:"operation,omitempty"` +} + // OperationInputs is input values. type OperationInputs struct { Name *string `json:"Name,omitempty"` } -// OperationsMonitoringProperties is the operations monitoring properties for -// the IoT hub. The possible keys to the dictionary are Connections, -// DeviceTelemetry, C2DCommands, DeviceIdentityOperations, -// FileUploadOperations. +// OperationListResult is result of the request to list IoT Hub operations. It contains a list of operations and a URL +// link to get the next set of results. +type OperationListResult struct { + autorest.Response `json:"-"` + Value *[]Operation `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// OperationListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client OperationListResult) OperationListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// OperationsMonitoringProperties is the operations monitoring properties for the IoT hub. The possible keys to the +// dictionary are Connections, DeviceTelemetry, C2DCommands, DeviceIdentityOperations, FileUploadOperations, Routes, +// D2CTwinOperations, C2DTwinOperations, TwinQueries, JobsOperations, DirectMethods. type OperationsMonitoringProperties struct { Events *map[string]*OperationMonitoringLevel `json:"events,omitempty"` } @@ -407,6 +433,7 @@ type Properties struct { ProvisioningState *string `json:"provisioningState,omitempty"` HostName *string `json:"hostName,omitempty"` EventHubEndpoints *map[string]*EventHubProperties `json:"eventHubEndpoints,omitempty"` + Routing *RoutingProperties `json:"routing,omitempty"` StorageEndpoints *map[string]*StorageEndpointProperties `json:"storageEndpoints,omitempty"` MessagingEndpoints *map[string]*MessagingEndpointProperties `json:"messagingEndpoints,omitempty"` EnableFileUploadNotifications *bool `json:"enableFileUploadNotifications,omitempty"` @@ -423,8 +450,7 @@ type QuotaMetricInfo struct { MaxValue *int64 `json:"MaxValue,omitempty"` } -// QuotaMetricInfoListResult is the JSON-serialized array of -// IotHubQuotaMetricInfo objects with a next link. +// QuotaMetricInfoListResult is the JSON-serialized array of IotHubQuotaMetricInfo objects with a next link. type QuotaMetricInfoListResult struct { autorest.Response `json:"-"` Value *[]QuotaMetricInfo `json:"value,omitempty"` @@ -451,7 +477,7 @@ type RegistryStatistics struct { DisabledDeviceCount *int64 `json:"disabledDeviceCount,omitempty"` } -// Resource is +// Resource is the common properties of an Azure resource. type Resource struct { ID *string `json:"id,omitempty"` Name *string `json:"name,omitempty"` @@ -460,14 +486,77 @@ type Resource struct { Tags *map[string]*string `json:"tags,omitempty"` } +// RouteProperties is the properties of a routing rule that your IoT hub uses to route messages to endpoints. +type RouteProperties struct { + Name *string `json:"name,omitempty"` + Source RoutingSource `json:"source,omitempty"` + Condition *string `json:"condition,omitempty"` + EndpointNames *[]string `json:"endpointNames,omitempty"` + IsEnabled *bool `json:"isEnabled,omitempty"` +} + +// RoutingEndpoints is the properties related to the custom endpoints to which your IoT hub routes messages based on +// the routing rules. A maximum of 10 custom endpoints are allowed across all endpoint types for paid hubs and only 1 +// custom endpoint is allowed across all endpoint types for free hubs. +type RoutingEndpoints struct { + ServiceBusQueues *[]RoutingServiceBusQueueEndpointProperties `json:"serviceBusQueues,omitempty"` + ServiceBusTopics *[]RoutingServiceBusTopicEndpointProperties `json:"serviceBusTopics,omitempty"` + EventHubs *[]RoutingEventHubProperties `json:"eventHubs,omitempty"` + StorageContainers *[]RoutingStorageContainerProperties `json:"storageContainers,omitempty"` +} + +// RoutingEventHubProperties is the properties related to an event hub endpoint. +type RoutingEventHubProperties struct { + ConnectionString *string `json:"connectionString,omitempty"` + Name *string `json:"name,omitempty"` + SubscriptionID *string `json:"subscriptionId,omitempty"` + ResourceGroup *string `json:"resourceGroup,omitempty"` +} + +// RoutingProperties is the routing related properties of the IoT hub. See: +// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging +type RoutingProperties struct { + Endpoints *RoutingEndpoints `json:"endpoints,omitempty"` + Routes *[]RouteProperties `json:"routes,omitempty"` + FallbackRoute *FallbackRouteProperties `json:"fallbackRoute,omitempty"` +} + +// RoutingServiceBusQueueEndpointProperties is the properties related to service bus queue endpoint types. +type RoutingServiceBusQueueEndpointProperties struct { + ConnectionString *string `json:"connectionString,omitempty"` + Name *string `json:"name,omitempty"` + SubscriptionID *string `json:"subscriptionId,omitempty"` + ResourceGroup *string `json:"resourceGroup,omitempty"` +} + +// RoutingServiceBusTopicEndpointProperties is the properties related to service bus topic endpoint types. +type RoutingServiceBusTopicEndpointProperties struct { + ConnectionString *string `json:"connectionString,omitempty"` + Name *string `json:"name,omitempty"` + SubscriptionID *string `json:"subscriptionId,omitempty"` + ResourceGroup *string `json:"resourceGroup,omitempty"` +} + +// RoutingStorageContainerProperties is the properties related to a storage container endpoint. +type RoutingStorageContainerProperties struct { + ConnectionString *string `json:"connectionString,omitempty"` + Name *string `json:"name,omitempty"` + SubscriptionID *string `json:"subscriptionId,omitempty"` + ResourceGroup *string `json:"resourceGroup,omitempty"` + ContainerName *string `json:"containerName,omitempty"` + FileNameFormat *string `json:"fileNameFormat,omitempty"` + BatchFrequencyInSeconds *int32 `json:"batchFrequencyInSeconds,omitempty"` + MaxChunkSizeInBytes *int32 `json:"maxChunkSizeInBytes,omitempty"` + Encoding *string `json:"encoding,omitempty"` +} + // SetObject is type SetObject struct { autorest.Response `json:"-"` Value *map[string]interface{} `json:"value,omitempty"` } -// SharedAccessSignatureAuthorizationRule is the properties of an IoT hub -// shared access policy. +// SharedAccessSignatureAuthorizationRule is the properties of an IoT hub shared access policy. type SharedAccessSignatureAuthorizationRule struct { autorest.Response `json:"-"` KeyName *string `json:"keyName,omitempty"` @@ -476,8 +565,7 @@ type SharedAccessSignatureAuthorizationRule struct { Rights AccessRights `json:"rights,omitempty"` } -// SharedAccessSignatureAuthorizationRuleListResult is the list of shared -// access policies with a next link. +// SharedAccessSignatureAuthorizationRuleListResult is the list of shared access policies with a next link. type SharedAccessSignatureAuthorizationRuleListResult struct { autorest.Response `json:"-"` Value *[]SharedAccessSignatureAuthorizationRule `json:"value,omitempty"` @@ -496,15 +584,14 @@ func (client SharedAccessSignatureAuthorizationRuleListResult) SharedAccessSigna autorest.WithBaseURL(to.String(client.NextLink))) } -// SkuDescription is sKU properties. +// SkuDescription is SKU properties. type SkuDescription struct { ResourceType *string `json:"resourceType,omitempty"` Sku *SkuInfo `json:"sku,omitempty"` Capacity *Capacity `json:"capacity,omitempty"` } -// SkuDescriptionListResult is the JSON-serialized array of -// IotHubSkuDescription objects with a next link. +// SkuDescriptionListResult is the JSON-serialized array of IotHubSkuDescription objects with a next link. type SkuDescriptionListResult struct { autorest.Response `json:"-"` Value *[]SkuDescription `json:"value,omitempty"` @@ -530,8 +617,7 @@ type SkuInfo struct { Capacity *int64 `json:"capacity,omitempty"` } -// StorageEndpointProperties is the properties of the Azure Storage endpoint -// for file upload. +// StorageEndpointProperties is the properties of the Azure Storage endpoint for file upload. type StorageEndpointProperties struct { SasTTLAsIso8601 *string `json:"sasTtlAsIso8601,omitempty"` ConnectionString *string `json:"connectionString,omitempty"` diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/operations.go new file mode 100644 index 000000000000..ae4d1bf0cc4e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/operations.go @@ -0,0 +1,165 @@ +package iothub + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// OperationsClient is the use this API to manage the IoT hubs in your Azure subscription. +type OperationsClient struct { + ManagementClient +} + +// NewOperationsClient creates an instance of the OperationsClient client. +func NewOperationsClient(subscriptionID string) OperationsClient { + return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client. +func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { + return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List lists all of the available IoT Hub REST API operations. +func (client OperationsClient) List() (result OperationListResult, err error) { + req, err := client.ListPreparer() + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.OperationsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "iothub.OperationsClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.OperationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client OperationsClient) ListPreparer() (*http.Request, error) { + const APIVersion = "2017-07-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.Devices/operations"), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client OperationsClient) ListResponder(resp *http.Response) (result OperationListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client OperationsClient) ListNextResults(lastResults OperationListResult) (result OperationListResult, err error) { + req, err := lastResults.OperationListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "iothub.OperationsClient", "List", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "iothub.OperationsClient", "List", resp, "Failure sending next results request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "iothub.OperationsClient", "List", resp, "Failure responding to next results request") + } + + return +} + +// ListComplete gets all elements from the list without paging. +func (client OperationsClient) ListComplete(cancel <-chan struct{}) (<-chan Operation, <-chan error) { + resultChan := make(chan Operation) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.List() + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.ListNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go index 83b97042999c..defcf95911f1 100755 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/resource.go @@ -14,9 +14,8 @@ package iothub // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/Azure/go-autorest/autorest" @@ -25,8 +24,7 @@ import ( "net/http" ) -// ResourceClient is the use this API to manage the IoT hubs in your -// subscription. +// ResourceClient is the use this API to manage the IoT hubs in your Azure subscription. type ResourceClient struct { ManagementClient } @@ -36,16 +34,14 @@ func NewResourceClient(subscriptionID string) ResourceClient { return NewResourceClientWithBaseURI(DefaultBaseURI, subscriptionID) } -// NewResourceClientWithBaseURI creates an instance of the ResourceClient -// client. +// NewResourceClientWithBaseURI creates an instance of the ResourceClient client. func NewResourceClientWithBaseURI(baseURI string, subscriptionID string) ResourceClient { return ResourceClient{NewWithBaseURI(baseURI, subscriptionID)} } // CheckNameAvailability check if an IoT hub name is available. // -// operationInputs is set the name parameter in the OperationInputs structure -// to the name of the IoT hub to check. +// operationInputs is set the name parameter in the OperationInputs structure to the name of the IoT hub to check. func (client ResourceClient) CheckNameAvailability(operationInputs OperationInputs) (result NameAvailabilityInfo, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: operationInputs, @@ -80,7 +76,7 @@ func (client ResourceClient) CheckNameAvailabilityPreparer(operationInputs Opera "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -114,13 +110,11 @@ func (client ResourceClient) CheckNameAvailabilityResponder(resp *http.Response) return } -// CreateEventHubConsumerGroup add a consumer group to an Event Hub-compatible -// endpoint in an IoT hub. +// CreateEventHubConsumerGroup add a consumer group to an Event Hub-compatible endpoint in an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the -// name of the Event Hub-compatible endpoint in the IoT hub. name is the name -// of the consumer group to add. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. eventHubEndpointName is the name of the Event Hub-compatible endpoint in the IoT hub. name is the name of the +// consumer group to add. func (client ResourceClient) CreateEventHubConsumerGroup(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (result EventHubConsumerGroupInfo, err error) { req, err := client.CreateEventHubConsumerGroupPreparer(resourceGroupName, resourceName, eventHubEndpointName, name) if err != nil { @@ -153,7 +147,7 @@ func (client ResourceClient) CreateEventHubConsumerGroupPreparer(resourceGroupNa "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -185,16 +179,13 @@ func (client ResourceClient) CreateEventHubConsumerGroupResponder(resp *http.Res return } -// CreateOrUpdate create or update the metadata of an Iot hub. The usual -// pattern to modify a property is to retrieve the IoT hub metadata and -// security metadata, and then combine them with the modified values in a new -// body to update the IoT hub. This method may poll for completion. Polling can -// be canceled by passing the cancel channel argument. The channel will be used -// to cancel polling and any outstanding HTTP requests. +// CreateOrUpdate create or update the metadata of an Iot hub. The usual pattern to modify a property is to retrieve +// the IoT hub metadata and security metadata, and then combine them with the modified values in a new body to update +// the IoT hub. This method may poll for completion. Polling can be canceled by passing the cancel channel argument. +// The channel will be used to cancel polling and any outstanding HTTP requests. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub to create or update. -// iotHubDescription is the IoT hub metadata and security metadata. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub to create or update. iotHubDescription is the IoT hub metadata and security metadata. func (client ResourceClient) CreateOrUpdate(resourceGroupName string, resourceName string, iotHubDescription Description, cancel <-chan struct{}) (<-chan Description, <-chan error) { resultChan := make(chan Description, 1) errChan := make(chan error, 1) @@ -203,18 +194,28 @@ func (client ResourceClient) CreateOrUpdate(resourceGroupName string, resourceNa Constraints: []validation.Constraint{{Target: "iotHubDescription.Subscriptionid", Name: validation.Null, Rule: true, Chain: nil}, {Target: "iotHubDescription.Resourcegroup", Name: validation.Null, Rule: true, Chain: nil}, {Target: "iotHubDescription.Properties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, - {Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, - }}, - {Target: "iotHubDescription.Properties.CloudToDevice.Feedback", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, - {Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing.FallbackRoute", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing.FallbackRoute.Source", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "iotHubDescription.Properties.Routing.FallbackRoute.EndpointNames", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.Routing.FallbackRoute.EndpointNames", Name: validation.MaxItems, Rule: 1, Chain: nil}, + {Target: "iotHubDescription.Properties.Routing.FallbackRoute.EndpointNames", Name: validation.MinItems, Rule: 1, Chain: nil}, }}, - }}, + {Target: "iotHubDescription.Properties.Routing.FallbackRoute.IsEnabled", Name: validation.Null, Rule: true, Chain: nil}, + }}, }}, + {Target: "iotHubDescription.Properties.CloudToDevice", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, + {Target: "iotHubDescription.Properties.CloudToDevice.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}, + {Target: "iotHubDescription.Properties.CloudToDevice.Feedback", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMaximum, Rule: 100, Chain: nil}, + {Target: "iotHubDescription.Properties.CloudToDevice.Feedback.MaxDeliveryCount", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}, + }}, + }}, }}, {Target: "iotHubDescription.Sku", Name: validation.Null, Rule: true, Chain: []validation.Constraint{{Target: "iotHubDescription.Sku.Capacity", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { @@ -228,8 +229,10 @@ func (client ResourceClient) CreateOrUpdate(resourceGroupName string, resourceNa var err error var result Description defer func() { + if err != nil { + errChan <- err + } resultChan <- result - errChan <- err close(resultChan) close(errChan) }() @@ -262,7 +265,7 @@ func (client ResourceClient) CreateOrUpdatePreparer(resourceGroupName string, re "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -298,12 +301,11 @@ func (client ResourceClient) CreateOrUpdateResponder(resp *http.Response) (resul return } -// Delete delete an IoT hub. This method may poll for completion. Polling can -// be canceled by passing the cancel channel argument. The channel will be used -// to cancel polling and any outstanding HTTP requests. +// Delete delete an IoT hub. This method may poll for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding HTTP requests. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub to delete. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub to delete. func (client ResourceClient) Delete(resourceGroupName string, resourceName string, cancel <-chan struct{}) (<-chan SetObject, <-chan error) { resultChan := make(chan SetObject, 1) errChan := make(chan error, 1) @@ -311,8 +313,10 @@ func (client ResourceClient) Delete(resourceGroupName string, resourceName strin var err error var result SetObject defer func() { + if err != nil { + errChan <- err + } resultChan <- result - errChan <- err close(resultChan) close(errChan) }() @@ -345,7 +349,7 @@ func (client ResourceClient) DeletePreparer(resourceGroupName string, resourceNa "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -379,13 +383,11 @@ func (client ResourceClient) DeleteResponder(resp *http.Response) (result SetObj return } -// DeleteEventHubConsumerGroup delete a consumer group from an Event -// Hub-compatible endpoint in an IoT hub. +// DeleteEventHubConsumerGroup delete a consumer group from an Event Hub-compatible endpoint in an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the -// name of the Event Hub-compatible endpoint in the IoT hub. name is the name -// of the consumer group to delete. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. eventHubEndpointName is the name of the Event Hub-compatible endpoint in the IoT hub. name is the name of the +// consumer group to delete. func (client ResourceClient) DeleteEventHubConsumerGroup(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (result autorest.Response, err error) { req, err := client.DeleteEventHubConsumerGroupPreparer(resourceGroupName, resourceName, eventHubEndpointName, name) if err != nil { @@ -418,7 +420,7 @@ func (client ResourceClient) DeleteEventHubConsumerGroupPreparer(resourceGroupNa "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -449,13 +451,12 @@ func (client ResourceClient) DeleteEventHubConsumerGroupResponder(resp *http.Res return } -// ExportDevices exports all the device identities in the IoT hub identity -// registry to an Azure Storage blob container. For more information, see: +// ExportDevices exports all the device identities in the IoT hub identity registry to an Azure Storage blob container. +// For more information, see: // https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. exportDevicesParameters is the -// parameters that specify the export devices operation. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. exportDevicesParameters is the parameters that specify the export devices operation. func (client ResourceClient) ExportDevices(resourceGroupName string, resourceName string, exportDevicesParameters ExportDevicesRequest) (result JobResponse, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: exportDevicesParameters, @@ -493,7 +494,7 @@ func (client ResourceClient) ExportDevicesPreparer(resourceGroupName string, res "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -529,8 +530,8 @@ func (client ResourceClient) ExportDevicesResponder(resp *http.Response) (result // Get get the non-security related metadata of an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. func (client ResourceClient) Get(resourceGroupName string, resourceName string) (result Description, err error) { req, err := client.GetPreparer(resourceGroupName, resourceName) if err != nil { @@ -561,7 +562,7 @@ func (client ResourceClient) GetPreparer(resourceGroupName string, resourceName "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -593,13 +594,11 @@ func (client ResourceClient) GetResponder(resp *http.Response) (result Descripti return } -// GetEventHubConsumerGroup get a consumer group from the Event Hub-compatible -// device-to-cloud endpoint for an IoT hub. +// GetEventHubConsumerGroup get a consumer group from the Event Hub-compatible device-to-cloud endpoint for an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the -// name of the Event Hub-compatible endpoint in the IoT hub. name is the name -// of the consumer group to retrieve. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. eventHubEndpointName is the name of the Event Hub-compatible endpoint in the IoT hub. name is the name of the +// consumer group to retrieve. func (client ResourceClient) GetEventHubConsumerGroup(resourceGroupName string, resourceName string, eventHubEndpointName string, name string) (result EventHubConsumerGroupInfo, err error) { req, err := client.GetEventHubConsumerGroupPreparer(resourceGroupName, resourceName, eventHubEndpointName, name) if err != nil { @@ -632,7 +631,7 @@ func (client ResourceClient) GetEventHubConsumerGroupPreparer(resourceGroupName "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -667,8 +666,8 @@ func (client ResourceClient) GetEventHubConsumerGroupResponder(resp *http.Respon // GetJob get the details of a job from an IoT hub. For more information, see: // https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. jobID is the job identifier. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. jobID is the job identifier. func (client ResourceClient) GetJob(resourceGroupName string, resourceName string, jobID string) (result JobResponse, err error) { req, err := client.GetJobPreparer(resourceGroupName, resourceName, jobID) if err != nil { @@ -700,7 +699,7 @@ func (client ResourceClient) GetJobPreparer(resourceGroupName string, resourceNa "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -732,13 +731,11 @@ func (client ResourceClient) GetJobResponder(resp *http.Response) (result JobRes return } -// GetKeysForKeyName get a shared access policy by name from an IoT hub. For -// more information, see: +// GetKeysForKeyName get a shared access policy by name from an IoT hub. For more information, see: // https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. keyName is the name of the -// shared access policy. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. keyName is the name of the shared access policy. func (client ResourceClient) GetKeysForKeyName(resourceGroupName string, resourceName string, keyName string) (result SharedAccessSignatureAuthorizationRule, err error) { req, err := client.GetKeysForKeyNamePreparer(resourceGroupName, resourceName, keyName) if err != nil { @@ -770,7 +767,7 @@ func (client ResourceClient) GetKeysForKeyNamePreparer(resourceGroupName string, "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -804,8 +801,8 @@ func (client ResourceClient) GetKeysForKeyNameResponder(resp *http.Response) (re // GetQuotaMetrics get the quota metrics for an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. func (client ResourceClient) GetQuotaMetrics(resourceGroupName string, resourceName string) (result QuotaMetricInfoListResult, err error) { req, err := client.GetQuotaMetricsPreparer(resourceGroupName, resourceName) if err != nil { @@ -836,7 +833,7 @@ func (client ResourceClient) GetQuotaMetricsPreparer(resourceGroupName string, r "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -892,10 +889,55 @@ func (client ResourceClient) GetQuotaMetricsNextResults(lastResults QuotaMetricI return } +// GetQuotaMetricsComplete gets all elements from the list without paging. +func (client ResourceClient) GetQuotaMetricsComplete(resourceGroupName string, resourceName string, cancel <-chan struct{}) (<-chan QuotaMetricInfo, <-chan error) { + resultChan := make(chan QuotaMetricInfo) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.GetQuotaMetrics(resourceGroupName, resourceName) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.GetQuotaMetricsNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} + // GetStats get the statistics from an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. func (client ResourceClient) GetStats(resourceGroupName string, resourceName string) (result RegistryStatistics, err error) { req, err := client.GetStatsPreparer(resourceGroupName, resourceName) if err != nil { @@ -926,7 +968,7 @@ func (client ResourceClient) GetStatsPreparer(resourceGroupName string, resource "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -960,8 +1002,8 @@ func (client ResourceClient) GetStatsResponder(resp *http.Response) (result Regi // GetValidSkus get the list of valid SKUs for an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. func (client ResourceClient) GetValidSkus(resourceGroupName string, resourceName string) (result SkuDescriptionListResult, err error) { req, err := client.GetValidSkusPreparer(resourceGroupName, resourceName) if err != nil { @@ -992,7 +1034,7 @@ func (client ResourceClient) GetValidSkusPreparer(resourceGroupName string, reso "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1048,13 +1090,57 @@ func (client ResourceClient) GetValidSkusNextResults(lastResults SkuDescriptionL return } -// ImportDevices import, update, or delete device identities in the IoT hub -// identity registry from a blob. For more information, see: +// GetValidSkusComplete gets all elements from the list without paging. +func (client ResourceClient) GetValidSkusComplete(resourceGroupName string, resourceName string, cancel <-chan struct{}) (<-chan SkuDescription, <-chan error) { + resultChan := make(chan SkuDescription) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.GetValidSkus(resourceGroupName, resourceName) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.GetValidSkusNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} + +// ImportDevices import, update, or delete device identities in the IoT hub identity registry from a blob. For more +// information, see: // https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. importDevicesParameters is the -// parameters that specify the import devices operation. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. importDevicesParameters is the parameters that specify the import devices operation. func (client ResourceClient) ImportDevices(resourceGroupName string, resourceName string, importDevicesParameters ImportDevicesRequest) (result JobResponse, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: importDevicesParameters, @@ -1092,7 +1178,7 @@ func (client ResourceClient) ImportDevicesPreparer(resourceGroupName string, res "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1128,8 +1214,7 @@ func (client ResourceClient) ImportDevicesResponder(resp *http.Response) (result // ListByResourceGroup get all the IoT hubs in a resource group. // -// resourceGroupName is the name of the resource group that contains the IoT -// hubs. +// resourceGroupName is the name of the resource group that contains the IoT hubs. func (client ResourceClient) ListByResourceGroup(resourceGroupName string) (result DescriptionListResult, err error) { req, err := client.ListByResourceGroupPreparer(resourceGroupName) if err != nil { @@ -1159,7 +1244,7 @@ func (client ResourceClient) ListByResourceGroupPreparer(resourceGroupName strin "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1215,6 +1300,51 @@ func (client ResourceClient) ListByResourceGroupNextResults(lastResults Descript return } +// ListByResourceGroupComplete gets all elements from the list without paging. +func (client ResourceClient) ListByResourceGroupComplete(resourceGroupName string, cancel <-chan struct{}) (<-chan Description, <-chan error) { + resultChan := make(chan Description) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.ListByResourceGroup(resourceGroupName) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.ListByResourceGroupNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} + // ListBySubscription get all the IoT hubs in a subscription. func (client ResourceClient) ListBySubscription() (result DescriptionListResult, err error) { req, err := client.ListBySubscriptionPreparer() @@ -1244,7 +1374,7 @@ func (client ResourceClient) ListBySubscriptionPreparer() (*http.Request, error) "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1300,12 +1430,56 @@ func (client ResourceClient) ListBySubscriptionNextResults(lastResults Descripti return } -// ListEventHubConsumerGroups get a list of the consumer groups in the Event -// Hub-compatible device-to-cloud endpoint in an IoT hub. +// ListBySubscriptionComplete gets all elements from the list without paging. +func (client ResourceClient) ListBySubscriptionComplete(cancel <-chan struct{}) (<-chan Description, <-chan error) { + resultChan := make(chan Description) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.ListBySubscription() + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.ListBySubscriptionNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} + +// ListEventHubConsumerGroups get a list of the consumer groups in the Event Hub-compatible device-to-cloud endpoint in +// an IoT hub. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. eventHubEndpointName is the -// name of the Event Hub-compatible endpoint. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. eventHubEndpointName is the name of the Event Hub-compatible endpoint. func (client ResourceClient) ListEventHubConsumerGroups(resourceGroupName string, resourceName string, eventHubEndpointName string) (result EventHubConsumerGroupsListResult, err error) { req, err := client.ListEventHubConsumerGroupsPreparer(resourceGroupName, resourceName, eventHubEndpointName) if err != nil { @@ -1337,7 +1511,7 @@ func (client ResourceClient) ListEventHubConsumerGroupsPreparer(resourceGroupNam "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1393,12 +1567,56 @@ func (client ResourceClient) ListEventHubConsumerGroupsNextResults(lastResults E return } -// ListJobs get a list of all the jobs in an IoT hub. For more information, -// see: +// ListEventHubConsumerGroupsComplete gets all elements from the list without paging. +func (client ResourceClient) ListEventHubConsumerGroupsComplete(resourceGroupName string, resourceName string, eventHubEndpointName string, cancel <-chan struct{}) (<-chan string, <-chan error) { + resultChan := make(chan string) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.ListEventHubConsumerGroups(resourceGroupName, resourceName, eventHubEndpointName) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.ListEventHubConsumerGroupsNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} + +// ListJobs get a list of all the jobs in an IoT hub. For more information, see: // https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. func (client ResourceClient) ListJobs(resourceGroupName string, resourceName string) (result JobResponseListResult, err error) { req, err := client.ListJobsPreparer(resourceGroupName, resourceName) if err != nil { @@ -1429,7 +1647,7 @@ func (client ResourceClient) ListJobsPreparer(resourceGroupName string, resource "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1485,11 +1703,56 @@ func (client ResourceClient) ListJobsNextResults(lastResults JobResponseListResu return } -// ListKeys get the security metadata for an IoT hub. For more information, -// see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. +// ListJobsComplete gets all elements from the list without paging. +func (client ResourceClient) ListJobsComplete(resourceGroupName string, resourceName string, cancel <-chan struct{}) (<-chan JobResponse, <-chan error) { + resultChan := make(chan JobResponse) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.ListJobs(resourceGroupName, resourceName) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.ListJobsNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} + +// ListKeys get the security metadata for an IoT hub. For more information, see: +// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security. // -// resourceGroupName is the name of the resource group that contains the IoT -// hub. resourceName is the name of the IoT hub. +// resourceGroupName is the name of the resource group that contains the IoT hub. resourceName is the name of the IoT +// hub. func (client ResourceClient) ListKeys(resourceGroupName string, resourceName string) (result SharedAccessSignatureAuthorizationRuleListResult, err error) { req, err := client.ListKeysPreparer(resourceGroupName, resourceName) if err != nil { @@ -1520,7 +1783,7 @@ func (client ResourceClient) ListKeysPreparer(resourceGroupName string, resource "subscriptionId": autorest.Encode("path", client.SubscriptionID), } - const APIVersion = "2016-02-03" + const APIVersion = "2017-07-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } @@ -1575,3 +1838,48 @@ func (client ResourceClient) ListKeysNextResults(lastResults SharedAccessSignatu return } + +// ListKeysComplete gets all elements from the list without paging. +func (client ResourceClient) ListKeysComplete(resourceGroupName string, resourceName string, cancel <-chan struct{}) (<-chan SharedAccessSignatureAuthorizationRule, <-chan error) { + resultChan := make(chan SharedAccessSignatureAuthorizationRule) + errChan := make(chan error, 1) + go func() { + defer func() { + close(resultChan) + close(errChan) + }() + list, err := client.ListKeys(resourceGroupName, resourceName) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + for list.NextLink != nil { + list, err = client.ListKeysNextResults(list) + if err != nil { + errChan <- err + return + } + if list.Value != nil { + for _, item := range *list.Value { + select { + case <-cancel: + return + case resultChan <- item: + // Intentionally left blank + } + } + } + } + }() + return resultChan, errChan +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go index d33d9dd5ad26..71c1b6e27286 100755 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/iothub/version.go @@ -14,15 +14,15 @@ package iothub // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0 +// Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { - return "Azure-SDK-For-Go/v10.3.0-beta arm-iothub/2017-07-01" + return "Azure-SDK-For-Go/v11.0.0-beta arm-iothub/2017-07-01" } // Version returns the semantic version (see http://semver.org) of the client. func Version() string { - return "v10.3.0-beta" + return "v11.0.0-beta" } diff --git a/vendor/vendor.json b/vendor/vendor.json index 52115e9ca680..5b3e689bbbe6 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -115,15 +115,21 @@ "versionExact": "v11.1.0-beta" }, { +<<<<<<< HEAD <<<<<<< HEAD "checksumSHA1": "ALyRCjT78W2bC4r8R/wexKF8ASQ=", ||||||| merged common ancestors "checksumSHA1": "FloEh78hgEozkpt0y4SPWK23/wI=", ======= "checksumSHA1": "wSLOrUgDpf9pmtZKl2KO3OavrZU=", +||||||| merged common ancestors + "checksumSHA1": "wSLOrUgDpf9pmtZKl2KO3OavrZU=", +======= + "checksumSHA1": "NCPG/4kLZlxz92cQE4NMyORU94k=", +>>>>>>> updated the iothub vendor dependency "path": "github.com/Azure/azure-sdk-for-go/arm/iothub", - "revision": "dedad7d55bef3a5fd61d3b682bcba0a93cf315e8", - "revisionTime": "2017-08-24T19:57:27Z" + "revision": "9f366792afa3e0ddaecdc860e793ba9d75e76c27", + "revisionTime": "2017-10-06T23:46:41Z" }, { "checksumSHA1": "FloEh78hgEozkpt0y4SPWK23/wI=", From 96bf5f66de6b9745ac3e7be39c975cd48124bcea Mon Sep 17 00:00:00 2001 From: girishramnani Date: Wed, 11 Oct 2017 13:43:33 +0530 Subject: [PATCH 30/69] Added keys to the lifecycle and schema --- .../resource_arm_iothub_resource_provider.go | 81 +++++++++++++++---- ...ource_arm_iothub_resource_provider_test.go | 1 - 2 files changed, 65 insertions(+), 17 deletions(-) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index bacf410b0223..643a34f7f9d1 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -21,24 +21,10 @@ func resourceArmIotHub() *schema.Resource { Required: true, ForceNew: true, }, - - "type": { - Type: schema.TypeString, - Computed: true, - }, - + "tags": tagsSchema(), "location": locationSchema(), "resource_group_name": resourceGroupNameSchema(), - - "etag": { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "tags": tagsSchema(), - "sku": { Type: schema.TypeList, MaxItems: 1, @@ -73,6 +59,47 @@ func resourceArmIotHub() *schema.Resource { }, }, }, + + "type": { + Type: schema.TypeString, + Computed: true, + }, + + "etag": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "hostname": { + Type: schema.TypeString, + Computed: true, + }, + + "shared_access_policy": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "key_name": { + Type: schema.TypeString, + Computed: true, + }, + "primary_key": { + Type: schema.TypeString, + Computed: true, + }, + "secondary_key": { + Type: schema.TypeString, + Computed: true, + }, + "permissions": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, }, } @@ -163,11 +190,33 @@ func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { armClient := meta.(*ArmClient) iothubClient := armClient.iothubResourceClient - desc, err := iothubClient.Get(id.ResourceGroup, id.Path["IotHubs"]) + iothubName := id.Path["IotHubs"] + desc, err := iothubClient.Get(id.ResourceGroup, iothubName) + + if err != nil { + return err + } + + properties := desc.Properties + + keysResp, err := iothubClient.ListKeys(id.ResourceGroup, iothubName) + + var keys []map[string]interface{} + for _, key := range *keysResp.Value { + keyMap := make(map[string]interface{}) + keyMap["key_name"] = key.KeyName + keyMap["primary_key"] = key.PrimaryKey + keyMap["secondary_key"] = key.SecondaryKey + keyMap["permissions"] = string(key.Rights) + keys = append(keys, keyMap) + } + if err != nil { return err } + d.Set("shared_access_policy", keys) + d.Set("hostname", *properties.HostName) d.Set("etag", *desc.Etag) d.Set("type", *desc.Type) flattenAndSetTags(d, desc.Tags) diff --git a/azurerm/resource_arm_iothub_resource_provider_test.go b/azurerm/resource_arm_iothub_resource_provider_test.go index 67eaefe7e8b0..3a21fd6bbf25 100644 --- a/azurerm/resource_arm_iothub_resource_provider_test.go +++ b/azurerm/resource_arm_iothub_resource_provider_test.go @@ -70,7 +70,6 @@ func testCheckAzureRMIotHubExists(name string) resource.TestCheckFunc { conn := testAccProvider.Meta().(*ArmClient).iothubResourceClient resp, err := conn.Get(resourceGroup, iothubName) - if err != nil { if resp.StatusCode == http.StatusNotFound { return fmt.Errorf("Bad: IotHub %q (resource group: %q) does not exist", iothubName, resourceGroup) From 67469d3284a000c53c37bd3bc8ff28de72147abb Mon Sep 17 00:00:00 2001 From: girishramnani Date: Wed, 11 Oct 2017 14:29:39 +0530 Subject: [PATCH 31/69] resolved a keys struct related bug --- azurerm/resource_arm_iothub_resource_provider.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 643a34f7f9d1..fdeb8a006eb4 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -2,6 +2,7 @@ package azurerm import ( "errors" + "log" "github.com/Azure/azure-sdk-for-go/arm/iothub" "github.com/hashicorp/terraform/helper/schema" @@ -204,9 +205,9 @@ func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { var keys []map[string]interface{} for _, key := range *keysResp.Value { keyMap := make(map[string]interface{}) - keyMap["key_name"] = key.KeyName - keyMap["primary_key"] = key.PrimaryKey - keyMap["secondary_key"] = key.SecondaryKey + keyMap["key_name"] = *key.KeyName + keyMap["primary_key"] = *key.PrimaryKey + keyMap["secondary_key"] = *key.SecondaryKey keyMap["permissions"] = string(key.Rights) keys = append(keys, keyMap) } @@ -214,6 +215,7 @@ func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { if err != nil { return err } + log.Println("[GIRISH]", keys) d.Set("shared_access_policy", keys) d.Set("hostname", *properties.HostName) From 1baeb52cf49e20145a100a8e424c419a2983cfea Mon Sep 17 00:00:00 2001 From: girishramnani Date: Thu, 12 Oct 2017 13:22:25 +0530 Subject: [PATCH 32/69] Added documentation for iothub --- website/azurerm.erb | 11 +++++ website/docs/r/iothub.html.markdown | 66 +++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 website/docs/r/iothub.html.markdown diff --git a/website/azurerm.erb b/website/azurerm.erb index 54532dd8a812..6b507b65ef88 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -536,9 +536,20 @@ + > + IotHub Resources + + +
  • Azure Service Management Provider »
  • + + <% end %> diff --git a/website/docs/r/iothub.html.markdown b/website/docs/r/iothub.html.markdown new file mode 100644 index 000000000000..474a0087e3eb --- /dev/null +++ b/website/docs/r/iothub.html.markdown @@ -0,0 +1,66 @@ +--- +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_iothub" +sidebar_current: "docs-azurerm-resource-iothub" +description: |- + Creates a new IotHub resource +--- + +# azurerm\_iothub + +Creates a new IotHub + +## Example Usage + +```hcl +resource "azurerm_resource_group" "test" { + name = "resourceGroup1" + location = "West US" +} + + +resource "azurerm_iothub" "test" { + name = "test" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "westus" + sku { + name = "S1" + tier = "Standard" + capacity = "1" + } + + tags { + "purpose" = "testing" + } + } + + +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Specifies the name of the IotHub resource. Changing this forces a new resource to be created. + +* `resource_group_name` - (Required) The name of the resource group under which the IotHub resource has to be created. Changing this forces a new resource to be created. + +* `location` - (Required) Specifies the supported Azure location where the resource has to be createc. Changing this forces a new resource to be created. + +* `sku` - (Required) Specifies the capacity and tier of the IotHub. + +* `tags` - (Optional) A mapping of tags to assign to the resource. + +## Attributes Reference + +The following attributes are exported: + +* `id` - The IotHub ID. + +* `etag` - The etag of IotHub Resource. + +* `hostname` - The hostname of the IotHub Resource. + +* `shared_access_policy` - The list of access policy which contain access keys and permissions. + + From a22eeb2d8bd3b85482ecffd16a4a1e3724e4aa87 Mon Sep 17 00:00:00 2001 From: girishramnani Date: Sun, 15 Oct 2017 19:32:10 +0530 Subject: [PATCH 33/69] Added importer in the iothub resource group As the refresh function ( read lifecyle ) of the iothub resource is only dependent on the id of the resource to genarate the state StatePassthrough method is used --- azurerm/resource_arm_iothub_resource_provider.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index fdeb8a006eb4..295065eecc4e 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -15,6 +15,9 @@ func resourceArmIotHub() *schema.Resource { Read: resourceArmIotHubRead, Update: resourceArmIotHubCreateAndUpdate, Delete: resourceArmIotHubDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, Schema: map[string]*schema.Schema{ "name": { From 304b9d2f9a9eb313baaf9493c1803b65437c9795 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Tue, 19 Dec 2017 17:41:51 -0600 Subject: [PATCH 34/69] Iothub consumer group initial commit Signed-off-by: shelley.bess --- azurerm/resource_arm_iothub_consumer_group.go | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 azurerm/resource_arm_iothub_consumer_group.go diff --git a/azurerm/resource_arm_iothub_consumer_group.go b/azurerm/resource_arm_iothub_consumer_group.go new file mode 100644 index 000000000000..9c8aaf8efc02 --- /dev/null +++ b/azurerm/resource_arm_iothub_consumer_group.go @@ -0,0 +1,120 @@ +package azurerm + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmIotHubConsumerGroup() *schema.Resource { + return &schema.Resource{ + Create: resourceArmIotHubConsumerGroupCreate, + Read: resourceArmIotHubConsumerGroupRead, + Delete: resourceArmIotHubConsumerGroupDelete, + + Schema: map[string]*schema.Schema{ + "consumer_group_name": { + Type: schema.TypeString, + Required: true, + }, + "resource_group_name": { + Type: schema.TypeString, + Required: true, + }, + "iotHub_name": { + Type: schema.TypeString, + Required: true, + }, + "event_hub_endpoint": { + Type: schema.TypeString, + Required: true, + }, + }, + } +} + +func resourceArmIotHubConsumerGroupCreate(d *schema.ResourceData, meta interface{}) error { + armClient := meta.(*ArmClient) + iothubClient := armClient.iothubResourceClient + log.Printf("[INFO} preparing arguments for AzureRM IoTHub Consumer Group creation.") + + groupName := d.Get("consumer_group_name").(string) + resourceGroup := d.Get("resource_group_name").(string) + iotHubName := d.Get("iotHub_name").(string) + eventhubEndpoint := d.Get("event_hub_endpoint").(string) + + _, err := iothubClient.CreateEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) + if err != nil { + return err + } + + check, err := iothubClient.GetEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) + if err != nil { + return err + } + + if check.ID == nil { + return fmt.Errorf("Cannot read IoTHub Consumer Group %s (resource group %s) ID", groupName, resourceGroup) + } + + d.SetId(*check.ID) + + return resourceArmIotHubConsumerGroupRead(d, meta) +} + +func resourceArmIotHubConsumerGroupRead(d *schema.ResourceData, meta interface{}) error { + armClient := meta.(*ArmClient) + iothubClient := armClient.iothubResourceClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + + resourceGroup := id.ResourceGroup + groupName := id.Path["consumergroups"] + iotHubName := id.Path["resourcename"] + eventhubEndpoint := id.Path["eventhubs"] + + resp, err := iothubClient.GetEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + d.SetId("") + return nil + } + return fmt.Errorf("Error making read request on Azure IoTHub Consumer Group %s: %+v", groupName, err) + } + + d.Set("consumer_group_name", groupName) + d.Set("resource_group_name", resourceGroup) + d.Set("iotHub_name", iotHubName) + d.Set("event_hub_endpoint", eventhubEndpoint) + + return nil +} + +func resourceArmIotHubConsumerGroupDelete(d *schema.ResourceData, meta interface{}) error { + armClient := meta.(*ArmClient) + iothubClient := armClient.iothubResourceClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + + resourceGroup := id.ResourceGroup + groupName := id.Path["consumergroups"] + iotHubName := id.Path["resourcename"] + eventhubEndpoint := id.Path["eventhubs"] + + resp, err := iothubClient.DeleteEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) + if err != nil { + if !utils.ResponseWasNotFound(resp) { + return fmt.Errorf("Error issuing Azure ARM delete request of IoTHub Consumer Group '%s' : %+v", groupName, err) + } + } + + return nil +} From eeb480440c31330c85ed107358eb2984ee535bb4 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 20 Dec 2017 12:38:24 -0600 Subject: [PATCH 35/69] Initial consumer group test Signed-off-by: shelley.bess --- ...resource_arm_iothub_consumer_group_test.go | 115 ++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 azurerm/resource_arm_iothub_consumer_group_test.go diff --git a/azurerm/resource_arm_iothub_consumer_group_test.go b/azurerm/resource_arm_iothub_consumer_group_test.go new file mode 100644 index 000000000000..2a3b638386a4 --- /dev/null +++ b/azurerm/resource_arm_iothub_consumer_group_test.go @@ -0,0 +1,115 @@ +package azurerm + +import ( + "fmt" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func TestAccAzureRMIotHubConsumerGroup_basic(t *testing.T) { + ri := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestory: testCheckAzureRMIotHubConsumerGroupDestory, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMIotHubConsumerGroupConfig(ri, testLocation()) + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMIotHubConsumerGroupExists("azurerm_iothub_consumer_group.foo"), + ), + }, + }, + }) +} + +func testCheckAzureRMIotHubConsumerGroupExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + groupName := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for IoT Hub Consumer Group: %s", groupName) + } + + conn := testAccProvider.Meta().(*ArmClient).iothubResourceClient + + iotHubName := rs.Primary.Attributes["iothub_name"] + eventhubEndpoint := rs.Primary.Attributes["event_hub_endpoint"] + + resp, err := conn.GetEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) + if err != ;nil { + return fmt.Errorf("Bad: Error on GetEventHubConsumerGroup: %+v", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: IotHub Get Event hub consumer group %q (resource group: %q) does not exist", groupName, resourceGroup) + } + + return nil + } +} + +func testCheckAzureRMIotHubConsumerGroupDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).iothubResourceClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_eventhub_consuemr_group" { + continue + } + + groupName := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + iotHubName := rs.Primary.Attributes["iothub_name"] + eventhubEndpoint := rs.Primary.Attributes["event_hub_endpoint"] + + resp, err := conn.GetEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("IoTHub endpoint consumer group still exists: %q", groupName) + } + } + + return nil +} + +func testAccAzureRMIotHubConsumerGroupConfig(rInt int, location string) string { + return fmt.Sprintf(' +resource "azurerm_resource_group" "foo" { + name = "acctestIot-%d" + location = "%s" +} + +resource "azurerm_iothub" "bar" { + name = "acctestiothub-%d" + location = "${azurerm_resource_group.foo.location}" + resource_group_name = "${azurerm_resource_group.foo.name}" + sku { + name = "S1" + tier = "Standard" + capacity = "1" + } + + tags { + "purpose" = "testing" + } +} + +resource "azurerm_iothub_consumer_group" "foo" { + name = "acctestiothubgroup-%d" + resource_group_name = "${azurerm_resource_group.foo.location}" + iothub_name = "${azurerm_iothub.bar.name}" + event_hub_endpoint = "test" +} + +} From 7be2c547178d4bc243d8c740e33a59c32fca22e0 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 20 Dec 2017 12:42:31 -0600 Subject: [PATCH 36/69] Fixed schema Signed-off-by: shelley.bess --- azurerm/resource_arm_iothub_consumer_group.go | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/azurerm/resource_arm_iothub_consumer_group.go b/azurerm/resource_arm_iothub_consumer_group.go index 9c8aaf8efc02..2a7e09010bac 100644 --- a/azurerm/resource_arm_iothub_consumer_group.go +++ b/azurerm/resource_arm_iothub_consumer_group.go @@ -15,15 +15,12 @@ func resourceArmIotHubConsumerGroup() *schema.Resource { Delete: resourceArmIotHubConsumerGroupDelete, Schema: map[string]*schema.Schema{ - "consumer_group_name": { + "name": { Type: schema.TypeString, Required: true, }, - "resource_group_name": { - Type: schema.TypeString, - Required: true, - }, - "iotHub_name": { + "resource_group_name": resourceGroupNameSchema(), + "iothub_name": { Type: schema.TypeString, Required: true, }, @@ -40,9 +37,9 @@ func resourceArmIotHubConsumerGroupCreate(d *schema.ResourceData, meta interface iothubClient := armClient.iothubResourceClient log.Printf("[INFO} preparing arguments for AzureRM IoTHub Consumer Group creation.") - groupName := d.Get("consumer_group_name").(string) + groupName := d.Get("name").(string) resourceGroup := d.Get("resource_group_name").(string) - iotHubName := d.Get("iotHub_name").(string) + iotHubName := d.Get("iothub_name").(string) eventhubEndpoint := d.Get("event_hub_endpoint").(string) _, err := iothubClient.CreateEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) @@ -87,9 +84,9 @@ func resourceArmIotHubConsumerGroupRead(d *schema.ResourceData, meta interface{} return fmt.Errorf("Error making read request on Azure IoTHub Consumer Group %s: %+v", groupName, err) } - d.Set("consumer_group_name", groupName) + d.Set("name", groupName) d.Set("resource_group_name", resourceGroup) - d.Set("iotHub_name", iotHubName) + d.Set("iothub_name", iotHubName) d.Set("event_hub_endpoint", eventhubEndpoint) return nil From 6b694227b3f81a30a0727ed400012eac5add0e26 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 20 Dec 2017 12:45:04 -0600 Subject: [PATCH 37/69] Modified configuration Signed-off-by: shelley.bess --- azurerm/resource_arm_iothub_consumer_group_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/azurerm/resource_arm_iothub_consumer_group_test.go b/azurerm/resource_arm_iothub_consumer_group_test.go index 2a3b638386a4..a7a105611d87 100644 --- a/azurerm/resource_arm_iothub_consumer_group_test.go +++ b/azurerm/resource_arm_iothub_consumer_group_test.go @@ -111,5 +111,6 @@ resource "azurerm_iothub_consumer_group" "foo" { iothub_name = "${azurerm_iothub.bar.name}" event_hub_endpoint = "test" } +', rInt, location, rInt, rInt) } From faf8e4bb73c3e6e8b74789e5e8b9ab3613fa3828 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 20 Dec 2017 13:18:08 -0600 Subject: [PATCH 38/69] Iothub consumer group documentation Signed-off-by: shelley.bess --- website/azurerm.erb | 5 +- .../r/iothub_consumer_group.html.markdown | 63 +++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 website/docs/r/iothub_consumer_group.html.markdown diff --git a/website/azurerm.erb b/website/azurerm.erb index 6b507b65ef88..2b2d73367041 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -540,7 +540,10 @@ IotHub Resources diff --git a/website/docs/r/iothub_consumer_group.html.markdown b/website/docs/r/iothub_consumer_group.html.markdown new file mode 100644 index 000000000000..adc79cf29ebd --- /dev/null +++ b/website/docs/r/iothub_consumer_group.html.markdown @@ -0,0 +1,63 @@ +--- +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_iothub_consumer_group" +sidebar_current: "docs-azurerm-resource-iothub-consumer-group" +description: |- + Adds a consumer group to an Event Hub-compatible endpoint in an IoT hub. +--- + +# azurerm\_iothub\_consumer\_group + +Creates a new consumer group + +## Example Usage + +```hcl +resource "azurerm_resource_group" "foo" { + name = "acctestIot-%d" + location = "%s" +} + +resource "azurerm_iothub" "bar" { + name = "acctestiothub-%d" + location = "${azurerm_resource_group.foo.location}" + resource_group_name = "${azurerm_resource_group.foo.name}" + sku { + name = "S1" + tier = "Standard" + capacity = "1" + } + + tags { + "purpose" = "testing" + } +} + +resource "azurerm_iothub_consumer_group" "foo" { + name = "acctestiothubgroup-%d" + resource_group_name = "${azurerm_resource_group.foo.location}" + iothub_name = "${azurerm_iothub.bar.name}" + event_hub_endpoint = "test" +} + + +``` + +## Argument Reference + +The following arguments are supported: + +* `name` (Required) Specifies the name of the Consumer Group resource. Changing this forces a new resource to be created. + +* `resource_group_name` (Required) The name of the resource group that contains the IoT hub. + +* `iothub_name` (Required) The name of the IoT hub. + +* `event_hub_endpoint` (Required) The name of the Event Hub-compatible endpoint in the IoT hub. + +## Attributes Reference + +The following attributes are exported: + +WIP + From 93c02b549ee58437b5d4d0361a00a5f3aa5c6309 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 20 Dec 2017 13:30:17 -0600 Subject: [PATCH 39/69] Added resource to provider Signed-off-by: shelley.bess --- azurerm/provider.go | 1 + 1 file changed, 1 insertion(+) diff --git a/azurerm/provider.go b/azurerm/provider.go index e0e019ba609b..e297c88ea469 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -170,6 +170,7 @@ func Provider() terraform.ResourceProvider { "azurerm_virtual_network": resourceArmVirtualNetwork(), "azurerm_virtual_network_peering": resourceArmVirtualNetworkPeering(), "azurerm_iothub": resourceArmIotHub(), + "azurerm_iothub_consumer_group": resourceArmIotHubConsumerGroup(), }, } From 8e38252ff6f9f566451bf51ac488deec3b96c35c Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 20 Dec 2017 13:40:23 -0600 Subject: [PATCH 40/69] Revised schema Signed-off-by: shelley.bess --- azurerm/resource_arm_iothub_consumer_group.go | 6 ++--- ...resource_arm_iothub_consumer_group_test.go | 6 ++--- .../r/iothub_consumer_group.html.markdown | 22 +++++++++---------- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/azurerm/resource_arm_iothub_consumer_group.go b/azurerm/resource_arm_iothub_consumer_group.go index 2a7e09010bac..8e92bc745f8f 100644 --- a/azurerm/resource_arm_iothub_consumer_group.go +++ b/azurerm/resource_arm_iothub_consumer_group.go @@ -20,7 +20,7 @@ func resourceArmIotHubConsumerGroup() *schema.Resource { Required: true, }, "resource_group_name": resourceGroupNameSchema(), - "iothub_name": { + "iot_hub_name": { Type: schema.TypeString, Required: true, }, @@ -39,7 +39,7 @@ func resourceArmIotHubConsumerGroupCreate(d *schema.ResourceData, meta interface groupName := d.Get("name").(string) resourceGroup := d.Get("resource_group_name").(string) - iotHubName := d.Get("iothub_name").(string) + iotHubName := d.Get("iot_hub_name").(string) eventhubEndpoint := d.Get("event_hub_endpoint").(string) _, err := iothubClient.CreateEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) @@ -86,7 +86,7 @@ func resourceArmIotHubConsumerGroupRead(d *schema.ResourceData, meta interface{} d.Set("name", groupName) d.Set("resource_group_name", resourceGroup) - d.Set("iothub_name", iotHubName) + d.Set("iot_hub_name", iotHubName) d.Set("event_hub_endpoint", eventhubEndpoint) return nil diff --git a/azurerm/resource_arm_iothub_consumer_group_test.go b/azurerm/resource_arm_iothub_consumer_group_test.go index a7a105611d87..c7e11125a167 100644 --- a/azurerm/resource_arm_iothub_consumer_group_test.go +++ b/azurerm/resource_arm_iothub_consumer_group_test.go @@ -41,7 +41,7 @@ func testCheckAzureRMIotHubConsumerGroupExists(name string) resource.TestCheckFu conn := testAccProvider.Meta().(*ArmClient).iothubResourceClient - iotHubName := rs.Primary.Attributes["iothub_name"] + iotHubName := rs.Primary.Attributes["iot_hub_name"] eventhubEndpoint := rs.Primary.Attributes["event_hub_endpoint"] resp, err := conn.GetEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) @@ -67,7 +67,7 @@ func testCheckAzureRMIotHubConsumerGroupDestroy(s *terraform.State) error { groupName := rs.Primary.Attributes["name"] resourceGroup := rs.Primary.Attributes["resource_group_name"] - iotHubName := rs.Primary.Attributes["iothub_name"] + iotHubName := rs.Primary.Attributes["iot_hub_name"] eventhubEndpoint := rs.Primary.Attributes["event_hub_endpoint"] resp, err := conn.GetEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) @@ -108,7 +108,7 @@ resource "azurerm_iothub" "bar" { resource "azurerm_iothub_consumer_group" "foo" { name = "acctestiothubgroup-%d" resource_group_name = "${azurerm_resource_group.foo.location}" - iothub_name = "${azurerm_iothub.bar.name}" + iot_hub_name = "${azurerm_iothub.bar.name}" event_hub_endpoint = "test" } ', rInt, location, rInt, rInt) diff --git a/website/docs/r/iothub_consumer_group.html.markdown b/website/docs/r/iothub_consumer_group.html.markdown index adc79cf29ebd..727a82047504 100644 --- a/website/docs/r/iothub_consumer_group.html.markdown +++ b/website/docs/r/iothub_consumer_group.html.markdown @@ -13,15 +13,15 @@ Creates a new consumer group ## Example Usage ```hcl -resource "azurerm_resource_group" "foo" { +resource "azurerm_resource_group" "test" { name = "acctestIot-%d" - location = "%s" + location = "West US" } -resource "azurerm_iothub" "bar" { - name = "acctestiothub-%d" - location = "${azurerm_resource_group.foo.location}" - resource_group_name = "${azurerm_resource_group.foo.name}" +resource "azurerm_iothub" "test" { + name = "test" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" sku { name = "S1" tier = "Standard" @@ -33,10 +33,10 @@ resource "azurerm_iothub" "bar" { } } -resource "azurerm_iothub_consumer_group" "foo" { - name = "acctestiothubgroup-%d" - resource_group_name = "${azurerm_resource_group.foo.location}" - iothub_name = "${azurerm_iothub.bar.name}" +resource "azurerm_iothub_consumer_group" "test" { + name = "test" + resource_group_name = "${azurerm_resource_group.test.location}" + iot_hub_name = "${azurerm_iothub.test.name}" event_hub_endpoint = "test" } @@ -51,7 +51,7 @@ The following arguments are supported: * `resource_group_name` (Required) The name of the resource group that contains the IoT hub. -* `iothub_name` (Required) The name of the IoT hub. +* `iot_hub_name` (Required) The name of the IoT hub. * `event_hub_endpoint` (Required) The name of the Event Hub-compatible endpoint in the IoT hub. From 60cd688486d722c6c36a4ee7155f24252405c0d8 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 20 Dec 2017 15:37:54 -0600 Subject: [PATCH 41/69] Modifications for acceptance tests Signed-off-by: shelley.bess --- azurerm/resource_arm_iothub_consumer_group.go | 6 ++++-- ...resource_arm_iothub_consumer_group_test.go | 20 ++++++++++--------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/azurerm/resource_arm_iothub_consumer_group.go b/azurerm/resource_arm_iothub_consumer_group.go index 8e92bc745f8f..e28d9cb0cf6a 100644 --- a/azurerm/resource_arm_iothub_consumer_group.go +++ b/azurerm/resource_arm_iothub_consumer_group.go @@ -10,14 +10,16 @@ import ( func resourceArmIotHubConsumerGroup() *schema.Resource { return &schema.Resource{ - Create: resourceArmIotHubConsumerGroupCreate, + Create: resourceArmIotHubConsumerGroupCreateUpdate, Read: resourceArmIotHubConsumerGroupRead, + Update: resourceArmIotHubConsumerGroupCreateUpdate, Delete: resourceArmIotHubConsumerGroupDelete, Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, Required: true, + ForceNew: true, }, "resource_group_name": resourceGroupNameSchema(), "iot_hub_name": { @@ -32,7 +34,7 @@ func resourceArmIotHubConsumerGroup() *schema.Resource { } } -func resourceArmIotHubConsumerGroupCreate(d *schema.ResourceData, meta interface{}) error { +func resourceArmIotHubConsumerGroupCreateUpdate(d *schema.ResourceData, meta interface{}) error { armClient := meta.(*ArmClient) iothubClient := armClient.iothubResourceClient log.Printf("[INFO} preparing arguments for AzureRM IoTHub Consumer Group creation.") diff --git a/azurerm/resource_arm_iothub_consumer_group_test.go b/azurerm/resource_arm_iothub_consumer_group_test.go index c7e11125a167..9fd3ac14e0e8 100644 --- a/azurerm/resource_arm_iothub_consumer_group_test.go +++ b/azurerm/resource_arm_iothub_consumer_group_test.go @@ -2,22 +2,24 @@ package azurerm import ( "fmt" + "net/http" + "testing" "github.com/hashicorp/terraform/helper/acctest" - "github.com/hashicorp/terraform/helper/schema" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" ) func TestAccAzureRMIotHubConsumerGroup_basic(t *testing.T) { ri := acctest.RandInt() resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestory: testCheckAzureRMIotHubConsumerGroupDestory, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMIotHubConsumerGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMIotHubConsumerGroupConfig(ri, testLocation()) + Config: testAccAzureRMIotHubConsumerGroupConfig(ri, testLocation()), Check: resource.ComposeTestCheckFunc( testCheckAzureRMIotHubConsumerGroupExists("azurerm_iothub_consumer_group.foo"), ), @@ -45,7 +47,7 @@ func testCheckAzureRMIotHubConsumerGroupExists(name string) resource.TestCheckFu eventhubEndpoint := rs.Primary.Attributes["event_hub_endpoint"] resp, err := conn.GetEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) - if err != ;nil { + if err != nil { return fmt.Errorf("Bad: Error on GetEventHubConsumerGroup: %+v", err) } @@ -84,7 +86,7 @@ func testCheckAzureRMIotHubConsumerGroupDestroy(s *terraform.State) error { } func testAccAzureRMIotHubConsumerGroupConfig(rInt int, location string) string { - return fmt.Sprintf(' + return fmt.Sprintf(` resource "azurerm_resource_group" "foo" { name = "acctestIot-%d" location = "%s" @@ -111,6 +113,6 @@ resource "azurerm_iothub_consumer_group" "foo" { iot_hub_name = "${azurerm_iothub.bar.name}" event_hub_endpoint = "test" } -', rInt, location, rInt, rInt) +`, rInt, location, rInt, rInt) } From 0c2e6aafd710e9fe7024b76e0f64f43a10c0f15d Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Fri, 22 Dec 2017 14:48:07 -0600 Subject: [PATCH 42/69] Corrected config Signed-off-by: shelley.bess --- azurerm/config.go | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/azurerm/config.go b/azurerm/config.go index 54c77c37838d..fd44660c2988 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -652,21 +652,13 @@ func (c *Config) getArmClient() (*ArmClient, error) { aschc.Sender = sender client.automationScheduleClient = aschc -<<<<<<< HEAD - client.registerAuthentication(endpoint, graphEndpoint, c.SubscriptionID, c.TenantID, auth, graphAuth, sender) -||||||| merged common ancestors - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - -======= ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) setUserAgent(&ihrc.Client) ihrc.Authorizer = auth ihrc.Sender = autorest.CreateSender(withRequestLogging()) client.iothubResourceClient = ihrc - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - ->>>>>>> added the config and cleaned up the schema iothub resource schema + client.registerAuthentication(endpoint, graphEndpoint, c.SubscriptionID, c.TenantID, auth, graphAuth, sender) client.registerDatabases(endpoint, c.SubscriptionID, auth, sender) client.registerDisks(endpoint, c.SubscriptionID, auth, sender) client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) From 79cfb285f09dc5e17281070e384749962dd98a59 Mon Sep 17 00:00:00 2001 From: "luke.peterson" Date: Fri, 22 Dec 2017 21:33:53 +0000 Subject: [PATCH 43/69] Delete config_REMOTE_7053.go --- azurerm/#*merge*#7131zEX# | 904 ----------------- azurerm/config.go | 17 - azurerm/config.go.orig | 905 ------------------ azurerm/config_BACKUP_7053.go | 905 ------------------ azurerm/config_BASE_7053.go | 895 ----------------- azurerm/config_LOCAL_7053.go | 904 ----------------- azurerm/config_REMOTE_7053.go | 887 ----------------- azurerm/provider.go | 3 - azurerm/resource_arm_iothub_consumer_group.go | 36 +- 9 files changed, 2 insertions(+), 5454 deletions(-) delete mode 100644 azurerm/#*merge*#7131zEX# delete mode 100644 azurerm/config.go.orig delete mode 100644 azurerm/config_BACKUP_7053.go delete mode 100644 azurerm/config_BASE_7053.go delete mode 100644 azurerm/config_LOCAL_7053.go delete mode 100644 azurerm/config_REMOTE_7053.go diff --git a/azurerm/#*merge*#7131zEX# b/azurerm/#*merge*#7131zEX# deleted file mode 100644 index 7b69c24fd47a..000000000000 --- a/azurerm/#*merge*#7131zEX# +++ /dev/null @@ -1,904 +0,0 @@ -package azurerm - -import ( - "context" - "fmt" - "log" - "net/http" - "net/http/httputil" - - "github.com/Azure/azure-sdk-for-go/arm/iothub" - - "github.com/Azure/azure-sdk-for-go/arm/appinsights" - "github.com/Azure/azure-sdk-for-go/arm/authorization" - "github.com/Azure/azure-sdk-for-go/arm/automation" - "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/containerinstance" - "github.com/Azure/azure-sdk-for-go/arm/containerregistry" - "github.com/Azure/azure-sdk-for-go/arm/containerservice" - "github.com/Azure/azure-sdk-for-go/arm/cosmos-db" - "github.com/Azure/azure-sdk-for-go/arm/disk" - "github.com/Azure/azure-sdk-for-go/arm/dns" - "github.com/Azure/azure-sdk-for-go/arm/eventgrid" - "github.com/Azure/azure-sdk-for-go/arm/eventhub" - "github.com/Azure/azure-sdk-for-go/arm/graphrbac" - "github.com/Azure/azure-sdk-for-go/arm/keyvault" - "github.com/Azure/azure-sdk-for-go/arm/mysql" - "github.com/Azure/azure-sdk-for-go/arm/network" - "github.com/Azure/azure-sdk-for-go/arm/operationalinsights" - "github.com/Azure/azure-sdk-for-go/arm/postgresql" - "github.com/Azure/azure-sdk-for-go/arm/redis" - "github.com/Azure/azure-sdk-for-go/arm/resources/resources" - "github.com/Azure/azure-sdk-for-go/arm/resources/subscriptions" - "github.com/Azure/azure-sdk-for-go/arm/scheduler" - "github.com/Azure/azure-sdk-for-go/arm/search" - "github.com/Azure/azure-sdk-for-go/arm/servicebus" - "github.com/Azure/azure-sdk-for-go/arm/sql" - "github.com/Azure/azure-sdk-for-go/arm/storage" - "github.com/Azure/azure-sdk-for-go/arm/trafficmanager" - "github.com/Azure/azure-sdk-for-go/arm/web" - keyVault "github.com/Azure/azure-sdk-for-go/dataplane/keyvault" - mainStorage "github.com/Azure/azure-sdk-for-go/storage" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/hashicorp/terraform/terraform" -) - -// ArmClient contains the handles to all the specific Azure Resource Manager -// resource classes' respective clients. -type ArmClient struct { - clientId string - tenantId string - subscriptionId string - usingServicePrincipal bool - environment azure.Environment - - StopContext context.Context - - availSetClient compute.AvailabilitySetsClient - usageOpsClient compute.UsageClient - vmExtensionImageClient compute.VirtualMachineExtensionImagesClient - vmExtensionClient compute.VirtualMachineExtensionsClient - vmScaleSetClient compute.VirtualMachineScaleSetsClient - vmImageClient compute.VirtualMachineImagesClient - vmClient compute.VirtualMachinesClient - imageClient compute.ImagesClient - - diskClient disk.DisksClient - snapshotsClient disk.SnapshotsClient - cosmosDBClient cosmosdb.DatabaseAccountsClient - automationAccountClient automation.AccountClient - automationRunbookClient automation.RunbookClient - automationCredentialClient automation.CredentialClient - automationScheduleClient automation.ScheduleClient - - appGatewayClient network.ApplicationGatewaysClient - ifaceClient network.InterfacesClient - expressRouteCircuitClient network.ExpressRouteCircuitsClient - loadBalancerClient network.LoadBalancersClient - localNetConnClient network.LocalNetworkGatewaysClient - publicIPClient network.PublicIPAddressesClient - secGroupClient network.SecurityGroupsClient - secRuleClient network.SecurityRulesClient - subnetClient network.SubnetsClient - netUsageClient network.UsagesClient - vnetGatewayConnectionsClient network.VirtualNetworkGatewayConnectionsClient - vnetGatewayClient network.VirtualNetworkGatewaysClient - vnetClient network.VirtualNetworksClient - vnetPeeringsClient network.VirtualNetworkPeeringsClient - routeTablesClient network.RouteTablesClient - routesClient network.RoutesClient - dnsClient dns.RecordSetsClient - zonesClient dns.ZonesClient - - cdnProfilesClient cdn.ProfilesClient - cdnEndpointsClient cdn.EndpointsClient - - containerRegistryClient containerregistry.RegistriesClient - containerServicesClient containerservice.ContainerServicesClient - containerGroupsClient containerinstance.ContainerGroupsClient - - eventGridTopicsClient eventgrid.TopicsClient - eventHubClient eventhub.EventHubsClient - eventHubConsumerGroupClient eventhub.ConsumerGroupsClient - eventHubNamespacesClient eventhub.NamespacesClient - - workspacesClient operationalinsights.WorkspacesClient - - providers resources.ProvidersClient - resourceGroupClient resources.GroupsClient - tagsClient resources.TagsClient - resourceFindClient resources.GroupClient - - subscriptionsGroupClient subscriptions.GroupClient - - jobsClient scheduler.JobsClient - jobsCollectionsClient scheduler.JobCollectionsClient - - storageServiceClient storage.AccountsClient - storageUsageClient storage.UsageClient - - deploymentsClient resources.DeploymentsClient - - redisClient redis.GroupClient - - trafficManagerProfilesClient trafficmanager.ProfilesClient - trafficManagerEndpointsClient trafficmanager.EndpointsClient - - searchServicesClient search.ServicesClient - serviceBusNamespacesClient servicebus.NamespacesClient - serviceBusQueuesClient servicebus.QueuesClient - serviceBusTopicsClient servicebus.TopicsClient - serviceBusSubscriptionsClient servicebus.SubscriptionsClient - - keyVaultClient keyvault.VaultsClient - keyVaultManagementClient keyVault.ManagementClient - - appServicePlansClient web.AppServicePlansClient - appServicesClient web.AppsClient - - appInsightsClient appinsights.ComponentsClient - - // Authentication - roleAssignmentsClient authorization.RoleAssignmentsClient - roleDefinitionsClient authorization.RoleDefinitionsClient - servicePrincipalsClient graphrbac.ServicePrincipalsClient - - // Databases - mysqlConfigurationsClient mysql.ConfigurationsClient - mysqlDatabasesClient mysql.DatabasesClient - mysqlFirewallRulesClient mysql.FirewallRulesClient - mysqlServersClient mysql.ServersClient - postgresqlConfigurationsClient postgresql.ConfigurationsClient - postgresqlDatabasesClient postgresql.DatabasesClient - postgresqlFirewallRulesClient postgresql.FirewallRulesClient - postgresqlServersClient postgresql.ServersClient - sqlDatabasesClient sql.DatabasesClient - sqlElasticPoolsClient sql.ElasticPoolsClient - sqlFirewallRulesClient sql.FirewallRulesClient - sqlServersClient sql.ServersClient - iothubResourceClient iothub.ResourceClient -} - -func withRequestLogging() autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - // dump request to wire format - if dump, err := httputil.DumpRequestOut(r, true); err == nil { - log.Printf("[DEBUG] AzureRM Request: \n%s\n", dump) - } else { - // fallback to basic message - log.Printf("[DEBUG] AzureRM Request: %s to %s\n", r.Method, r.URL) - } - - resp, err := s.Do(r) - if resp != nil { - // dump response to wire format - if dump, err := httputil.DumpResponse(resp, true); err == nil { - log.Printf("[DEBUG] AzureRM Response for %s: \n%s\n", r.URL, dump) - } else { - // fallback to basic message - log.Printf("[DEBUG] AzureRM Response: %s for %s\n", resp.Status, r.URL) - } - } else { - log.Printf("[DEBUG] Request to %s completed with no response", r.URL) - } - return resp, err - }) - } -} - -func setUserAgent(client *autorest.Client) { - version := terraform.VersionString() - client.UserAgent = fmt.Sprintf("HashiCorp-Terraform-v%s", version) -} - -func (c *Config) getAuthorizationToken(oauthConfig *adal.OAuthConfig, endpoint string) (*autorest.BearerAuthorizer, error) { - useServicePrincipal := c.ClientSecret != "" - - if useServicePrincipal { - spt, err := adal.NewServicePrincipalToken(*oauthConfig, c.ClientID, c.ClientSecret, endpoint) - if err != nil { - return nil, err - } - - auth := autorest.NewBearerAuthorizer(spt) - return auth, nil - } - - if c.IsCloudShell { - // load the refreshed tokens from the Azure CLI - err := c.LoadTokensFromAzureCLI() - if err != nil { - return nil, fmt.Errorf("Error loading the refreshed CloudShell tokens: %+v", err) - } - } - - spt, err := adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, c.ClientID, endpoint, *c.AccessToken) - if err != nil { - return nil, err - } - - auth := autorest.NewBearerAuthorizer(spt) - return auth, nil -} - -// getArmClient is a helper method which returns a fully instantiated -// *ArmClient based on the Config's current settings. -func (c *Config) getArmClient() (*ArmClient, error) { - // detect cloud from environment - env, envErr := azure.EnvironmentFromName(c.Environment) - if envErr != nil { - // try again with wrapped value to support readable values like german instead of AZUREGERMANCLOUD - wrapped := fmt.Sprintf("AZURE%sCLOUD", c.Environment) - var innerErr error - if env, innerErr = azure.EnvironmentFromName(wrapped); innerErr != nil { - return nil, envErr - } - } - - // client declarations: - client := ArmClient{ - clientId: c.ClientID, - tenantId: c.TenantID, - subscriptionId: c.SubscriptionID, - environment: env, - usingServicePrincipal: c.ClientSecret != "", - } - - oauthConfig, err := adal.NewOAuthConfig(env.ActiveDirectoryEndpoint, c.TenantID) - if err != nil { - return nil, err - } - - // OAuthConfigForTenant returns a pointer, which can be nil. - if oauthConfig == nil { - return nil, fmt.Errorf("Unable to configure OAuthConfig for tenant %s", c.TenantID) - } - - sender := autorest.CreateSender(withRequestLogging()) - - // Resource Manager endpoints - endpoint := env.ResourceManagerEndpoint - auth, err := c.getAuthorizationToken(oauthConfig, endpoint) - if err != nil { - return nil, err - } - - // Graph Endpoints - graphEndpoint := env.GraphEndpoint - graphAuth, err := c.getAuthorizationToken(oauthConfig, graphEndpoint) - if err != nil { - return nil, err - } - - // Key Vault Endpoints - keyVaultAuth := autorest.NewBearerAuthorizerCallback(sender, func(tenantID, resource string) (*autorest.BearerAuthorizer, error) { - keyVaultSpt, err := c.getAuthorizationToken(oauthConfig, resource) - if err != nil { - return nil, err - } - - return keyVaultSpt, nil - }) - - // NOTE: these declarations should be left separate for clarity should the - // clients be wished to be configured with custom Responders/PollingModes etc... - asc := compute.NewAvailabilitySetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&asc.Client) - asc.Authorizer = auth - asc.Sender = sender - client.availSetClient = asc - - uoc := compute.NewUsageClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&uoc.Client) - uoc.Authorizer = auth - uoc.Sender = sender - client.usageOpsClient = uoc - - vmeic := compute.NewVirtualMachineExtensionImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmeic.Client) - vmeic.Authorizer = auth - vmeic.Sender = sender - client.vmExtensionImageClient = vmeic - - vmec := compute.NewVirtualMachineExtensionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmec.Client) - vmec.Authorizer = auth - vmec.Sender = sender - client.vmExtensionClient = vmec - - vmic := compute.NewVirtualMachineImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmic.Client) - vmic.Authorizer = auth - vmic.Sender = sender - client.vmImageClient = vmic - - vmssc := compute.NewVirtualMachineScaleSetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmssc.Client) - vmssc.Authorizer = auth - vmssc.Sender = sender - client.vmScaleSetClient = vmssc - - vmc := compute.NewVirtualMachinesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmc.Client) - vmc.Authorizer = auth - vmc.Sender = sender - client.vmClient = vmc - - agc := network.NewApplicationGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&agc.Client) - agc.Authorizer = auth - agc.Sender = sender - client.appGatewayClient = agc - - crc := containerregistry.NewRegistriesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&crc.Client) - crc.Authorizer = auth - crc.Sender = sender - client.containerRegistryClient = crc - - csc := containerservice.NewContainerServicesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&csc.Client) - csc.Authorizer = auth - csc.Sender = sender - client.containerServicesClient = csc - - cgc := containerinstance.NewContainerGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cgc.Client) - cgc.Authorizer = auth - cgc.Sender = autorest.CreateSender(withRequestLogging()) - client.containerGroupsClient = cgc - - cdb := cosmosdb.NewDatabaseAccountsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cdb.Client) - cdb.Authorizer = auth - cdb.Sender = sender - client.cosmosDBClient = cdb - - img := compute.NewImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&img.Client) - img.Authorizer = auth - img.Sender = sender - client.imageClient = img - - egtc := eventgrid.NewTopicsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&egtc.Client) - egtc.Authorizer = auth - egtc.Sender = sender - client.eventGridTopicsClient = egtc - - ehc := eventhub.NewEventHubsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ehc.Client) - ehc.Authorizer = auth - ehc.Sender = sender - client.eventHubClient = ehc - - chcgc := eventhub.NewConsumerGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&chcgc.Client) - chcgc.Authorizer = auth - chcgc.Sender = sender - client.eventHubConsumerGroupClient = chcgc - - ehnc := eventhub.NewNamespacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ehnc.Client) - ehnc.Authorizer = auth - ehnc.Sender = sender - client.eventHubNamespacesClient = ehnc - - ifc := network.NewInterfacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ifc.Client) - ifc.Authorizer = auth - ifc.Sender = sender - client.ifaceClient = ifc - - erc := network.NewExpressRouteCircuitsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&erc.Client) - erc.Authorizer = auth - erc.Sender = sender - client.expressRouteCircuitClient = erc - - lbc := network.NewLoadBalancersClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&lbc.Client) - lbc.Authorizer = auth - lbc.Sender = sender - client.loadBalancerClient = lbc - - lgc := network.NewLocalNetworkGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&lgc.Client) - lgc.Authorizer = auth - lgc.Sender = sender - client.localNetConnClient = lgc - - opwc := operationalinsights.NewWorkspacesClient(c.SubscriptionID) - setUserAgent(&opwc.Client) - opwc.Authorizer = auth - opwc.Sender = autorest.CreateSender(withRequestLogging()) - client.workspacesClient = opwc - - pipc := network.NewPublicIPAddressesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&pipc.Client) - pipc.Authorizer = auth - pipc.Sender = sender - client.publicIPClient = pipc - - sgc := network.NewSecurityGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sgc.Client) - sgc.Authorizer = auth - sgc.Sender = sender - client.secGroupClient = sgc - - src := network.NewSecurityRulesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&src.Client) - src.Authorizer = auth - src.Sender = sender - client.secRuleClient = src - - snc := network.NewSubnetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&snc.Client) - snc.Authorizer = auth - snc.Sender = sender - client.subnetClient = snc - - vgcc := network.NewVirtualNetworkGatewayConnectionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vgcc.Client) - vgcc.Authorizer = auth - vgcc.Sender = sender - client.vnetGatewayConnectionsClient = vgcc - - vgc := network.NewVirtualNetworkGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vgc.Client) - vgc.Authorizer = auth - vgc.Sender = sender - client.vnetGatewayClient = vgc - - vnc := network.NewVirtualNetworksClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vnc.Client) - vnc.Authorizer = auth - vnc.Sender = sender - client.vnetClient = vnc - - vnpc := network.NewVirtualNetworkPeeringsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vnpc.Client) - vnpc.Authorizer = auth - vnpc.Sender = sender - client.vnetPeeringsClient = vnpc - - rtc := network.NewRouteTablesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rtc.Client) - rtc.Authorizer = auth - rtc.Sender = sender - client.routeTablesClient = rtc - - rc := network.NewRoutesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rc.Client) - rc.Authorizer = auth - rc.Sender = sender - client.routesClient = rc - - dn := dns.NewRecordSetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&dn.Client) - dn.Authorizer = auth - dn.Sender = sender - client.dnsClient = dn - - zo := dns.NewZonesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&zo.Client) - zo.Authorizer = auth - zo.Sender = sender - client.zonesClient = zo - - rgc := resources.NewGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rgc.Client) - rgc.Authorizer = auth - rgc.Sender = sender - client.resourceGroupClient = rgc - - pc := resources.NewProvidersClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&pc.Client) - pc.Authorizer = auth - pc.Sender = sender - client.providers = pc - - tc := resources.NewTagsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tc.Client) - tc.Authorizer = auth - tc.Sender = sender - client.tagsClient = tc - - rf := resources.NewGroupClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rf.Client) - rf.Authorizer = auth - rf.Sender = sender - client.resourceFindClient = rf - - subgc := subscriptions.NewGroupClientWithBaseURI(endpoint) - setUserAgent(&subgc.Client) - subgc.Authorizer = auth - subgc.Sender = sender - client.subscriptionsGroupClient = subgc - - jc := scheduler.NewJobsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&jc.Client) - jc.Authorizer = auth - jc.Sender = sender - client.jobsClient = jc - - jcc := scheduler.NewJobCollectionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&jcc.Client) - jcc.Authorizer = auth - jcc.Sender = sender - client.jobsCollectionsClient = jcc - - ssc := storage.NewAccountsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ssc.Client) - ssc.Authorizer = auth - ssc.Sender = sender - client.storageServiceClient = ssc - - suc := storage.NewUsageClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&suc.Client) - suc.Authorizer = auth - suc.Sender = sender - client.storageUsageClient = suc - - cpc := cdn.NewProfilesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cpc.Client) - cpc.Authorizer = auth - cpc.Sender = sender - client.cdnProfilesClient = cpc - - cec := cdn.NewEndpointsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cec.Client) - cec.Authorizer = auth - cec.Sender = sender - client.cdnEndpointsClient = cec - - dc := resources.NewDeploymentsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&dc.Client) - dc.Authorizer = auth - dc.Sender = sender - client.deploymentsClient = dc - - tmpc := trafficmanager.NewProfilesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tmpc.Client) - tmpc.Authorizer = auth - tmpc.Sender = sender - client.trafficManagerProfilesClient = tmpc - - tmec := trafficmanager.NewEndpointsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tmec.Client) - tmec.Authorizer = auth - tmec.Sender = sender - client.trafficManagerEndpointsClient = tmec - - rdc := redis.NewGroupClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rdc.Client) - rdc.Authorizer = auth - rdc.Sender = sender - client.redisClient = rdc - - sesc := search.NewServicesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sesc.Client) - sesc.Authorizer = auth - sesc.Sender = sender - client.searchServicesClient = sesc - - sbnc := servicebus.NewNamespacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbnc.Client) - sbnc.Authorizer = auth - sbnc.Sender = sender - client.serviceBusNamespacesClient = sbnc - - sbqc := servicebus.NewQueuesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbqc.Client) - sbqc.Authorizer = auth - sbqc.Sender = sender - client.serviceBusQueuesClient = sbqc - - sbtc := servicebus.NewTopicsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbtc.Client) - sbtc.Authorizer = auth - sbtc.Sender = sender - client.serviceBusTopicsClient = sbtc - - sbsc := servicebus.NewSubscriptionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbsc.Client) - sbsc.Authorizer = auth - sbsc.Sender = sender - client.serviceBusSubscriptionsClient = sbsc - - aspc := web.NewAppServicePlansClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aspc.Client) - aspc.Authorizer = auth - aspc.Sender = sender - client.appServicePlansClient = aspc - - ac := web.NewAppsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ac.Client) - ac.Authorizer = auth - ac.Sender = autorest.CreateSender(withRequestLogging()) - client.appServicesClient = ac - - ai := appinsights.NewComponentsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ai.Client) - ai.Authorizer = auth - ai.Sender = sender - client.appInsightsClient = ai - - aadb := automation.NewAccountClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aadb.Client) - aadb.Authorizer = auth - aadb.Sender = sender - client.automationAccountClient = aadb - - arc := automation.NewRunbookClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&arc.Client) - arc.Authorizer = auth - arc.Sender = sender - client.automationRunbookClient = arc - - acc := automation.NewCredentialClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&acc.Client) - acc.Authorizer = auth - acc.Sender = sender - client.automationCredentialClient = acc - - aschc := automation.NewScheduleClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aschc.Client) - aschc.Authorizer = auth - aschc.Sender = sender - client.automationScheduleClient = aschc - -<<<<<<< HEAD - ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ihrc.Client) - ihrc.Authorizer = auth - ihrc.Sender = autorest.CreateSender(withRequestLogging()) - client.iothubResourceClient = ihrc - -======= -<<<<<<< HEAD - client.registerAuthentication(endpoint, graphEndpoint, c.SubscriptionID, c.TenantID, auth, graphAuth, sender) -||||||| merged common ancestors ->>>>>>> 60cd688486d722c6c36a4ee7155f24252405c0d8 - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - -======= - ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ihrc.Client) - ihrc.Authorizer = auth - ihrc.Sender = autorest.CreateSender(withRequestLogging()) - client.iothubResourceClient = ihrc - - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - ->>>>>>> added the config and cleaned up the schema iothub resource schema - client.registerDatabases(endpoint, c.SubscriptionID, auth, sender) - client.registerDisks(endpoint, c.SubscriptionID, auth, sender) - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - - return &client, nil -} - -func (c *ArmClient) registerAuthentication(endpoint, graphEndpoint, subscriptionId, tenantId string, auth, graphAuth autorest.Authorizer, sender autorest.Sender) { - spc := graphrbac.NewServicePrincipalsClientWithBaseURI(graphEndpoint, tenantId) - setUserAgent(&spc.Client) - spc.Authorizer = graphAuth - spc.Sender = sender - c.servicePrincipalsClient = spc - - rac := authorization.NewRoleAssignmentsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&rac.Client) - rac.Authorizer = auth - rac.Sender = sender - c.roleAssignmentsClient = rac - - rdc := authorization.NewRoleDefinitionsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&rdc.Client) - rdc.Authorizer = auth - rdc.Sender = sender - c.roleDefinitionsClient = rdc -} - -func (c *ArmClient) registerDatabases(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { - // MySQL - mysqlConfigClient := mysql.NewConfigurationsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlConfigClient.Client) - mysqlConfigClient.Authorizer = auth - mysqlConfigClient.Sender = sender - c.mysqlConfigurationsClient = mysqlConfigClient - - mysqlDBClient := mysql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlDBClient.Client) - mysqlDBClient.Authorizer = auth - mysqlDBClient.Sender = sender - c.mysqlDatabasesClient = mysqlDBClient - - mysqlFWClient := mysql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlFWClient.Client) - mysqlFWClient.Authorizer = auth - mysqlFWClient.Sender = sender - c.mysqlFirewallRulesClient = mysqlFWClient - - mysqlServersClient := mysql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlServersClient.Client) - mysqlServersClient.Authorizer = auth - mysqlServersClient.Sender = sender - c.mysqlServersClient = mysqlServersClient - - // PostgreSQL - postgresqlConfigClient := postgresql.NewConfigurationsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlConfigClient.Client) - postgresqlConfigClient.Authorizer = auth - postgresqlConfigClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlConfigurationsClient = postgresqlConfigClient - - postgresqlDBClient := postgresql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlDBClient.Client) - postgresqlDBClient.Authorizer = auth - postgresqlDBClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlDatabasesClient = postgresqlDBClient - - postgresqlFWClient := postgresql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlFWClient.Client) - postgresqlFWClient.Authorizer = auth - postgresqlFWClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlFirewallRulesClient = postgresqlFWClient - - postgresqlSrvClient := postgresql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlSrvClient.Client) - postgresqlSrvClient.Authorizer = auth - postgresqlSrvClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlServersClient = postgresqlSrvClient - - // SQL Azure - sqlDBClient := sql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlDBClient.Client) - sqlDBClient.Authorizer = auth - sqlDBClient.Sender = sender - c.sqlDatabasesClient = sqlDBClient - - sqlFWClient := sql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlFWClient.Client) - sqlFWClient.Authorizer = auth - sqlFWClient.Sender = sender - c.sqlFirewallRulesClient = sqlFWClient - - sqlEPClient := sql.NewElasticPoolsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlEPClient.Client) - sqlEPClient.Authorizer = auth - sqlEPClient.Sender = sender - c.sqlElasticPoolsClient = sqlEPClient - - sqlSrvClient := sql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlSrvClient.Client) - sqlSrvClient.Authorizer = auth - sqlSrvClient.Sender = sender - c.sqlServersClient = sqlSrvClient -} - -func (c *ArmClient) registerDisks(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { - diskClient := disk.NewDisksClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&diskClient.Client) - diskClient.Authorizer = auth - diskClient.Sender = sender - c.diskClient = diskClient - - snapshotsClient := disk.NewSnapshotsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&snapshotsClient.Client) - snapshotsClient.Authorizer = auth - snapshotsClient.Sender = sender - c.snapshotsClient = snapshotsClient -} - -func (c *ArmClient) registerKeyVaultClients(endpoint, subscriptionId string, auth autorest.Authorizer, keyVaultAuth autorest.Authorizer, sender autorest.Sender) { - keyVaultClient := keyvault.NewVaultsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&keyVaultClient.Client) - keyVaultClient.Authorizer = auth - keyVaultClient.Sender = sender - c.keyVaultClient = keyVaultClient - - keyVaultManagementClient := keyVault.New() - setUserAgent(&keyVaultManagementClient.Client) - keyVaultManagementClient.Authorizer = keyVaultAuth - keyVaultManagementClient.Sender = sender - c.keyVaultManagementClient = keyVaultManagementClient -} - -func (armClient *ArmClient) getKeyForStorageAccount(resourceGroupName, storageAccountName string) (string, bool, error) { - accountKeys, err := armClient.storageServiceClient.ListKeys(resourceGroupName, storageAccountName) - if accountKeys.StatusCode == http.StatusNotFound { - return "", false, nil - } - if err != nil { - // We assume this is a transient error rather than a 404 (which is caught above), so assume the - // account still exists. - return "", true, fmt.Errorf("Error retrieving keys for storage account %q: %s", storageAccountName, err) - } - - if accountKeys.Keys == nil { - return "", false, fmt.Errorf("Nil key returned for storage account %q", storageAccountName) - } - - keys := *accountKeys.Keys - return *keys[0].Value, true, nil -} - -func (armClient *ArmClient) getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.BlobStorageClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - blobClient := storageClient.GetBlobService() - return &blobClient, true, nil -} - -func (armClient *ArmClient) getFileServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.FileServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - fileClient := storageClient.GetFileService() - return &fileClient, true, nil -} - -func (armClient *ArmClient) getTableServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.TableServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - tableClient := storageClient.GetTableService() - return &tableClient, true, nil -} - -func (armClient *ArmClient) getQueueServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.QueueServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - queueClient := storageClient.GetQueueService() - return &queueClient, true, nil -} diff --git a/azurerm/config.go b/azurerm/config.go index 7b69c24fd47a..fd44660c2988 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -652,30 +652,13 @@ func (c *Config) getArmClient() (*ArmClient, error) { aschc.Sender = sender client.automationScheduleClient = aschc -<<<<<<< HEAD ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) setUserAgent(&ihrc.Client) ihrc.Authorizer = auth ihrc.Sender = autorest.CreateSender(withRequestLogging()) client.iothubResourceClient = ihrc -======= -<<<<<<< HEAD client.registerAuthentication(endpoint, graphEndpoint, c.SubscriptionID, c.TenantID, auth, graphAuth, sender) -||||||| merged common ancestors ->>>>>>> 60cd688486d722c6c36a4ee7155f24252405c0d8 - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - -======= - ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ihrc.Client) - ihrc.Authorizer = auth - ihrc.Sender = autorest.CreateSender(withRequestLogging()) - client.iothubResourceClient = ihrc - - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - ->>>>>>> added the config and cleaned up the schema iothub resource schema client.registerDatabases(endpoint, c.SubscriptionID, auth, sender) client.registerDisks(endpoint, c.SubscriptionID, auth, sender) client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) diff --git a/azurerm/config.go.orig b/azurerm/config.go.orig deleted file mode 100644 index 34b49816253c..000000000000 --- a/azurerm/config.go.orig +++ /dev/null @@ -1,905 +0,0 @@ -package azurerm - -import ( - "context" - "fmt" - "log" - "net/http" - "net/http/httputil" - - "github.com/Azure/azure-sdk-for-go/arm/iothub" - - "github.com/Azure/azure-sdk-for-go/arm/appinsights" - "github.com/Azure/azure-sdk-for-go/arm/authorization" - "github.com/Azure/azure-sdk-for-go/arm/automation" - "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/containerinstance" - "github.com/Azure/azure-sdk-for-go/arm/containerregistry" - "github.com/Azure/azure-sdk-for-go/arm/containerservice" - "github.com/Azure/azure-sdk-for-go/arm/cosmos-db" - "github.com/Azure/azure-sdk-for-go/arm/disk" - "github.com/Azure/azure-sdk-for-go/arm/dns" - "github.com/Azure/azure-sdk-for-go/arm/eventgrid" - "github.com/Azure/azure-sdk-for-go/arm/eventhub" - "github.com/Azure/azure-sdk-for-go/arm/graphrbac" - "github.com/Azure/azure-sdk-for-go/arm/keyvault" - "github.com/Azure/azure-sdk-for-go/arm/mysql" - "github.com/Azure/azure-sdk-for-go/arm/network" - "github.com/Azure/azure-sdk-for-go/arm/operationalinsights" - "github.com/Azure/azure-sdk-for-go/arm/postgresql" - "github.com/Azure/azure-sdk-for-go/arm/redis" - "github.com/Azure/azure-sdk-for-go/arm/resources/resources" - "github.com/Azure/azure-sdk-for-go/arm/resources/subscriptions" - "github.com/Azure/azure-sdk-for-go/arm/scheduler" - "github.com/Azure/azure-sdk-for-go/arm/search" - "github.com/Azure/azure-sdk-for-go/arm/servicebus" - "github.com/Azure/azure-sdk-for-go/arm/sql" - "github.com/Azure/azure-sdk-for-go/arm/storage" - "github.com/Azure/azure-sdk-for-go/arm/trafficmanager" - "github.com/Azure/azure-sdk-for-go/arm/web" - keyVault "github.com/Azure/azure-sdk-for-go/dataplane/keyvault" - mainStorage "github.com/Azure/azure-sdk-for-go/storage" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/hashicorp/terraform/terraform" -) - -// ArmClient contains the handles to all the specific Azure Resource Manager -// resource classes' respective clients. -type ArmClient struct { - clientId string - tenantId string - subscriptionId string - usingServicePrincipal bool - environment azure.Environment - - StopContext context.Context - - availSetClient compute.AvailabilitySetsClient - usageOpsClient compute.UsageClient - vmExtensionImageClient compute.VirtualMachineExtensionImagesClient - vmExtensionClient compute.VirtualMachineExtensionsClient - vmScaleSetClient compute.VirtualMachineScaleSetsClient - vmImageClient compute.VirtualMachineImagesClient - vmClient compute.VirtualMachinesClient - imageClient compute.ImagesClient - - diskClient disk.DisksClient - snapshotsClient disk.SnapshotsClient - cosmosDBClient cosmosdb.DatabaseAccountsClient - automationAccountClient automation.AccountClient - automationRunbookClient automation.RunbookClient - automationCredentialClient automation.CredentialClient - automationScheduleClient automation.ScheduleClient - - appGatewayClient network.ApplicationGatewaysClient - ifaceClient network.InterfacesClient - expressRouteCircuitClient network.ExpressRouteCircuitsClient - loadBalancerClient network.LoadBalancersClient - localNetConnClient network.LocalNetworkGatewaysClient - publicIPClient network.PublicIPAddressesClient - secGroupClient network.SecurityGroupsClient - secRuleClient network.SecurityRulesClient - subnetClient network.SubnetsClient - netUsageClient network.UsagesClient - vnetGatewayConnectionsClient network.VirtualNetworkGatewayConnectionsClient - vnetGatewayClient network.VirtualNetworkGatewaysClient - vnetClient network.VirtualNetworksClient - vnetPeeringsClient network.VirtualNetworkPeeringsClient - routeTablesClient network.RouteTablesClient - routesClient network.RoutesClient - dnsClient dns.RecordSetsClient - zonesClient dns.ZonesClient - - cdnProfilesClient cdn.ProfilesClient - cdnEndpointsClient cdn.EndpointsClient - - containerRegistryClient containerregistry.RegistriesClient - containerServicesClient containerservice.ContainerServicesClient - containerGroupsClient containerinstance.ContainerGroupsClient - - eventGridTopicsClient eventgrid.TopicsClient - eventHubClient eventhub.EventHubsClient - eventHubConsumerGroupClient eventhub.ConsumerGroupsClient - eventHubNamespacesClient eventhub.NamespacesClient - - workspacesClient operationalinsights.WorkspacesClient - - providers resources.ProvidersClient - resourceGroupClient resources.GroupsClient - tagsClient resources.TagsClient - resourceFindClient resources.GroupClient - - subscriptionsGroupClient subscriptions.GroupClient - - jobsClient scheduler.JobsClient - jobsCollectionsClient scheduler.JobCollectionsClient - - storageServiceClient storage.AccountsClient - storageUsageClient storage.UsageClient - - deploymentsClient resources.DeploymentsClient - - redisClient redis.GroupClient - - trafficManagerProfilesClient trafficmanager.ProfilesClient - trafficManagerEndpointsClient trafficmanager.EndpointsClient - - searchServicesClient search.ServicesClient - serviceBusNamespacesClient servicebus.NamespacesClient - serviceBusQueuesClient servicebus.QueuesClient - serviceBusTopicsClient servicebus.TopicsClient - serviceBusSubscriptionsClient servicebus.SubscriptionsClient - - keyVaultClient keyvault.VaultsClient - keyVaultManagementClient keyVault.ManagementClient - - appServicePlansClient web.AppServicePlansClient - appServicesClient web.AppsClient - - appInsightsClient appinsights.ComponentsClient - - // Authentication - roleAssignmentsClient authorization.RoleAssignmentsClient - roleDefinitionsClient authorization.RoleDefinitionsClient - servicePrincipalsClient graphrbac.ServicePrincipalsClient - - // Databases - mysqlConfigurationsClient mysql.ConfigurationsClient - mysqlDatabasesClient mysql.DatabasesClient - mysqlFirewallRulesClient mysql.FirewallRulesClient - mysqlServersClient mysql.ServersClient - postgresqlConfigurationsClient postgresql.ConfigurationsClient - postgresqlDatabasesClient postgresql.DatabasesClient - postgresqlFirewallRulesClient postgresql.FirewallRulesClient - postgresqlServersClient postgresql.ServersClient - sqlDatabasesClient sql.DatabasesClient - sqlElasticPoolsClient sql.ElasticPoolsClient - sqlFirewallRulesClient sql.FirewallRulesClient - sqlServersClient sql.ServersClient - iothubResourceClient iothub.ResourceClient -} - -func withRequestLogging() autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - // dump request to wire format - if dump, err := httputil.DumpRequestOut(r, true); err == nil { - log.Printf("[DEBUG] AzureRM Request: \n%s\n", dump) - } else { - // fallback to basic message - log.Printf("[DEBUG] AzureRM Request: %s to %s\n", r.Method, r.URL) - } - - resp, err := s.Do(r) - if resp != nil { - // dump response to wire format - if dump, err := httputil.DumpResponse(resp, true); err == nil { - log.Printf("[DEBUG] AzureRM Response for %s: \n%s\n", r.URL, dump) - } else { - // fallback to basic message - log.Printf("[DEBUG] AzureRM Response: %s for %s\n", resp.Status, r.URL) - } - } else { - log.Printf("[DEBUG] Request to %s completed with no response", r.URL) - } - return resp, err - }) - } -} - -func setUserAgent(client *autorest.Client) { - version := terraform.VersionString() - client.UserAgent = fmt.Sprintf("HashiCorp-Terraform-v%s", version) -} - -func (c *Config) getAuthorizationToken(oauthConfig *adal.OAuthConfig, endpoint string) (*autorest.BearerAuthorizer, error) { - useServicePrincipal := c.ClientSecret != "" - - if useServicePrincipal { - spt, err := adal.NewServicePrincipalToken(*oauthConfig, c.ClientID, c.ClientSecret, endpoint) - if err != nil { - return nil, err - } - - auth := autorest.NewBearerAuthorizer(spt) - return auth, nil - } - - if c.IsCloudShell { - // load the refreshed tokens from the Azure CLI - err := c.LoadTokensFromAzureCLI() - if err != nil { - return nil, fmt.Errorf("Error loading the refreshed CloudShell tokens: %+v", err) - } - } - - spt, err := adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, c.ClientID, endpoint, *c.AccessToken) - if err != nil { - return nil, err - } - - auth := autorest.NewBearerAuthorizer(spt) - return auth, nil -} - -// getArmClient is a helper method which returns a fully instantiated -// *ArmClient based on the Config's current settings. -func (c *Config) getArmClient() (*ArmClient, error) { - // detect cloud from environment - env, envErr := azure.EnvironmentFromName(c.Environment) - if envErr != nil { - // try again with wrapped value to support readable values like german instead of AZUREGERMANCLOUD - wrapped := fmt.Sprintf("AZURE%sCLOUD", c.Environment) - var innerErr error - if env, innerErr = azure.EnvironmentFromName(wrapped); innerErr != nil { - return nil, envErr - } - } - - // client declarations: - client := ArmClient{ - clientId: c.ClientID, - tenantId: c.TenantID, - subscriptionId: c.SubscriptionID, - environment: env, - usingServicePrincipal: c.ClientSecret != "", - } - - oauthConfig, err := adal.NewOAuthConfig(env.ActiveDirectoryEndpoint, c.TenantID) - if err != nil { - return nil, err - } - - // OAuthConfigForTenant returns a pointer, which can be nil. - if oauthConfig == nil { - return nil, fmt.Errorf("Unable to configure OAuthConfig for tenant %s", c.TenantID) - } - - sender := autorest.CreateSender(withRequestLogging()) - - // Resource Manager endpoints - endpoint := env.ResourceManagerEndpoint - auth, err := c.getAuthorizationToken(oauthConfig, endpoint) - if err != nil { - return nil, err - } - - // Graph Endpoints - graphEndpoint := env.GraphEndpoint - graphAuth, err := c.getAuthorizationToken(oauthConfig, graphEndpoint) - if err != nil { - return nil, err - } - - // Key Vault Endpoints - keyVaultAuth := autorest.NewBearerAuthorizerCallback(sender, func(tenantID, resource string) (*autorest.BearerAuthorizer, error) { - keyVaultSpt, err := c.getAuthorizationToken(oauthConfig, resource) - if err != nil { - return nil, err - } - - return keyVaultSpt, nil - }) - - // NOTE: these declarations should be left separate for clarity should the - // clients be wished to be configured with custom Responders/PollingModes etc... - asc := compute.NewAvailabilitySetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&asc.Client) - asc.Authorizer = auth - asc.Sender = sender - client.availSetClient = asc - - uoc := compute.NewUsageClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&uoc.Client) - uoc.Authorizer = auth - uoc.Sender = sender - client.usageOpsClient = uoc - - vmeic := compute.NewVirtualMachineExtensionImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmeic.Client) - vmeic.Authorizer = auth - vmeic.Sender = sender - client.vmExtensionImageClient = vmeic - - vmec := compute.NewVirtualMachineExtensionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmec.Client) - vmec.Authorizer = auth - vmec.Sender = sender - client.vmExtensionClient = vmec - - vmic := compute.NewVirtualMachineImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmic.Client) - vmic.Authorizer = auth - vmic.Sender = sender - client.vmImageClient = vmic - - vmssc := compute.NewVirtualMachineScaleSetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmssc.Client) - vmssc.Authorizer = auth - vmssc.Sender = sender - client.vmScaleSetClient = vmssc - - vmc := compute.NewVirtualMachinesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmc.Client) - vmc.Authorizer = auth - vmc.Sender = sender - client.vmClient = vmc - - agc := network.NewApplicationGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&agc.Client) - agc.Authorizer = auth - agc.Sender = sender - client.appGatewayClient = agc - - crc := containerregistry.NewRegistriesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&crc.Client) - crc.Authorizer = auth - crc.Sender = sender - client.containerRegistryClient = crc - - csc := containerservice.NewContainerServicesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&csc.Client) - csc.Authorizer = auth - csc.Sender = sender - client.containerServicesClient = csc - - cgc := containerinstance.NewContainerGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cgc.Client) - cgc.Authorizer = auth - cgc.Sender = autorest.CreateSender(withRequestLogging()) - client.containerGroupsClient = cgc - - cdb := cosmosdb.NewDatabaseAccountsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cdb.Client) - cdb.Authorizer = auth - cdb.Sender = sender - client.cosmosDBClient = cdb - - img := compute.NewImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&img.Client) - img.Authorizer = auth - img.Sender = sender - client.imageClient = img - - egtc := eventgrid.NewTopicsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&egtc.Client) - egtc.Authorizer = auth - egtc.Sender = sender - client.eventGridTopicsClient = egtc - - ehc := eventhub.NewEventHubsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ehc.Client) - ehc.Authorizer = auth - ehc.Sender = sender - client.eventHubClient = ehc - - chcgc := eventhub.NewConsumerGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&chcgc.Client) - chcgc.Authorizer = auth - chcgc.Sender = sender - client.eventHubConsumerGroupClient = chcgc - - ehnc := eventhub.NewNamespacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ehnc.Client) - ehnc.Authorizer = auth - ehnc.Sender = sender - client.eventHubNamespacesClient = ehnc - - ifc := network.NewInterfacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ifc.Client) - ifc.Authorizer = auth - ifc.Sender = sender - client.ifaceClient = ifc - - erc := network.NewExpressRouteCircuitsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&erc.Client) - erc.Authorizer = auth - erc.Sender = sender - client.expressRouteCircuitClient = erc - - lbc := network.NewLoadBalancersClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&lbc.Client) - lbc.Authorizer = auth - lbc.Sender = sender - client.loadBalancerClient = lbc - - lgc := network.NewLocalNetworkGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&lgc.Client) - lgc.Authorizer = auth - lgc.Sender = sender - client.localNetConnClient = lgc - - opwc := operationalinsights.NewWorkspacesClient(c.SubscriptionID) - setUserAgent(&opwc.Client) - opwc.Authorizer = auth - opwc.Sender = autorest.CreateSender(withRequestLogging()) - client.workspacesClient = opwc - - pipc := network.NewPublicIPAddressesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&pipc.Client) - pipc.Authorizer = auth - pipc.Sender = sender - client.publicIPClient = pipc - - sgc := network.NewSecurityGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sgc.Client) - sgc.Authorizer = auth - sgc.Sender = sender - client.secGroupClient = sgc - - src := network.NewSecurityRulesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&src.Client) - src.Authorizer = auth - src.Sender = sender - client.secRuleClient = src - - snc := network.NewSubnetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&snc.Client) - snc.Authorizer = auth - snc.Sender = sender - client.subnetClient = snc - - vgcc := network.NewVirtualNetworkGatewayConnectionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vgcc.Client) - vgcc.Authorizer = auth - vgcc.Sender = sender - client.vnetGatewayConnectionsClient = vgcc - - vgc := network.NewVirtualNetworkGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vgc.Client) - vgc.Authorizer = auth - vgc.Sender = sender - client.vnetGatewayClient = vgc - - vnc := network.NewVirtualNetworksClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vnc.Client) - vnc.Authorizer = auth - vnc.Sender = sender - client.vnetClient = vnc - - vnpc := network.NewVirtualNetworkPeeringsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vnpc.Client) - vnpc.Authorizer = auth - vnpc.Sender = sender - client.vnetPeeringsClient = vnpc - - rtc := network.NewRouteTablesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rtc.Client) - rtc.Authorizer = auth - rtc.Sender = sender - client.routeTablesClient = rtc - - rc := network.NewRoutesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rc.Client) - rc.Authorizer = auth - rc.Sender = sender - client.routesClient = rc - - dn := dns.NewRecordSetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&dn.Client) - dn.Authorizer = auth - dn.Sender = sender - client.dnsClient = dn - - zo := dns.NewZonesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&zo.Client) - zo.Authorizer = auth - zo.Sender = sender - client.zonesClient = zo - - rgc := resources.NewGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rgc.Client) - rgc.Authorizer = auth - rgc.Sender = sender - client.resourceGroupClient = rgc - - pc := resources.NewProvidersClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&pc.Client) - pc.Authorizer = auth - pc.Sender = sender - client.providers = pc - - tc := resources.NewTagsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tc.Client) - tc.Authorizer = auth - tc.Sender = sender - client.tagsClient = tc - - rf := resources.NewGroupClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rf.Client) - rf.Authorizer = auth - rf.Sender = sender - client.resourceFindClient = rf - - subgc := subscriptions.NewGroupClientWithBaseURI(endpoint) - setUserAgent(&subgc.Client) - subgc.Authorizer = auth - subgc.Sender = sender - client.subscriptionsGroupClient = subgc - - jc := scheduler.NewJobsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&jc.Client) - jc.Authorizer = auth - jc.Sender = sender - client.jobsClient = jc - - jcc := scheduler.NewJobCollectionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&jcc.Client) - jcc.Authorizer = auth - jcc.Sender = sender - client.jobsCollectionsClient = jcc - - ssc := storage.NewAccountsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ssc.Client) - ssc.Authorizer = auth - ssc.Sender = sender - client.storageServiceClient = ssc - - suc := storage.NewUsageClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&suc.Client) - suc.Authorizer = auth - suc.Sender = sender - client.storageUsageClient = suc - - cpc := cdn.NewProfilesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cpc.Client) - cpc.Authorizer = auth - cpc.Sender = sender - client.cdnProfilesClient = cpc - - cec := cdn.NewEndpointsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cec.Client) - cec.Authorizer = auth - cec.Sender = sender - client.cdnEndpointsClient = cec - - dc := resources.NewDeploymentsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&dc.Client) - dc.Authorizer = auth - dc.Sender = sender - client.deploymentsClient = dc - - tmpc := trafficmanager.NewProfilesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tmpc.Client) - tmpc.Authorizer = auth - tmpc.Sender = sender - client.trafficManagerProfilesClient = tmpc - - tmec := trafficmanager.NewEndpointsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tmec.Client) - tmec.Authorizer = auth - tmec.Sender = sender - client.trafficManagerEndpointsClient = tmec - - rdc := redis.NewGroupClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rdc.Client) - rdc.Authorizer = auth - rdc.Sender = sender - client.redisClient = rdc - - sesc := search.NewServicesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sesc.Client) - sesc.Authorizer = auth - sesc.Sender = sender - client.searchServicesClient = sesc - - sbnc := servicebus.NewNamespacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbnc.Client) - sbnc.Authorizer = auth - sbnc.Sender = sender - client.serviceBusNamespacesClient = sbnc - - sbqc := servicebus.NewQueuesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbqc.Client) - sbqc.Authorizer = auth - sbqc.Sender = sender - client.serviceBusQueuesClient = sbqc - - sbtc := servicebus.NewTopicsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbtc.Client) - sbtc.Authorizer = auth - sbtc.Sender = sender - client.serviceBusTopicsClient = sbtc - - sbsc := servicebus.NewSubscriptionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbsc.Client) - sbsc.Authorizer = auth - sbsc.Sender = sender - client.serviceBusSubscriptionsClient = sbsc - - aspc := web.NewAppServicePlansClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aspc.Client) - aspc.Authorizer = auth - aspc.Sender = sender - client.appServicePlansClient = aspc - - ac := web.NewAppsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ac.Client) - ac.Authorizer = auth - ac.Sender = autorest.CreateSender(withRequestLogging()) - client.appServicesClient = ac - - ai := appinsights.NewComponentsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ai.Client) - ai.Authorizer = auth - ai.Sender = sender - client.appInsightsClient = ai - - aadb := automation.NewAccountClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aadb.Client) - aadb.Authorizer = auth - aadb.Sender = sender - client.automationAccountClient = aadb - - arc := automation.NewRunbookClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&arc.Client) - arc.Authorizer = auth - arc.Sender = sender - client.automationRunbookClient = arc - - acc := automation.NewCredentialClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&acc.Client) - acc.Authorizer = auth - acc.Sender = sender - client.automationCredentialClient = acc - - aschc := automation.NewScheduleClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aschc.Client) - aschc.Authorizer = auth - aschc.Sender = sender - client.automationScheduleClient = aschc - -<<<<<<< HEAD -<<<<<<< HEAD - ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ihrc.Client) - ihrc.Authorizer = auth - ihrc.Sender = autorest.CreateSender(withRequestLogging()) - client.iothubResourceClient = ihrc - -======= -<<<<<<< HEAD - client.registerAuthentication(endpoint, graphEndpoint, c.SubscriptionID, c.TenantID, auth, graphAuth, sender) -||||||| merged common ancestors ->>>>>>> 60cd688486d722c6c36a4ee7155f24252405c0d8 - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - -======= -======= ->>>>>>> 0c2e6aafd710e9fe7024b76e0f64f43a10c0f15d - ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ihrc.Client) - ihrc.Authorizer = auth - ihrc.Sender = autorest.CreateSender(withRequestLogging()) - client.iothubResourceClient = ihrc - - client.registerAuthentication(endpoint, graphEndpoint, c.SubscriptionID, c.TenantID, auth, graphAuth, sender) - client.registerDatabases(endpoint, c.SubscriptionID, auth, sender) - client.registerDisks(endpoint, c.SubscriptionID, auth, sender) - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - - return &client, nil -} - -func (c *ArmClient) registerAuthentication(endpoint, graphEndpoint, subscriptionId, tenantId string, auth, graphAuth autorest.Authorizer, sender autorest.Sender) { - spc := graphrbac.NewServicePrincipalsClientWithBaseURI(graphEndpoint, tenantId) - setUserAgent(&spc.Client) - spc.Authorizer = graphAuth - spc.Sender = sender - c.servicePrincipalsClient = spc - - rac := authorization.NewRoleAssignmentsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&rac.Client) - rac.Authorizer = auth - rac.Sender = sender - c.roleAssignmentsClient = rac - - rdc := authorization.NewRoleDefinitionsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&rdc.Client) - rdc.Authorizer = auth - rdc.Sender = sender - c.roleDefinitionsClient = rdc -} - -func (c *ArmClient) registerDatabases(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { - // MySQL - mysqlConfigClient := mysql.NewConfigurationsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlConfigClient.Client) - mysqlConfigClient.Authorizer = auth - mysqlConfigClient.Sender = sender - c.mysqlConfigurationsClient = mysqlConfigClient - - mysqlDBClient := mysql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlDBClient.Client) - mysqlDBClient.Authorizer = auth - mysqlDBClient.Sender = sender - c.mysqlDatabasesClient = mysqlDBClient - - mysqlFWClient := mysql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlFWClient.Client) - mysqlFWClient.Authorizer = auth - mysqlFWClient.Sender = sender - c.mysqlFirewallRulesClient = mysqlFWClient - - mysqlServersClient := mysql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlServersClient.Client) - mysqlServersClient.Authorizer = auth - mysqlServersClient.Sender = sender - c.mysqlServersClient = mysqlServersClient - - // PostgreSQL - postgresqlConfigClient := postgresql.NewConfigurationsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlConfigClient.Client) - postgresqlConfigClient.Authorizer = auth - postgresqlConfigClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlConfigurationsClient = postgresqlConfigClient - - postgresqlDBClient := postgresql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlDBClient.Client) - postgresqlDBClient.Authorizer = auth - postgresqlDBClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlDatabasesClient = postgresqlDBClient - - postgresqlFWClient := postgresql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlFWClient.Client) - postgresqlFWClient.Authorizer = auth - postgresqlFWClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlFirewallRulesClient = postgresqlFWClient - - postgresqlSrvClient := postgresql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlSrvClient.Client) - postgresqlSrvClient.Authorizer = auth - postgresqlSrvClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlServersClient = postgresqlSrvClient - - // SQL Azure - sqlDBClient := sql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlDBClient.Client) - sqlDBClient.Authorizer = auth - sqlDBClient.Sender = sender - c.sqlDatabasesClient = sqlDBClient - - sqlFWClient := sql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlFWClient.Client) - sqlFWClient.Authorizer = auth - sqlFWClient.Sender = sender - c.sqlFirewallRulesClient = sqlFWClient - - sqlEPClient := sql.NewElasticPoolsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlEPClient.Client) - sqlEPClient.Authorizer = auth - sqlEPClient.Sender = sender - c.sqlElasticPoolsClient = sqlEPClient - - sqlSrvClient := sql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlSrvClient.Client) - sqlSrvClient.Authorizer = auth - sqlSrvClient.Sender = sender - c.sqlServersClient = sqlSrvClient -} - -func (c *ArmClient) registerDisks(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { - diskClient := disk.NewDisksClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&diskClient.Client) - diskClient.Authorizer = auth - diskClient.Sender = sender - c.diskClient = diskClient - - snapshotsClient := disk.NewSnapshotsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&snapshotsClient.Client) - snapshotsClient.Authorizer = auth - snapshotsClient.Sender = sender - c.snapshotsClient = snapshotsClient -} - -func (c *ArmClient) registerKeyVaultClients(endpoint, subscriptionId string, auth autorest.Authorizer, keyVaultAuth autorest.Authorizer, sender autorest.Sender) { - keyVaultClient := keyvault.NewVaultsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&keyVaultClient.Client) - keyVaultClient.Authorizer = auth - keyVaultClient.Sender = sender - c.keyVaultClient = keyVaultClient - - keyVaultManagementClient := keyVault.New() - setUserAgent(&keyVaultManagementClient.Client) - keyVaultManagementClient.Authorizer = keyVaultAuth - keyVaultManagementClient.Sender = sender - c.keyVaultManagementClient = keyVaultManagementClient -} - -func (armClient *ArmClient) getKeyForStorageAccount(resourceGroupName, storageAccountName string) (string, bool, error) { - accountKeys, err := armClient.storageServiceClient.ListKeys(resourceGroupName, storageAccountName) - if accountKeys.StatusCode == http.StatusNotFound { - return "", false, nil - } - if err != nil { - // We assume this is a transient error rather than a 404 (which is caught above), so assume the - // account still exists. - return "", true, fmt.Errorf("Error retrieving keys for storage account %q: %s", storageAccountName, err) - } - - if accountKeys.Keys == nil { - return "", false, fmt.Errorf("Nil key returned for storage account %q", storageAccountName) - } - - keys := *accountKeys.Keys - return *keys[0].Value, true, nil -} - -func (armClient *ArmClient) getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.BlobStorageClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - blobClient := storageClient.GetBlobService() - return &blobClient, true, nil -} - -func (armClient *ArmClient) getFileServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.FileServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - fileClient := storageClient.GetFileService() - return &fileClient, true, nil -} - -func (armClient *ArmClient) getTableServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.TableServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - tableClient := storageClient.GetTableService() - return &tableClient, true, nil -} - -func (armClient *ArmClient) getQueueServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.QueueServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - queueClient := storageClient.GetQueueService() - return &queueClient, true, nil -} diff --git a/azurerm/config_BACKUP_7053.go b/azurerm/config_BACKUP_7053.go deleted file mode 100644 index 34b49816253c..000000000000 --- a/azurerm/config_BACKUP_7053.go +++ /dev/null @@ -1,905 +0,0 @@ -package azurerm - -import ( - "context" - "fmt" - "log" - "net/http" - "net/http/httputil" - - "github.com/Azure/azure-sdk-for-go/arm/iothub" - - "github.com/Azure/azure-sdk-for-go/arm/appinsights" - "github.com/Azure/azure-sdk-for-go/arm/authorization" - "github.com/Azure/azure-sdk-for-go/arm/automation" - "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/containerinstance" - "github.com/Azure/azure-sdk-for-go/arm/containerregistry" - "github.com/Azure/azure-sdk-for-go/arm/containerservice" - "github.com/Azure/azure-sdk-for-go/arm/cosmos-db" - "github.com/Azure/azure-sdk-for-go/arm/disk" - "github.com/Azure/azure-sdk-for-go/arm/dns" - "github.com/Azure/azure-sdk-for-go/arm/eventgrid" - "github.com/Azure/azure-sdk-for-go/arm/eventhub" - "github.com/Azure/azure-sdk-for-go/arm/graphrbac" - "github.com/Azure/azure-sdk-for-go/arm/keyvault" - "github.com/Azure/azure-sdk-for-go/arm/mysql" - "github.com/Azure/azure-sdk-for-go/arm/network" - "github.com/Azure/azure-sdk-for-go/arm/operationalinsights" - "github.com/Azure/azure-sdk-for-go/arm/postgresql" - "github.com/Azure/azure-sdk-for-go/arm/redis" - "github.com/Azure/azure-sdk-for-go/arm/resources/resources" - "github.com/Azure/azure-sdk-for-go/arm/resources/subscriptions" - "github.com/Azure/azure-sdk-for-go/arm/scheduler" - "github.com/Azure/azure-sdk-for-go/arm/search" - "github.com/Azure/azure-sdk-for-go/arm/servicebus" - "github.com/Azure/azure-sdk-for-go/arm/sql" - "github.com/Azure/azure-sdk-for-go/arm/storage" - "github.com/Azure/azure-sdk-for-go/arm/trafficmanager" - "github.com/Azure/azure-sdk-for-go/arm/web" - keyVault "github.com/Azure/azure-sdk-for-go/dataplane/keyvault" - mainStorage "github.com/Azure/azure-sdk-for-go/storage" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/hashicorp/terraform/terraform" -) - -// ArmClient contains the handles to all the specific Azure Resource Manager -// resource classes' respective clients. -type ArmClient struct { - clientId string - tenantId string - subscriptionId string - usingServicePrincipal bool - environment azure.Environment - - StopContext context.Context - - availSetClient compute.AvailabilitySetsClient - usageOpsClient compute.UsageClient - vmExtensionImageClient compute.VirtualMachineExtensionImagesClient - vmExtensionClient compute.VirtualMachineExtensionsClient - vmScaleSetClient compute.VirtualMachineScaleSetsClient - vmImageClient compute.VirtualMachineImagesClient - vmClient compute.VirtualMachinesClient - imageClient compute.ImagesClient - - diskClient disk.DisksClient - snapshotsClient disk.SnapshotsClient - cosmosDBClient cosmosdb.DatabaseAccountsClient - automationAccountClient automation.AccountClient - automationRunbookClient automation.RunbookClient - automationCredentialClient automation.CredentialClient - automationScheduleClient automation.ScheduleClient - - appGatewayClient network.ApplicationGatewaysClient - ifaceClient network.InterfacesClient - expressRouteCircuitClient network.ExpressRouteCircuitsClient - loadBalancerClient network.LoadBalancersClient - localNetConnClient network.LocalNetworkGatewaysClient - publicIPClient network.PublicIPAddressesClient - secGroupClient network.SecurityGroupsClient - secRuleClient network.SecurityRulesClient - subnetClient network.SubnetsClient - netUsageClient network.UsagesClient - vnetGatewayConnectionsClient network.VirtualNetworkGatewayConnectionsClient - vnetGatewayClient network.VirtualNetworkGatewaysClient - vnetClient network.VirtualNetworksClient - vnetPeeringsClient network.VirtualNetworkPeeringsClient - routeTablesClient network.RouteTablesClient - routesClient network.RoutesClient - dnsClient dns.RecordSetsClient - zonesClient dns.ZonesClient - - cdnProfilesClient cdn.ProfilesClient - cdnEndpointsClient cdn.EndpointsClient - - containerRegistryClient containerregistry.RegistriesClient - containerServicesClient containerservice.ContainerServicesClient - containerGroupsClient containerinstance.ContainerGroupsClient - - eventGridTopicsClient eventgrid.TopicsClient - eventHubClient eventhub.EventHubsClient - eventHubConsumerGroupClient eventhub.ConsumerGroupsClient - eventHubNamespacesClient eventhub.NamespacesClient - - workspacesClient operationalinsights.WorkspacesClient - - providers resources.ProvidersClient - resourceGroupClient resources.GroupsClient - tagsClient resources.TagsClient - resourceFindClient resources.GroupClient - - subscriptionsGroupClient subscriptions.GroupClient - - jobsClient scheduler.JobsClient - jobsCollectionsClient scheduler.JobCollectionsClient - - storageServiceClient storage.AccountsClient - storageUsageClient storage.UsageClient - - deploymentsClient resources.DeploymentsClient - - redisClient redis.GroupClient - - trafficManagerProfilesClient trafficmanager.ProfilesClient - trafficManagerEndpointsClient trafficmanager.EndpointsClient - - searchServicesClient search.ServicesClient - serviceBusNamespacesClient servicebus.NamespacesClient - serviceBusQueuesClient servicebus.QueuesClient - serviceBusTopicsClient servicebus.TopicsClient - serviceBusSubscriptionsClient servicebus.SubscriptionsClient - - keyVaultClient keyvault.VaultsClient - keyVaultManagementClient keyVault.ManagementClient - - appServicePlansClient web.AppServicePlansClient - appServicesClient web.AppsClient - - appInsightsClient appinsights.ComponentsClient - - // Authentication - roleAssignmentsClient authorization.RoleAssignmentsClient - roleDefinitionsClient authorization.RoleDefinitionsClient - servicePrincipalsClient graphrbac.ServicePrincipalsClient - - // Databases - mysqlConfigurationsClient mysql.ConfigurationsClient - mysqlDatabasesClient mysql.DatabasesClient - mysqlFirewallRulesClient mysql.FirewallRulesClient - mysqlServersClient mysql.ServersClient - postgresqlConfigurationsClient postgresql.ConfigurationsClient - postgresqlDatabasesClient postgresql.DatabasesClient - postgresqlFirewallRulesClient postgresql.FirewallRulesClient - postgresqlServersClient postgresql.ServersClient - sqlDatabasesClient sql.DatabasesClient - sqlElasticPoolsClient sql.ElasticPoolsClient - sqlFirewallRulesClient sql.FirewallRulesClient - sqlServersClient sql.ServersClient - iothubResourceClient iothub.ResourceClient -} - -func withRequestLogging() autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - // dump request to wire format - if dump, err := httputil.DumpRequestOut(r, true); err == nil { - log.Printf("[DEBUG] AzureRM Request: \n%s\n", dump) - } else { - // fallback to basic message - log.Printf("[DEBUG] AzureRM Request: %s to %s\n", r.Method, r.URL) - } - - resp, err := s.Do(r) - if resp != nil { - // dump response to wire format - if dump, err := httputil.DumpResponse(resp, true); err == nil { - log.Printf("[DEBUG] AzureRM Response for %s: \n%s\n", r.URL, dump) - } else { - // fallback to basic message - log.Printf("[DEBUG] AzureRM Response: %s for %s\n", resp.Status, r.URL) - } - } else { - log.Printf("[DEBUG] Request to %s completed with no response", r.URL) - } - return resp, err - }) - } -} - -func setUserAgent(client *autorest.Client) { - version := terraform.VersionString() - client.UserAgent = fmt.Sprintf("HashiCorp-Terraform-v%s", version) -} - -func (c *Config) getAuthorizationToken(oauthConfig *adal.OAuthConfig, endpoint string) (*autorest.BearerAuthorizer, error) { - useServicePrincipal := c.ClientSecret != "" - - if useServicePrincipal { - spt, err := adal.NewServicePrincipalToken(*oauthConfig, c.ClientID, c.ClientSecret, endpoint) - if err != nil { - return nil, err - } - - auth := autorest.NewBearerAuthorizer(spt) - return auth, nil - } - - if c.IsCloudShell { - // load the refreshed tokens from the Azure CLI - err := c.LoadTokensFromAzureCLI() - if err != nil { - return nil, fmt.Errorf("Error loading the refreshed CloudShell tokens: %+v", err) - } - } - - spt, err := adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, c.ClientID, endpoint, *c.AccessToken) - if err != nil { - return nil, err - } - - auth := autorest.NewBearerAuthorizer(spt) - return auth, nil -} - -// getArmClient is a helper method which returns a fully instantiated -// *ArmClient based on the Config's current settings. -func (c *Config) getArmClient() (*ArmClient, error) { - // detect cloud from environment - env, envErr := azure.EnvironmentFromName(c.Environment) - if envErr != nil { - // try again with wrapped value to support readable values like german instead of AZUREGERMANCLOUD - wrapped := fmt.Sprintf("AZURE%sCLOUD", c.Environment) - var innerErr error - if env, innerErr = azure.EnvironmentFromName(wrapped); innerErr != nil { - return nil, envErr - } - } - - // client declarations: - client := ArmClient{ - clientId: c.ClientID, - tenantId: c.TenantID, - subscriptionId: c.SubscriptionID, - environment: env, - usingServicePrincipal: c.ClientSecret != "", - } - - oauthConfig, err := adal.NewOAuthConfig(env.ActiveDirectoryEndpoint, c.TenantID) - if err != nil { - return nil, err - } - - // OAuthConfigForTenant returns a pointer, which can be nil. - if oauthConfig == nil { - return nil, fmt.Errorf("Unable to configure OAuthConfig for tenant %s", c.TenantID) - } - - sender := autorest.CreateSender(withRequestLogging()) - - // Resource Manager endpoints - endpoint := env.ResourceManagerEndpoint - auth, err := c.getAuthorizationToken(oauthConfig, endpoint) - if err != nil { - return nil, err - } - - // Graph Endpoints - graphEndpoint := env.GraphEndpoint - graphAuth, err := c.getAuthorizationToken(oauthConfig, graphEndpoint) - if err != nil { - return nil, err - } - - // Key Vault Endpoints - keyVaultAuth := autorest.NewBearerAuthorizerCallback(sender, func(tenantID, resource string) (*autorest.BearerAuthorizer, error) { - keyVaultSpt, err := c.getAuthorizationToken(oauthConfig, resource) - if err != nil { - return nil, err - } - - return keyVaultSpt, nil - }) - - // NOTE: these declarations should be left separate for clarity should the - // clients be wished to be configured with custom Responders/PollingModes etc... - asc := compute.NewAvailabilitySetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&asc.Client) - asc.Authorizer = auth - asc.Sender = sender - client.availSetClient = asc - - uoc := compute.NewUsageClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&uoc.Client) - uoc.Authorizer = auth - uoc.Sender = sender - client.usageOpsClient = uoc - - vmeic := compute.NewVirtualMachineExtensionImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmeic.Client) - vmeic.Authorizer = auth - vmeic.Sender = sender - client.vmExtensionImageClient = vmeic - - vmec := compute.NewVirtualMachineExtensionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmec.Client) - vmec.Authorizer = auth - vmec.Sender = sender - client.vmExtensionClient = vmec - - vmic := compute.NewVirtualMachineImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmic.Client) - vmic.Authorizer = auth - vmic.Sender = sender - client.vmImageClient = vmic - - vmssc := compute.NewVirtualMachineScaleSetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmssc.Client) - vmssc.Authorizer = auth - vmssc.Sender = sender - client.vmScaleSetClient = vmssc - - vmc := compute.NewVirtualMachinesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmc.Client) - vmc.Authorizer = auth - vmc.Sender = sender - client.vmClient = vmc - - agc := network.NewApplicationGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&agc.Client) - agc.Authorizer = auth - agc.Sender = sender - client.appGatewayClient = agc - - crc := containerregistry.NewRegistriesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&crc.Client) - crc.Authorizer = auth - crc.Sender = sender - client.containerRegistryClient = crc - - csc := containerservice.NewContainerServicesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&csc.Client) - csc.Authorizer = auth - csc.Sender = sender - client.containerServicesClient = csc - - cgc := containerinstance.NewContainerGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cgc.Client) - cgc.Authorizer = auth - cgc.Sender = autorest.CreateSender(withRequestLogging()) - client.containerGroupsClient = cgc - - cdb := cosmosdb.NewDatabaseAccountsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cdb.Client) - cdb.Authorizer = auth - cdb.Sender = sender - client.cosmosDBClient = cdb - - img := compute.NewImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&img.Client) - img.Authorizer = auth - img.Sender = sender - client.imageClient = img - - egtc := eventgrid.NewTopicsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&egtc.Client) - egtc.Authorizer = auth - egtc.Sender = sender - client.eventGridTopicsClient = egtc - - ehc := eventhub.NewEventHubsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ehc.Client) - ehc.Authorizer = auth - ehc.Sender = sender - client.eventHubClient = ehc - - chcgc := eventhub.NewConsumerGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&chcgc.Client) - chcgc.Authorizer = auth - chcgc.Sender = sender - client.eventHubConsumerGroupClient = chcgc - - ehnc := eventhub.NewNamespacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ehnc.Client) - ehnc.Authorizer = auth - ehnc.Sender = sender - client.eventHubNamespacesClient = ehnc - - ifc := network.NewInterfacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ifc.Client) - ifc.Authorizer = auth - ifc.Sender = sender - client.ifaceClient = ifc - - erc := network.NewExpressRouteCircuitsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&erc.Client) - erc.Authorizer = auth - erc.Sender = sender - client.expressRouteCircuitClient = erc - - lbc := network.NewLoadBalancersClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&lbc.Client) - lbc.Authorizer = auth - lbc.Sender = sender - client.loadBalancerClient = lbc - - lgc := network.NewLocalNetworkGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&lgc.Client) - lgc.Authorizer = auth - lgc.Sender = sender - client.localNetConnClient = lgc - - opwc := operationalinsights.NewWorkspacesClient(c.SubscriptionID) - setUserAgent(&opwc.Client) - opwc.Authorizer = auth - opwc.Sender = autorest.CreateSender(withRequestLogging()) - client.workspacesClient = opwc - - pipc := network.NewPublicIPAddressesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&pipc.Client) - pipc.Authorizer = auth - pipc.Sender = sender - client.publicIPClient = pipc - - sgc := network.NewSecurityGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sgc.Client) - sgc.Authorizer = auth - sgc.Sender = sender - client.secGroupClient = sgc - - src := network.NewSecurityRulesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&src.Client) - src.Authorizer = auth - src.Sender = sender - client.secRuleClient = src - - snc := network.NewSubnetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&snc.Client) - snc.Authorizer = auth - snc.Sender = sender - client.subnetClient = snc - - vgcc := network.NewVirtualNetworkGatewayConnectionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vgcc.Client) - vgcc.Authorizer = auth - vgcc.Sender = sender - client.vnetGatewayConnectionsClient = vgcc - - vgc := network.NewVirtualNetworkGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vgc.Client) - vgc.Authorizer = auth - vgc.Sender = sender - client.vnetGatewayClient = vgc - - vnc := network.NewVirtualNetworksClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vnc.Client) - vnc.Authorizer = auth - vnc.Sender = sender - client.vnetClient = vnc - - vnpc := network.NewVirtualNetworkPeeringsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vnpc.Client) - vnpc.Authorizer = auth - vnpc.Sender = sender - client.vnetPeeringsClient = vnpc - - rtc := network.NewRouteTablesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rtc.Client) - rtc.Authorizer = auth - rtc.Sender = sender - client.routeTablesClient = rtc - - rc := network.NewRoutesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rc.Client) - rc.Authorizer = auth - rc.Sender = sender - client.routesClient = rc - - dn := dns.NewRecordSetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&dn.Client) - dn.Authorizer = auth - dn.Sender = sender - client.dnsClient = dn - - zo := dns.NewZonesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&zo.Client) - zo.Authorizer = auth - zo.Sender = sender - client.zonesClient = zo - - rgc := resources.NewGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rgc.Client) - rgc.Authorizer = auth - rgc.Sender = sender - client.resourceGroupClient = rgc - - pc := resources.NewProvidersClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&pc.Client) - pc.Authorizer = auth - pc.Sender = sender - client.providers = pc - - tc := resources.NewTagsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tc.Client) - tc.Authorizer = auth - tc.Sender = sender - client.tagsClient = tc - - rf := resources.NewGroupClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rf.Client) - rf.Authorizer = auth - rf.Sender = sender - client.resourceFindClient = rf - - subgc := subscriptions.NewGroupClientWithBaseURI(endpoint) - setUserAgent(&subgc.Client) - subgc.Authorizer = auth - subgc.Sender = sender - client.subscriptionsGroupClient = subgc - - jc := scheduler.NewJobsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&jc.Client) - jc.Authorizer = auth - jc.Sender = sender - client.jobsClient = jc - - jcc := scheduler.NewJobCollectionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&jcc.Client) - jcc.Authorizer = auth - jcc.Sender = sender - client.jobsCollectionsClient = jcc - - ssc := storage.NewAccountsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ssc.Client) - ssc.Authorizer = auth - ssc.Sender = sender - client.storageServiceClient = ssc - - suc := storage.NewUsageClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&suc.Client) - suc.Authorizer = auth - suc.Sender = sender - client.storageUsageClient = suc - - cpc := cdn.NewProfilesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cpc.Client) - cpc.Authorizer = auth - cpc.Sender = sender - client.cdnProfilesClient = cpc - - cec := cdn.NewEndpointsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cec.Client) - cec.Authorizer = auth - cec.Sender = sender - client.cdnEndpointsClient = cec - - dc := resources.NewDeploymentsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&dc.Client) - dc.Authorizer = auth - dc.Sender = sender - client.deploymentsClient = dc - - tmpc := trafficmanager.NewProfilesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tmpc.Client) - tmpc.Authorizer = auth - tmpc.Sender = sender - client.trafficManagerProfilesClient = tmpc - - tmec := trafficmanager.NewEndpointsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tmec.Client) - tmec.Authorizer = auth - tmec.Sender = sender - client.trafficManagerEndpointsClient = tmec - - rdc := redis.NewGroupClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rdc.Client) - rdc.Authorizer = auth - rdc.Sender = sender - client.redisClient = rdc - - sesc := search.NewServicesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sesc.Client) - sesc.Authorizer = auth - sesc.Sender = sender - client.searchServicesClient = sesc - - sbnc := servicebus.NewNamespacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbnc.Client) - sbnc.Authorizer = auth - sbnc.Sender = sender - client.serviceBusNamespacesClient = sbnc - - sbqc := servicebus.NewQueuesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbqc.Client) - sbqc.Authorizer = auth - sbqc.Sender = sender - client.serviceBusQueuesClient = sbqc - - sbtc := servicebus.NewTopicsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbtc.Client) - sbtc.Authorizer = auth - sbtc.Sender = sender - client.serviceBusTopicsClient = sbtc - - sbsc := servicebus.NewSubscriptionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbsc.Client) - sbsc.Authorizer = auth - sbsc.Sender = sender - client.serviceBusSubscriptionsClient = sbsc - - aspc := web.NewAppServicePlansClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aspc.Client) - aspc.Authorizer = auth - aspc.Sender = sender - client.appServicePlansClient = aspc - - ac := web.NewAppsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ac.Client) - ac.Authorizer = auth - ac.Sender = autorest.CreateSender(withRequestLogging()) - client.appServicesClient = ac - - ai := appinsights.NewComponentsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ai.Client) - ai.Authorizer = auth - ai.Sender = sender - client.appInsightsClient = ai - - aadb := automation.NewAccountClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aadb.Client) - aadb.Authorizer = auth - aadb.Sender = sender - client.automationAccountClient = aadb - - arc := automation.NewRunbookClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&arc.Client) - arc.Authorizer = auth - arc.Sender = sender - client.automationRunbookClient = arc - - acc := automation.NewCredentialClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&acc.Client) - acc.Authorizer = auth - acc.Sender = sender - client.automationCredentialClient = acc - - aschc := automation.NewScheduleClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aschc.Client) - aschc.Authorizer = auth - aschc.Sender = sender - client.automationScheduleClient = aschc - -<<<<<<< HEAD -<<<<<<< HEAD - ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ihrc.Client) - ihrc.Authorizer = auth - ihrc.Sender = autorest.CreateSender(withRequestLogging()) - client.iothubResourceClient = ihrc - -======= -<<<<<<< HEAD - client.registerAuthentication(endpoint, graphEndpoint, c.SubscriptionID, c.TenantID, auth, graphAuth, sender) -||||||| merged common ancestors ->>>>>>> 60cd688486d722c6c36a4ee7155f24252405c0d8 - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - -======= -======= ->>>>>>> 0c2e6aafd710e9fe7024b76e0f64f43a10c0f15d - ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ihrc.Client) - ihrc.Authorizer = auth - ihrc.Sender = autorest.CreateSender(withRequestLogging()) - client.iothubResourceClient = ihrc - - client.registerAuthentication(endpoint, graphEndpoint, c.SubscriptionID, c.TenantID, auth, graphAuth, sender) - client.registerDatabases(endpoint, c.SubscriptionID, auth, sender) - client.registerDisks(endpoint, c.SubscriptionID, auth, sender) - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - - return &client, nil -} - -func (c *ArmClient) registerAuthentication(endpoint, graphEndpoint, subscriptionId, tenantId string, auth, graphAuth autorest.Authorizer, sender autorest.Sender) { - spc := graphrbac.NewServicePrincipalsClientWithBaseURI(graphEndpoint, tenantId) - setUserAgent(&spc.Client) - spc.Authorizer = graphAuth - spc.Sender = sender - c.servicePrincipalsClient = spc - - rac := authorization.NewRoleAssignmentsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&rac.Client) - rac.Authorizer = auth - rac.Sender = sender - c.roleAssignmentsClient = rac - - rdc := authorization.NewRoleDefinitionsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&rdc.Client) - rdc.Authorizer = auth - rdc.Sender = sender - c.roleDefinitionsClient = rdc -} - -func (c *ArmClient) registerDatabases(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { - // MySQL - mysqlConfigClient := mysql.NewConfigurationsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlConfigClient.Client) - mysqlConfigClient.Authorizer = auth - mysqlConfigClient.Sender = sender - c.mysqlConfigurationsClient = mysqlConfigClient - - mysqlDBClient := mysql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlDBClient.Client) - mysqlDBClient.Authorizer = auth - mysqlDBClient.Sender = sender - c.mysqlDatabasesClient = mysqlDBClient - - mysqlFWClient := mysql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlFWClient.Client) - mysqlFWClient.Authorizer = auth - mysqlFWClient.Sender = sender - c.mysqlFirewallRulesClient = mysqlFWClient - - mysqlServersClient := mysql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlServersClient.Client) - mysqlServersClient.Authorizer = auth - mysqlServersClient.Sender = sender - c.mysqlServersClient = mysqlServersClient - - // PostgreSQL - postgresqlConfigClient := postgresql.NewConfigurationsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlConfigClient.Client) - postgresqlConfigClient.Authorizer = auth - postgresqlConfigClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlConfigurationsClient = postgresqlConfigClient - - postgresqlDBClient := postgresql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlDBClient.Client) - postgresqlDBClient.Authorizer = auth - postgresqlDBClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlDatabasesClient = postgresqlDBClient - - postgresqlFWClient := postgresql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlFWClient.Client) - postgresqlFWClient.Authorizer = auth - postgresqlFWClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlFirewallRulesClient = postgresqlFWClient - - postgresqlSrvClient := postgresql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlSrvClient.Client) - postgresqlSrvClient.Authorizer = auth - postgresqlSrvClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlServersClient = postgresqlSrvClient - - // SQL Azure - sqlDBClient := sql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlDBClient.Client) - sqlDBClient.Authorizer = auth - sqlDBClient.Sender = sender - c.sqlDatabasesClient = sqlDBClient - - sqlFWClient := sql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlFWClient.Client) - sqlFWClient.Authorizer = auth - sqlFWClient.Sender = sender - c.sqlFirewallRulesClient = sqlFWClient - - sqlEPClient := sql.NewElasticPoolsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlEPClient.Client) - sqlEPClient.Authorizer = auth - sqlEPClient.Sender = sender - c.sqlElasticPoolsClient = sqlEPClient - - sqlSrvClient := sql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlSrvClient.Client) - sqlSrvClient.Authorizer = auth - sqlSrvClient.Sender = sender - c.sqlServersClient = sqlSrvClient -} - -func (c *ArmClient) registerDisks(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { - diskClient := disk.NewDisksClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&diskClient.Client) - diskClient.Authorizer = auth - diskClient.Sender = sender - c.diskClient = diskClient - - snapshotsClient := disk.NewSnapshotsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&snapshotsClient.Client) - snapshotsClient.Authorizer = auth - snapshotsClient.Sender = sender - c.snapshotsClient = snapshotsClient -} - -func (c *ArmClient) registerKeyVaultClients(endpoint, subscriptionId string, auth autorest.Authorizer, keyVaultAuth autorest.Authorizer, sender autorest.Sender) { - keyVaultClient := keyvault.NewVaultsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&keyVaultClient.Client) - keyVaultClient.Authorizer = auth - keyVaultClient.Sender = sender - c.keyVaultClient = keyVaultClient - - keyVaultManagementClient := keyVault.New() - setUserAgent(&keyVaultManagementClient.Client) - keyVaultManagementClient.Authorizer = keyVaultAuth - keyVaultManagementClient.Sender = sender - c.keyVaultManagementClient = keyVaultManagementClient -} - -func (armClient *ArmClient) getKeyForStorageAccount(resourceGroupName, storageAccountName string) (string, bool, error) { - accountKeys, err := armClient.storageServiceClient.ListKeys(resourceGroupName, storageAccountName) - if accountKeys.StatusCode == http.StatusNotFound { - return "", false, nil - } - if err != nil { - // We assume this is a transient error rather than a 404 (which is caught above), so assume the - // account still exists. - return "", true, fmt.Errorf("Error retrieving keys for storage account %q: %s", storageAccountName, err) - } - - if accountKeys.Keys == nil { - return "", false, fmt.Errorf("Nil key returned for storage account %q", storageAccountName) - } - - keys := *accountKeys.Keys - return *keys[0].Value, true, nil -} - -func (armClient *ArmClient) getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.BlobStorageClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - blobClient := storageClient.GetBlobService() - return &blobClient, true, nil -} - -func (armClient *ArmClient) getFileServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.FileServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - fileClient := storageClient.GetFileService() - return &fileClient, true, nil -} - -func (armClient *ArmClient) getTableServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.TableServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - tableClient := storageClient.GetTableService() - return &tableClient, true, nil -} - -func (armClient *ArmClient) getQueueServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.QueueServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - queueClient := storageClient.GetQueueService() - return &queueClient, true, nil -} diff --git a/azurerm/config_BASE_7053.go b/azurerm/config_BASE_7053.go deleted file mode 100644 index 54c77c37838d..000000000000 --- a/azurerm/config_BASE_7053.go +++ /dev/null @@ -1,895 +0,0 @@ -package azurerm - -import ( - "context" - "fmt" - "log" - "net/http" - "net/http/httputil" - - "github.com/Azure/azure-sdk-for-go/arm/iothub" - - "github.com/Azure/azure-sdk-for-go/arm/appinsights" - "github.com/Azure/azure-sdk-for-go/arm/authorization" - "github.com/Azure/azure-sdk-for-go/arm/automation" - "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/containerinstance" - "github.com/Azure/azure-sdk-for-go/arm/containerregistry" - "github.com/Azure/azure-sdk-for-go/arm/containerservice" - "github.com/Azure/azure-sdk-for-go/arm/cosmos-db" - "github.com/Azure/azure-sdk-for-go/arm/disk" - "github.com/Azure/azure-sdk-for-go/arm/dns" - "github.com/Azure/azure-sdk-for-go/arm/eventgrid" - "github.com/Azure/azure-sdk-for-go/arm/eventhub" - "github.com/Azure/azure-sdk-for-go/arm/graphrbac" - "github.com/Azure/azure-sdk-for-go/arm/keyvault" - "github.com/Azure/azure-sdk-for-go/arm/mysql" - "github.com/Azure/azure-sdk-for-go/arm/network" - "github.com/Azure/azure-sdk-for-go/arm/operationalinsights" - "github.com/Azure/azure-sdk-for-go/arm/postgresql" - "github.com/Azure/azure-sdk-for-go/arm/redis" - "github.com/Azure/azure-sdk-for-go/arm/resources/resources" - "github.com/Azure/azure-sdk-for-go/arm/resources/subscriptions" - "github.com/Azure/azure-sdk-for-go/arm/scheduler" - "github.com/Azure/azure-sdk-for-go/arm/search" - "github.com/Azure/azure-sdk-for-go/arm/servicebus" - "github.com/Azure/azure-sdk-for-go/arm/sql" - "github.com/Azure/azure-sdk-for-go/arm/storage" - "github.com/Azure/azure-sdk-for-go/arm/trafficmanager" - "github.com/Azure/azure-sdk-for-go/arm/web" - keyVault "github.com/Azure/azure-sdk-for-go/dataplane/keyvault" - mainStorage "github.com/Azure/azure-sdk-for-go/storage" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/hashicorp/terraform/terraform" -) - -// ArmClient contains the handles to all the specific Azure Resource Manager -// resource classes' respective clients. -type ArmClient struct { - clientId string - tenantId string - subscriptionId string - usingServicePrincipal bool - environment azure.Environment - - StopContext context.Context - - availSetClient compute.AvailabilitySetsClient - usageOpsClient compute.UsageClient - vmExtensionImageClient compute.VirtualMachineExtensionImagesClient - vmExtensionClient compute.VirtualMachineExtensionsClient - vmScaleSetClient compute.VirtualMachineScaleSetsClient - vmImageClient compute.VirtualMachineImagesClient - vmClient compute.VirtualMachinesClient - imageClient compute.ImagesClient - - diskClient disk.DisksClient - snapshotsClient disk.SnapshotsClient - cosmosDBClient cosmosdb.DatabaseAccountsClient - automationAccountClient automation.AccountClient - automationRunbookClient automation.RunbookClient - automationCredentialClient automation.CredentialClient - automationScheduleClient automation.ScheduleClient - - appGatewayClient network.ApplicationGatewaysClient - ifaceClient network.InterfacesClient - expressRouteCircuitClient network.ExpressRouteCircuitsClient - loadBalancerClient network.LoadBalancersClient - localNetConnClient network.LocalNetworkGatewaysClient - publicIPClient network.PublicIPAddressesClient - secGroupClient network.SecurityGroupsClient - secRuleClient network.SecurityRulesClient - subnetClient network.SubnetsClient - netUsageClient network.UsagesClient - vnetGatewayConnectionsClient network.VirtualNetworkGatewayConnectionsClient - vnetGatewayClient network.VirtualNetworkGatewaysClient - vnetClient network.VirtualNetworksClient - vnetPeeringsClient network.VirtualNetworkPeeringsClient - routeTablesClient network.RouteTablesClient - routesClient network.RoutesClient - dnsClient dns.RecordSetsClient - zonesClient dns.ZonesClient - - cdnProfilesClient cdn.ProfilesClient - cdnEndpointsClient cdn.EndpointsClient - - containerRegistryClient containerregistry.RegistriesClient - containerServicesClient containerservice.ContainerServicesClient - containerGroupsClient containerinstance.ContainerGroupsClient - - eventGridTopicsClient eventgrid.TopicsClient - eventHubClient eventhub.EventHubsClient - eventHubConsumerGroupClient eventhub.ConsumerGroupsClient - eventHubNamespacesClient eventhub.NamespacesClient - - workspacesClient operationalinsights.WorkspacesClient - - providers resources.ProvidersClient - resourceGroupClient resources.GroupsClient - tagsClient resources.TagsClient - resourceFindClient resources.GroupClient - - subscriptionsGroupClient subscriptions.GroupClient - - jobsClient scheduler.JobsClient - jobsCollectionsClient scheduler.JobCollectionsClient - - storageServiceClient storage.AccountsClient - storageUsageClient storage.UsageClient - - deploymentsClient resources.DeploymentsClient - - redisClient redis.GroupClient - - trafficManagerProfilesClient trafficmanager.ProfilesClient - trafficManagerEndpointsClient trafficmanager.EndpointsClient - - searchServicesClient search.ServicesClient - serviceBusNamespacesClient servicebus.NamespacesClient - serviceBusQueuesClient servicebus.QueuesClient - serviceBusTopicsClient servicebus.TopicsClient - serviceBusSubscriptionsClient servicebus.SubscriptionsClient - - keyVaultClient keyvault.VaultsClient - keyVaultManagementClient keyVault.ManagementClient - - appServicePlansClient web.AppServicePlansClient - appServicesClient web.AppsClient - - appInsightsClient appinsights.ComponentsClient - - // Authentication - roleAssignmentsClient authorization.RoleAssignmentsClient - roleDefinitionsClient authorization.RoleDefinitionsClient - servicePrincipalsClient graphrbac.ServicePrincipalsClient - - // Databases - mysqlConfigurationsClient mysql.ConfigurationsClient - mysqlDatabasesClient mysql.DatabasesClient - mysqlFirewallRulesClient mysql.FirewallRulesClient - mysqlServersClient mysql.ServersClient - postgresqlConfigurationsClient postgresql.ConfigurationsClient - postgresqlDatabasesClient postgresql.DatabasesClient - postgresqlFirewallRulesClient postgresql.FirewallRulesClient - postgresqlServersClient postgresql.ServersClient - sqlDatabasesClient sql.DatabasesClient - sqlElasticPoolsClient sql.ElasticPoolsClient - sqlFirewallRulesClient sql.FirewallRulesClient - sqlServersClient sql.ServersClient - iothubResourceClient iothub.ResourceClient -} - -func withRequestLogging() autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - // dump request to wire format - if dump, err := httputil.DumpRequestOut(r, true); err == nil { - log.Printf("[DEBUG] AzureRM Request: \n%s\n", dump) - } else { - // fallback to basic message - log.Printf("[DEBUG] AzureRM Request: %s to %s\n", r.Method, r.URL) - } - - resp, err := s.Do(r) - if resp != nil { - // dump response to wire format - if dump, err := httputil.DumpResponse(resp, true); err == nil { - log.Printf("[DEBUG] AzureRM Response for %s: \n%s\n", r.URL, dump) - } else { - // fallback to basic message - log.Printf("[DEBUG] AzureRM Response: %s for %s\n", resp.Status, r.URL) - } - } else { - log.Printf("[DEBUG] Request to %s completed with no response", r.URL) - } - return resp, err - }) - } -} - -func setUserAgent(client *autorest.Client) { - version := terraform.VersionString() - client.UserAgent = fmt.Sprintf("HashiCorp-Terraform-v%s", version) -} - -func (c *Config) getAuthorizationToken(oauthConfig *adal.OAuthConfig, endpoint string) (*autorest.BearerAuthorizer, error) { - useServicePrincipal := c.ClientSecret != "" - - if useServicePrincipal { - spt, err := adal.NewServicePrincipalToken(*oauthConfig, c.ClientID, c.ClientSecret, endpoint) - if err != nil { - return nil, err - } - - auth := autorest.NewBearerAuthorizer(spt) - return auth, nil - } - - if c.IsCloudShell { - // load the refreshed tokens from the Azure CLI - err := c.LoadTokensFromAzureCLI() - if err != nil { - return nil, fmt.Errorf("Error loading the refreshed CloudShell tokens: %+v", err) - } - } - - spt, err := adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, c.ClientID, endpoint, *c.AccessToken) - if err != nil { - return nil, err - } - - auth := autorest.NewBearerAuthorizer(spt) - return auth, nil -} - -// getArmClient is a helper method which returns a fully instantiated -// *ArmClient based on the Config's current settings. -func (c *Config) getArmClient() (*ArmClient, error) { - // detect cloud from environment - env, envErr := azure.EnvironmentFromName(c.Environment) - if envErr != nil { - // try again with wrapped value to support readable values like german instead of AZUREGERMANCLOUD - wrapped := fmt.Sprintf("AZURE%sCLOUD", c.Environment) - var innerErr error - if env, innerErr = azure.EnvironmentFromName(wrapped); innerErr != nil { - return nil, envErr - } - } - - // client declarations: - client := ArmClient{ - clientId: c.ClientID, - tenantId: c.TenantID, - subscriptionId: c.SubscriptionID, - environment: env, - usingServicePrincipal: c.ClientSecret != "", - } - - oauthConfig, err := adal.NewOAuthConfig(env.ActiveDirectoryEndpoint, c.TenantID) - if err != nil { - return nil, err - } - - // OAuthConfigForTenant returns a pointer, which can be nil. - if oauthConfig == nil { - return nil, fmt.Errorf("Unable to configure OAuthConfig for tenant %s", c.TenantID) - } - - sender := autorest.CreateSender(withRequestLogging()) - - // Resource Manager endpoints - endpoint := env.ResourceManagerEndpoint - auth, err := c.getAuthorizationToken(oauthConfig, endpoint) - if err != nil { - return nil, err - } - - // Graph Endpoints - graphEndpoint := env.GraphEndpoint - graphAuth, err := c.getAuthorizationToken(oauthConfig, graphEndpoint) - if err != nil { - return nil, err - } - - // Key Vault Endpoints - keyVaultAuth := autorest.NewBearerAuthorizerCallback(sender, func(tenantID, resource string) (*autorest.BearerAuthorizer, error) { - keyVaultSpt, err := c.getAuthorizationToken(oauthConfig, resource) - if err != nil { - return nil, err - } - - return keyVaultSpt, nil - }) - - // NOTE: these declarations should be left separate for clarity should the - // clients be wished to be configured with custom Responders/PollingModes etc... - asc := compute.NewAvailabilitySetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&asc.Client) - asc.Authorizer = auth - asc.Sender = sender - client.availSetClient = asc - - uoc := compute.NewUsageClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&uoc.Client) - uoc.Authorizer = auth - uoc.Sender = sender - client.usageOpsClient = uoc - - vmeic := compute.NewVirtualMachineExtensionImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmeic.Client) - vmeic.Authorizer = auth - vmeic.Sender = sender - client.vmExtensionImageClient = vmeic - - vmec := compute.NewVirtualMachineExtensionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmec.Client) - vmec.Authorizer = auth - vmec.Sender = sender - client.vmExtensionClient = vmec - - vmic := compute.NewVirtualMachineImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmic.Client) - vmic.Authorizer = auth - vmic.Sender = sender - client.vmImageClient = vmic - - vmssc := compute.NewVirtualMachineScaleSetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmssc.Client) - vmssc.Authorizer = auth - vmssc.Sender = sender - client.vmScaleSetClient = vmssc - - vmc := compute.NewVirtualMachinesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmc.Client) - vmc.Authorizer = auth - vmc.Sender = sender - client.vmClient = vmc - - agc := network.NewApplicationGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&agc.Client) - agc.Authorizer = auth - agc.Sender = sender - client.appGatewayClient = agc - - crc := containerregistry.NewRegistriesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&crc.Client) - crc.Authorizer = auth - crc.Sender = sender - client.containerRegistryClient = crc - - csc := containerservice.NewContainerServicesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&csc.Client) - csc.Authorizer = auth - csc.Sender = sender - client.containerServicesClient = csc - - cgc := containerinstance.NewContainerGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cgc.Client) - cgc.Authorizer = auth - cgc.Sender = autorest.CreateSender(withRequestLogging()) - client.containerGroupsClient = cgc - - cdb := cosmosdb.NewDatabaseAccountsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cdb.Client) - cdb.Authorizer = auth - cdb.Sender = sender - client.cosmosDBClient = cdb - - img := compute.NewImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&img.Client) - img.Authorizer = auth - img.Sender = sender - client.imageClient = img - - egtc := eventgrid.NewTopicsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&egtc.Client) - egtc.Authorizer = auth - egtc.Sender = sender - client.eventGridTopicsClient = egtc - - ehc := eventhub.NewEventHubsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ehc.Client) - ehc.Authorizer = auth - ehc.Sender = sender - client.eventHubClient = ehc - - chcgc := eventhub.NewConsumerGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&chcgc.Client) - chcgc.Authorizer = auth - chcgc.Sender = sender - client.eventHubConsumerGroupClient = chcgc - - ehnc := eventhub.NewNamespacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ehnc.Client) - ehnc.Authorizer = auth - ehnc.Sender = sender - client.eventHubNamespacesClient = ehnc - - ifc := network.NewInterfacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ifc.Client) - ifc.Authorizer = auth - ifc.Sender = sender - client.ifaceClient = ifc - - erc := network.NewExpressRouteCircuitsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&erc.Client) - erc.Authorizer = auth - erc.Sender = sender - client.expressRouteCircuitClient = erc - - lbc := network.NewLoadBalancersClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&lbc.Client) - lbc.Authorizer = auth - lbc.Sender = sender - client.loadBalancerClient = lbc - - lgc := network.NewLocalNetworkGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&lgc.Client) - lgc.Authorizer = auth - lgc.Sender = sender - client.localNetConnClient = lgc - - opwc := operationalinsights.NewWorkspacesClient(c.SubscriptionID) - setUserAgent(&opwc.Client) - opwc.Authorizer = auth - opwc.Sender = autorest.CreateSender(withRequestLogging()) - client.workspacesClient = opwc - - pipc := network.NewPublicIPAddressesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&pipc.Client) - pipc.Authorizer = auth - pipc.Sender = sender - client.publicIPClient = pipc - - sgc := network.NewSecurityGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sgc.Client) - sgc.Authorizer = auth - sgc.Sender = sender - client.secGroupClient = sgc - - src := network.NewSecurityRulesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&src.Client) - src.Authorizer = auth - src.Sender = sender - client.secRuleClient = src - - snc := network.NewSubnetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&snc.Client) - snc.Authorizer = auth - snc.Sender = sender - client.subnetClient = snc - - vgcc := network.NewVirtualNetworkGatewayConnectionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vgcc.Client) - vgcc.Authorizer = auth - vgcc.Sender = sender - client.vnetGatewayConnectionsClient = vgcc - - vgc := network.NewVirtualNetworkGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vgc.Client) - vgc.Authorizer = auth - vgc.Sender = sender - client.vnetGatewayClient = vgc - - vnc := network.NewVirtualNetworksClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vnc.Client) - vnc.Authorizer = auth - vnc.Sender = sender - client.vnetClient = vnc - - vnpc := network.NewVirtualNetworkPeeringsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vnpc.Client) - vnpc.Authorizer = auth - vnpc.Sender = sender - client.vnetPeeringsClient = vnpc - - rtc := network.NewRouteTablesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rtc.Client) - rtc.Authorizer = auth - rtc.Sender = sender - client.routeTablesClient = rtc - - rc := network.NewRoutesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rc.Client) - rc.Authorizer = auth - rc.Sender = sender - client.routesClient = rc - - dn := dns.NewRecordSetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&dn.Client) - dn.Authorizer = auth - dn.Sender = sender - client.dnsClient = dn - - zo := dns.NewZonesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&zo.Client) - zo.Authorizer = auth - zo.Sender = sender - client.zonesClient = zo - - rgc := resources.NewGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rgc.Client) - rgc.Authorizer = auth - rgc.Sender = sender - client.resourceGroupClient = rgc - - pc := resources.NewProvidersClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&pc.Client) - pc.Authorizer = auth - pc.Sender = sender - client.providers = pc - - tc := resources.NewTagsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tc.Client) - tc.Authorizer = auth - tc.Sender = sender - client.tagsClient = tc - - rf := resources.NewGroupClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rf.Client) - rf.Authorizer = auth - rf.Sender = sender - client.resourceFindClient = rf - - subgc := subscriptions.NewGroupClientWithBaseURI(endpoint) - setUserAgent(&subgc.Client) - subgc.Authorizer = auth - subgc.Sender = sender - client.subscriptionsGroupClient = subgc - - jc := scheduler.NewJobsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&jc.Client) - jc.Authorizer = auth - jc.Sender = sender - client.jobsClient = jc - - jcc := scheduler.NewJobCollectionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&jcc.Client) - jcc.Authorizer = auth - jcc.Sender = sender - client.jobsCollectionsClient = jcc - - ssc := storage.NewAccountsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ssc.Client) - ssc.Authorizer = auth - ssc.Sender = sender - client.storageServiceClient = ssc - - suc := storage.NewUsageClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&suc.Client) - suc.Authorizer = auth - suc.Sender = sender - client.storageUsageClient = suc - - cpc := cdn.NewProfilesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cpc.Client) - cpc.Authorizer = auth - cpc.Sender = sender - client.cdnProfilesClient = cpc - - cec := cdn.NewEndpointsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cec.Client) - cec.Authorizer = auth - cec.Sender = sender - client.cdnEndpointsClient = cec - - dc := resources.NewDeploymentsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&dc.Client) - dc.Authorizer = auth - dc.Sender = sender - client.deploymentsClient = dc - - tmpc := trafficmanager.NewProfilesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tmpc.Client) - tmpc.Authorizer = auth - tmpc.Sender = sender - client.trafficManagerProfilesClient = tmpc - - tmec := trafficmanager.NewEndpointsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tmec.Client) - tmec.Authorizer = auth - tmec.Sender = sender - client.trafficManagerEndpointsClient = tmec - - rdc := redis.NewGroupClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rdc.Client) - rdc.Authorizer = auth - rdc.Sender = sender - client.redisClient = rdc - - sesc := search.NewServicesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sesc.Client) - sesc.Authorizer = auth - sesc.Sender = sender - client.searchServicesClient = sesc - - sbnc := servicebus.NewNamespacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbnc.Client) - sbnc.Authorizer = auth - sbnc.Sender = sender - client.serviceBusNamespacesClient = sbnc - - sbqc := servicebus.NewQueuesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbqc.Client) - sbqc.Authorizer = auth - sbqc.Sender = sender - client.serviceBusQueuesClient = sbqc - - sbtc := servicebus.NewTopicsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbtc.Client) - sbtc.Authorizer = auth - sbtc.Sender = sender - client.serviceBusTopicsClient = sbtc - - sbsc := servicebus.NewSubscriptionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbsc.Client) - sbsc.Authorizer = auth - sbsc.Sender = sender - client.serviceBusSubscriptionsClient = sbsc - - aspc := web.NewAppServicePlansClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aspc.Client) - aspc.Authorizer = auth - aspc.Sender = sender - client.appServicePlansClient = aspc - - ac := web.NewAppsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ac.Client) - ac.Authorizer = auth - ac.Sender = autorest.CreateSender(withRequestLogging()) - client.appServicesClient = ac - - ai := appinsights.NewComponentsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ai.Client) - ai.Authorizer = auth - ai.Sender = sender - client.appInsightsClient = ai - - aadb := automation.NewAccountClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aadb.Client) - aadb.Authorizer = auth - aadb.Sender = sender - client.automationAccountClient = aadb - - arc := automation.NewRunbookClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&arc.Client) - arc.Authorizer = auth - arc.Sender = sender - client.automationRunbookClient = arc - - acc := automation.NewCredentialClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&acc.Client) - acc.Authorizer = auth - acc.Sender = sender - client.automationCredentialClient = acc - - aschc := automation.NewScheduleClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aschc.Client) - aschc.Authorizer = auth - aschc.Sender = sender - client.automationScheduleClient = aschc - -<<<<<<< HEAD - client.registerAuthentication(endpoint, graphEndpoint, c.SubscriptionID, c.TenantID, auth, graphAuth, sender) -||||||| merged common ancestors - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - -======= - ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ihrc.Client) - ihrc.Authorizer = auth - ihrc.Sender = autorest.CreateSender(withRequestLogging()) - client.iothubResourceClient = ihrc - - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - ->>>>>>> added the config and cleaned up the schema iothub resource schema - client.registerDatabases(endpoint, c.SubscriptionID, auth, sender) - client.registerDisks(endpoint, c.SubscriptionID, auth, sender) - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - - return &client, nil -} - -func (c *ArmClient) registerAuthentication(endpoint, graphEndpoint, subscriptionId, tenantId string, auth, graphAuth autorest.Authorizer, sender autorest.Sender) { - spc := graphrbac.NewServicePrincipalsClientWithBaseURI(graphEndpoint, tenantId) - setUserAgent(&spc.Client) - spc.Authorizer = graphAuth - spc.Sender = sender - c.servicePrincipalsClient = spc - - rac := authorization.NewRoleAssignmentsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&rac.Client) - rac.Authorizer = auth - rac.Sender = sender - c.roleAssignmentsClient = rac - - rdc := authorization.NewRoleDefinitionsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&rdc.Client) - rdc.Authorizer = auth - rdc.Sender = sender - c.roleDefinitionsClient = rdc -} - -func (c *ArmClient) registerDatabases(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { - // MySQL - mysqlConfigClient := mysql.NewConfigurationsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlConfigClient.Client) - mysqlConfigClient.Authorizer = auth - mysqlConfigClient.Sender = sender - c.mysqlConfigurationsClient = mysqlConfigClient - - mysqlDBClient := mysql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlDBClient.Client) - mysqlDBClient.Authorizer = auth - mysqlDBClient.Sender = sender - c.mysqlDatabasesClient = mysqlDBClient - - mysqlFWClient := mysql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlFWClient.Client) - mysqlFWClient.Authorizer = auth - mysqlFWClient.Sender = sender - c.mysqlFirewallRulesClient = mysqlFWClient - - mysqlServersClient := mysql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlServersClient.Client) - mysqlServersClient.Authorizer = auth - mysqlServersClient.Sender = sender - c.mysqlServersClient = mysqlServersClient - - // PostgreSQL - postgresqlConfigClient := postgresql.NewConfigurationsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlConfigClient.Client) - postgresqlConfigClient.Authorizer = auth - postgresqlConfigClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlConfigurationsClient = postgresqlConfigClient - - postgresqlDBClient := postgresql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlDBClient.Client) - postgresqlDBClient.Authorizer = auth - postgresqlDBClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlDatabasesClient = postgresqlDBClient - - postgresqlFWClient := postgresql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlFWClient.Client) - postgresqlFWClient.Authorizer = auth - postgresqlFWClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlFirewallRulesClient = postgresqlFWClient - - postgresqlSrvClient := postgresql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlSrvClient.Client) - postgresqlSrvClient.Authorizer = auth - postgresqlSrvClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlServersClient = postgresqlSrvClient - - // SQL Azure - sqlDBClient := sql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlDBClient.Client) - sqlDBClient.Authorizer = auth - sqlDBClient.Sender = sender - c.sqlDatabasesClient = sqlDBClient - - sqlFWClient := sql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlFWClient.Client) - sqlFWClient.Authorizer = auth - sqlFWClient.Sender = sender - c.sqlFirewallRulesClient = sqlFWClient - - sqlEPClient := sql.NewElasticPoolsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlEPClient.Client) - sqlEPClient.Authorizer = auth - sqlEPClient.Sender = sender - c.sqlElasticPoolsClient = sqlEPClient - - sqlSrvClient := sql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlSrvClient.Client) - sqlSrvClient.Authorizer = auth - sqlSrvClient.Sender = sender - c.sqlServersClient = sqlSrvClient -} - -func (c *ArmClient) registerDisks(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { - diskClient := disk.NewDisksClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&diskClient.Client) - diskClient.Authorizer = auth - diskClient.Sender = sender - c.diskClient = diskClient - - snapshotsClient := disk.NewSnapshotsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&snapshotsClient.Client) - snapshotsClient.Authorizer = auth - snapshotsClient.Sender = sender - c.snapshotsClient = snapshotsClient -} - -func (c *ArmClient) registerKeyVaultClients(endpoint, subscriptionId string, auth autorest.Authorizer, keyVaultAuth autorest.Authorizer, sender autorest.Sender) { - keyVaultClient := keyvault.NewVaultsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&keyVaultClient.Client) - keyVaultClient.Authorizer = auth - keyVaultClient.Sender = sender - c.keyVaultClient = keyVaultClient - - keyVaultManagementClient := keyVault.New() - setUserAgent(&keyVaultManagementClient.Client) - keyVaultManagementClient.Authorizer = keyVaultAuth - keyVaultManagementClient.Sender = sender - c.keyVaultManagementClient = keyVaultManagementClient -} - -func (armClient *ArmClient) getKeyForStorageAccount(resourceGroupName, storageAccountName string) (string, bool, error) { - accountKeys, err := armClient.storageServiceClient.ListKeys(resourceGroupName, storageAccountName) - if accountKeys.StatusCode == http.StatusNotFound { - return "", false, nil - } - if err != nil { - // We assume this is a transient error rather than a 404 (which is caught above), so assume the - // account still exists. - return "", true, fmt.Errorf("Error retrieving keys for storage account %q: %s", storageAccountName, err) - } - - if accountKeys.Keys == nil { - return "", false, fmt.Errorf("Nil key returned for storage account %q", storageAccountName) - } - - keys := *accountKeys.Keys - return *keys[0].Value, true, nil -} - -func (armClient *ArmClient) getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.BlobStorageClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - blobClient := storageClient.GetBlobService() - return &blobClient, true, nil -} - -func (armClient *ArmClient) getFileServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.FileServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - fileClient := storageClient.GetFileService() - return &fileClient, true, nil -} - -func (armClient *ArmClient) getTableServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.TableServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - tableClient := storageClient.GetTableService() - return &tableClient, true, nil -} - -func (armClient *ArmClient) getQueueServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.QueueServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - queueClient := storageClient.GetQueueService() - return &queueClient, true, nil -} diff --git a/azurerm/config_LOCAL_7053.go b/azurerm/config_LOCAL_7053.go deleted file mode 100644 index 7b69c24fd47a..000000000000 --- a/azurerm/config_LOCAL_7053.go +++ /dev/null @@ -1,904 +0,0 @@ -package azurerm - -import ( - "context" - "fmt" - "log" - "net/http" - "net/http/httputil" - - "github.com/Azure/azure-sdk-for-go/arm/iothub" - - "github.com/Azure/azure-sdk-for-go/arm/appinsights" - "github.com/Azure/azure-sdk-for-go/arm/authorization" - "github.com/Azure/azure-sdk-for-go/arm/automation" - "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/containerinstance" - "github.com/Azure/azure-sdk-for-go/arm/containerregistry" - "github.com/Azure/azure-sdk-for-go/arm/containerservice" - "github.com/Azure/azure-sdk-for-go/arm/cosmos-db" - "github.com/Azure/azure-sdk-for-go/arm/disk" - "github.com/Azure/azure-sdk-for-go/arm/dns" - "github.com/Azure/azure-sdk-for-go/arm/eventgrid" - "github.com/Azure/azure-sdk-for-go/arm/eventhub" - "github.com/Azure/azure-sdk-for-go/arm/graphrbac" - "github.com/Azure/azure-sdk-for-go/arm/keyvault" - "github.com/Azure/azure-sdk-for-go/arm/mysql" - "github.com/Azure/azure-sdk-for-go/arm/network" - "github.com/Azure/azure-sdk-for-go/arm/operationalinsights" - "github.com/Azure/azure-sdk-for-go/arm/postgresql" - "github.com/Azure/azure-sdk-for-go/arm/redis" - "github.com/Azure/azure-sdk-for-go/arm/resources/resources" - "github.com/Azure/azure-sdk-for-go/arm/resources/subscriptions" - "github.com/Azure/azure-sdk-for-go/arm/scheduler" - "github.com/Azure/azure-sdk-for-go/arm/search" - "github.com/Azure/azure-sdk-for-go/arm/servicebus" - "github.com/Azure/azure-sdk-for-go/arm/sql" - "github.com/Azure/azure-sdk-for-go/arm/storage" - "github.com/Azure/azure-sdk-for-go/arm/trafficmanager" - "github.com/Azure/azure-sdk-for-go/arm/web" - keyVault "github.com/Azure/azure-sdk-for-go/dataplane/keyvault" - mainStorage "github.com/Azure/azure-sdk-for-go/storage" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/hashicorp/terraform/terraform" -) - -// ArmClient contains the handles to all the specific Azure Resource Manager -// resource classes' respective clients. -type ArmClient struct { - clientId string - tenantId string - subscriptionId string - usingServicePrincipal bool - environment azure.Environment - - StopContext context.Context - - availSetClient compute.AvailabilitySetsClient - usageOpsClient compute.UsageClient - vmExtensionImageClient compute.VirtualMachineExtensionImagesClient - vmExtensionClient compute.VirtualMachineExtensionsClient - vmScaleSetClient compute.VirtualMachineScaleSetsClient - vmImageClient compute.VirtualMachineImagesClient - vmClient compute.VirtualMachinesClient - imageClient compute.ImagesClient - - diskClient disk.DisksClient - snapshotsClient disk.SnapshotsClient - cosmosDBClient cosmosdb.DatabaseAccountsClient - automationAccountClient automation.AccountClient - automationRunbookClient automation.RunbookClient - automationCredentialClient automation.CredentialClient - automationScheduleClient automation.ScheduleClient - - appGatewayClient network.ApplicationGatewaysClient - ifaceClient network.InterfacesClient - expressRouteCircuitClient network.ExpressRouteCircuitsClient - loadBalancerClient network.LoadBalancersClient - localNetConnClient network.LocalNetworkGatewaysClient - publicIPClient network.PublicIPAddressesClient - secGroupClient network.SecurityGroupsClient - secRuleClient network.SecurityRulesClient - subnetClient network.SubnetsClient - netUsageClient network.UsagesClient - vnetGatewayConnectionsClient network.VirtualNetworkGatewayConnectionsClient - vnetGatewayClient network.VirtualNetworkGatewaysClient - vnetClient network.VirtualNetworksClient - vnetPeeringsClient network.VirtualNetworkPeeringsClient - routeTablesClient network.RouteTablesClient - routesClient network.RoutesClient - dnsClient dns.RecordSetsClient - zonesClient dns.ZonesClient - - cdnProfilesClient cdn.ProfilesClient - cdnEndpointsClient cdn.EndpointsClient - - containerRegistryClient containerregistry.RegistriesClient - containerServicesClient containerservice.ContainerServicesClient - containerGroupsClient containerinstance.ContainerGroupsClient - - eventGridTopicsClient eventgrid.TopicsClient - eventHubClient eventhub.EventHubsClient - eventHubConsumerGroupClient eventhub.ConsumerGroupsClient - eventHubNamespacesClient eventhub.NamespacesClient - - workspacesClient operationalinsights.WorkspacesClient - - providers resources.ProvidersClient - resourceGroupClient resources.GroupsClient - tagsClient resources.TagsClient - resourceFindClient resources.GroupClient - - subscriptionsGroupClient subscriptions.GroupClient - - jobsClient scheduler.JobsClient - jobsCollectionsClient scheduler.JobCollectionsClient - - storageServiceClient storage.AccountsClient - storageUsageClient storage.UsageClient - - deploymentsClient resources.DeploymentsClient - - redisClient redis.GroupClient - - trafficManagerProfilesClient trafficmanager.ProfilesClient - trafficManagerEndpointsClient trafficmanager.EndpointsClient - - searchServicesClient search.ServicesClient - serviceBusNamespacesClient servicebus.NamespacesClient - serviceBusQueuesClient servicebus.QueuesClient - serviceBusTopicsClient servicebus.TopicsClient - serviceBusSubscriptionsClient servicebus.SubscriptionsClient - - keyVaultClient keyvault.VaultsClient - keyVaultManagementClient keyVault.ManagementClient - - appServicePlansClient web.AppServicePlansClient - appServicesClient web.AppsClient - - appInsightsClient appinsights.ComponentsClient - - // Authentication - roleAssignmentsClient authorization.RoleAssignmentsClient - roleDefinitionsClient authorization.RoleDefinitionsClient - servicePrincipalsClient graphrbac.ServicePrincipalsClient - - // Databases - mysqlConfigurationsClient mysql.ConfigurationsClient - mysqlDatabasesClient mysql.DatabasesClient - mysqlFirewallRulesClient mysql.FirewallRulesClient - mysqlServersClient mysql.ServersClient - postgresqlConfigurationsClient postgresql.ConfigurationsClient - postgresqlDatabasesClient postgresql.DatabasesClient - postgresqlFirewallRulesClient postgresql.FirewallRulesClient - postgresqlServersClient postgresql.ServersClient - sqlDatabasesClient sql.DatabasesClient - sqlElasticPoolsClient sql.ElasticPoolsClient - sqlFirewallRulesClient sql.FirewallRulesClient - sqlServersClient sql.ServersClient - iothubResourceClient iothub.ResourceClient -} - -func withRequestLogging() autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - // dump request to wire format - if dump, err := httputil.DumpRequestOut(r, true); err == nil { - log.Printf("[DEBUG] AzureRM Request: \n%s\n", dump) - } else { - // fallback to basic message - log.Printf("[DEBUG] AzureRM Request: %s to %s\n", r.Method, r.URL) - } - - resp, err := s.Do(r) - if resp != nil { - // dump response to wire format - if dump, err := httputil.DumpResponse(resp, true); err == nil { - log.Printf("[DEBUG] AzureRM Response for %s: \n%s\n", r.URL, dump) - } else { - // fallback to basic message - log.Printf("[DEBUG] AzureRM Response: %s for %s\n", resp.Status, r.URL) - } - } else { - log.Printf("[DEBUG] Request to %s completed with no response", r.URL) - } - return resp, err - }) - } -} - -func setUserAgent(client *autorest.Client) { - version := terraform.VersionString() - client.UserAgent = fmt.Sprintf("HashiCorp-Terraform-v%s", version) -} - -func (c *Config) getAuthorizationToken(oauthConfig *adal.OAuthConfig, endpoint string) (*autorest.BearerAuthorizer, error) { - useServicePrincipal := c.ClientSecret != "" - - if useServicePrincipal { - spt, err := adal.NewServicePrincipalToken(*oauthConfig, c.ClientID, c.ClientSecret, endpoint) - if err != nil { - return nil, err - } - - auth := autorest.NewBearerAuthorizer(spt) - return auth, nil - } - - if c.IsCloudShell { - // load the refreshed tokens from the Azure CLI - err := c.LoadTokensFromAzureCLI() - if err != nil { - return nil, fmt.Errorf("Error loading the refreshed CloudShell tokens: %+v", err) - } - } - - spt, err := adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, c.ClientID, endpoint, *c.AccessToken) - if err != nil { - return nil, err - } - - auth := autorest.NewBearerAuthorizer(spt) - return auth, nil -} - -// getArmClient is a helper method which returns a fully instantiated -// *ArmClient based on the Config's current settings. -func (c *Config) getArmClient() (*ArmClient, error) { - // detect cloud from environment - env, envErr := azure.EnvironmentFromName(c.Environment) - if envErr != nil { - // try again with wrapped value to support readable values like german instead of AZUREGERMANCLOUD - wrapped := fmt.Sprintf("AZURE%sCLOUD", c.Environment) - var innerErr error - if env, innerErr = azure.EnvironmentFromName(wrapped); innerErr != nil { - return nil, envErr - } - } - - // client declarations: - client := ArmClient{ - clientId: c.ClientID, - tenantId: c.TenantID, - subscriptionId: c.SubscriptionID, - environment: env, - usingServicePrincipal: c.ClientSecret != "", - } - - oauthConfig, err := adal.NewOAuthConfig(env.ActiveDirectoryEndpoint, c.TenantID) - if err != nil { - return nil, err - } - - // OAuthConfigForTenant returns a pointer, which can be nil. - if oauthConfig == nil { - return nil, fmt.Errorf("Unable to configure OAuthConfig for tenant %s", c.TenantID) - } - - sender := autorest.CreateSender(withRequestLogging()) - - // Resource Manager endpoints - endpoint := env.ResourceManagerEndpoint - auth, err := c.getAuthorizationToken(oauthConfig, endpoint) - if err != nil { - return nil, err - } - - // Graph Endpoints - graphEndpoint := env.GraphEndpoint - graphAuth, err := c.getAuthorizationToken(oauthConfig, graphEndpoint) - if err != nil { - return nil, err - } - - // Key Vault Endpoints - keyVaultAuth := autorest.NewBearerAuthorizerCallback(sender, func(tenantID, resource string) (*autorest.BearerAuthorizer, error) { - keyVaultSpt, err := c.getAuthorizationToken(oauthConfig, resource) - if err != nil { - return nil, err - } - - return keyVaultSpt, nil - }) - - // NOTE: these declarations should be left separate for clarity should the - // clients be wished to be configured with custom Responders/PollingModes etc... - asc := compute.NewAvailabilitySetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&asc.Client) - asc.Authorizer = auth - asc.Sender = sender - client.availSetClient = asc - - uoc := compute.NewUsageClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&uoc.Client) - uoc.Authorizer = auth - uoc.Sender = sender - client.usageOpsClient = uoc - - vmeic := compute.NewVirtualMachineExtensionImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmeic.Client) - vmeic.Authorizer = auth - vmeic.Sender = sender - client.vmExtensionImageClient = vmeic - - vmec := compute.NewVirtualMachineExtensionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmec.Client) - vmec.Authorizer = auth - vmec.Sender = sender - client.vmExtensionClient = vmec - - vmic := compute.NewVirtualMachineImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmic.Client) - vmic.Authorizer = auth - vmic.Sender = sender - client.vmImageClient = vmic - - vmssc := compute.NewVirtualMachineScaleSetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmssc.Client) - vmssc.Authorizer = auth - vmssc.Sender = sender - client.vmScaleSetClient = vmssc - - vmc := compute.NewVirtualMachinesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmc.Client) - vmc.Authorizer = auth - vmc.Sender = sender - client.vmClient = vmc - - agc := network.NewApplicationGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&agc.Client) - agc.Authorizer = auth - agc.Sender = sender - client.appGatewayClient = agc - - crc := containerregistry.NewRegistriesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&crc.Client) - crc.Authorizer = auth - crc.Sender = sender - client.containerRegistryClient = crc - - csc := containerservice.NewContainerServicesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&csc.Client) - csc.Authorizer = auth - csc.Sender = sender - client.containerServicesClient = csc - - cgc := containerinstance.NewContainerGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cgc.Client) - cgc.Authorizer = auth - cgc.Sender = autorest.CreateSender(withRequestLogging()) - client.containerGroupsClient = cgc - - cdb := cosmosdb.NewDatabaseAccountsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cdb.Client) - cdb.Authorizer = auth - cdb.Sender = sender - client.cosmosDBClient = cdb - - img := compute.NewImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&img.Client) - img.Authorizer = auth - img.Sender = sender - client.imageClient = img - - egtc := eventgrid.NewTopicsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&egtc.Client) - egtc.Authorizer = auth - egtc.Sender = sender - client.eventGridTopicsClient = egtc - - ehc := eventhub.NewEventHubsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ehc.Client) - ehc.Authorizer = auth - ehc.Sender = sender - client.eventHubClient = ehc - - chcgc := eventhub.NewConsumerGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&chcgc.Client) - chcgc.Authorizer = auth - chcgc.Sender = sender - client.eventHubConsumerGroupClient = chcgc - - ehnc := eventhub.NewNamespacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ehnc.Client) - ehnc.Authorizer = auth - ehnc.Sender = sender - client.eventHubNamespacesClient = ehnc - - ifc := network.NewInterfacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ifc.Client) - ifc.Authorizer = auth - ifc.Sender = sender - client.ifaceClient = ifc - - erc := network.NewExpressRouteCircuitsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&erc.Client) - erc.Authorizer = auth - erc.Sender = sender - client.expressRouteCircuitClient = erc - - lbc := network.NewLoadBalancersClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&lbc.Client) - lbc.Authorizer = auth - lbc.Sender = sender - client.loadBalancerClient = lbc - - lgc := network.NewLocalNetworkGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&lgc.Client) - lgc.Authorizer = auth - lgc.Sender = sender - client.localNetConnClient = lgc - - opwc := operationalinsights.NewWorkspacesClient(c.SubscriptionID) - setUserAgent(&opwc.Client) - opwc.Authorizer = auth - opwc.Sender = autorest.CreateSender(withRequestLogging()) - client.workspacesClient = opwc - - pipc := network.NewPublicIPAddressesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&pipc.Client) - pipc.Authorizer = auth - pipc.Sender = sender - client.publicIPClient = pipc - - sgc := network.NewSecurityGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sgc.Client) - sgc.Authorizer = auth - sgc.Sender = sender - client.secGroupClient = sgc - - src := network.NewSecurityRulesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&src.Client) - src.Authorizer = auth - src.Sender = sender - client.secRuleClient = src - - snc := network.NewSubnetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&snc.Client) - snc.Authorizer = auth - snc.Sender = sender - client.subnetClient = snc - - vgcc := network.NewVirtualNetworkGatewayConnectionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vgcc.Client) - vgcc.Authorizer = auth - vgcc.Sender = sender - client.vnetGatewayConnectionsClient = vgcc - - vgc := network.NewVirtualNetworkGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vgc.Client) - vgc.Authorizer = auth - vgc.Sender = sender - client.vnetGatewayClient = vgc - - vnc := network.NewVirtualNetworksClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vnc.Client) - vnc.Authorizer = auth - vnc.Sender = sender - client.vnetClient = vnc - - vnpc := network.NewVirtualNetworkPeeringsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vnpc.Client) - vnpc.Authorizer = auth - vnpc.Sender = sender - client.vnetPeeringsClient = vnpc - - rtc := network.NewRouteTablesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rtc.Client) - rtc.Authorizer = auth - rtc.Sender = sender - client.routeTablesClient = rtc - - rc := network.NewRoutesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rc.Client) - rc.Authorizer = auth - rc.Sender = sender - client.routesClient = rc - - dn := dns.NewRecordSetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&dn.Client) - dn.Authorizer = auth - dn.Sender = sender - client.dnsClient = dn - - zo := dns.NewZonesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&zo.Client) - zo.Authorizer = auth - zo.Sender = sender - client.zonesClient = zo - - rgc := resources.NewGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rgc.Client) - rgc.Authorizer = auth - rgc.Sender = sender - client.resourceGroupClient = rgc - - pc := resources.NewProvidersClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&pc.Client) - pc.Authorizer = auth - pc.Sender = sender - client.providers = pc - - tc := resources.NewTagsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tc.Client) - tc.Authorizer = auth - tc.Sender = sender - client.tagsClient = tc - - rf := resources.NewGroupClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rf.Client) - rf.Authorizer = auth - rf.Sender = sender - client.resourceFindClient = rf - - subgc := subscriptions.NewGroupClientWithBaseURI(endpoint) - setUserAgent(&subgc.Client) - subgc.Authorizer = auth - subgc.Sender = sender - client.subscriptionsGroupClient = subgc - - jc := scheduler.NewJobsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&jc.Client) - jc.Authorizer = auth - jc.Sender = sender - client.jobsClient = jc - - jcc := scheduler.NewJobCollectionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&jcc.Client) - jcc.Authorizer = auth - jcc.Sender = sender - client.jobsCollectionsClient = jcc - - ssc := storage.NewAccountsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ssc.Client) - ssc.Authorizer = auth - ssc.Sender = sender - client.storageServiceClient = ssc - - suc := storage.NewUsageClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&suc.Client) - suc.Authorizer = auth - suc.Sender = sender - client.storageUsageClient = suc - - cpc := cdn.NewProfilesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cpc.Client) - cpc.Authorizer = auth - cpc.Sender = sender - client.cdnProfilesClient = cpc - - cec := cdn.NewEndpointsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cec.Client) - cec.Authorizer = auth - cec.Sender = sender - client.cdnEndpointsClient = cec - - dc := resources.NewDeploymentsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&dc.Client) - dc.Authorizer = auth - dc.Sender = sender - client.deploymentsClient = dc - - tmpc := trafficmanager.NewProfilesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tmpc.Client) - tmpc.Authorizer = auth - tmpc.Sender = sender - client.trafficManagerProfilesClient = tmpc - - tmec := trafficmanager.NewEndpointsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tmec.Client) - tmec.Authorizer = auth - tmec.Sender = sender - client.trafficManagerEndpointsClient = tmec - - rdc := redis.NewGroupClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rdc.Client) - rdc.Authorizer = auth - rdc.Sender = sender - client.redisClient = rdc - - sesc := search.NewServicesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sesc.Client) - sesc.Authorizer = auth - sesc.Sender = sender - client.searchServicesClient = sesc - - sbnc := servicebus.NewNamespacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbnc.Client) - sbnc.Authorizer = auth - sbnc.Sender = sender - client.serviceBusNamespacesClient = sbnc - - sbqc := servicebus.NewQueuesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbqc.Client) - sbqc.Authorizer = auth - sbqc.Sender = sender - client.serviceBusQueuesClient = sbqc - - sbtc := servicebus.NewTopicsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbtc.Client) - sbtc.Authorizer = auth - sbtc.Sender = sender - client.serviceBusTopicsClient = sbtc - - sbsc := servicebus.NewSubscriptionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbsc.Client) - sbsc.Authorizer = auth - sbsc.Sender = sender - client.serviceBusSubscriptionsClient = sbsc - - aspc := web.NewAppServicePlansClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aspc.Client) - aspc.Authorizer = auth - aspc.Sender = sender - client.appServicePlansClient = aspc - - ac := web.NewAppsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ac.Client) - ac.Authorizer = auth - ac.Sender = autorest.CreateSender(withRequestLogging()) - client.appServicesClient = ac - - ai := appinsights.NewComponentsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ai.Client) - ai.Authorizer = auth - ai.Sender = sender - client.appInsightsClient = ai - - aadb := automation.NewAccountClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aadb.Client) - aadb.Authorizer = auth - aadb.Sender = sender - client.automationAccountClient = aadb - - arc := automation.NewRunbookClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&arc.Client) - arc.Authorizer = auth - arc.Sender = sender - client.automationRunbookClient = arc - - acc := automation.NewCredentialClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&acc.Client) - acc.Authorizer = auth - acc.Sender = sender - client.automationCredentialClient = acc - - aschc := automation.NewScheduleClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aschc.Client) - aschc.Authorizer = auth - aschc.Sender = sender - client.automationScheduleClient = aschc - -<<<<<<< HEAD - ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ihrc.Client) - ihrc.Authorizer = auth - ihrc.Sender = autorest.CreateSender(withRequestLogging()) - client.iothubResourceClient = ihrc - -======= -<<<<<<< HEAD - client.registerAuthentication(endpoint, graphEndpoint, c.SubscriptionID, c.TenantID, auth, graphAuth, sender) -||||||| merged common ancestors ->>>>>>> 60cd688486d722c6c36a4ee7155f24252405c0d8 - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - -======= - ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ihrc.Client) - ihrc.Authorizer = auth - ihrc.Sender = autorest.CreateSender(withRequestLogging()) - client.iothubResourceClient = ihrc - - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - ->>>>>>> added the config and cleaned up the schema iothub resource schema - client.registerDatabases(endpoint, c.SubscriptionID, auth, sender) - client.registerDisks(endpoint, c.SubscriptionID, auth, sender) - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - - return &client, nil -} - -func (c *ArmClient) registerAuthentication(endpoint, graphEndpoint, subscriptionId, tenantId string, auth, graphAuth autorest.Authorizer, sender autorest.Sender) { - spc := graphrbac.NewServicePrincipalsClientWithBaseURI(graphEndpoint, tenantId) - setUserAgent(&spc.Client) - spc.Authorizer = graphAuth - spc.Sender = sender - c.servicePrincipalsClient = spc - - rac := authorization.NewRoleAssignmentsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&rac.Client) - rac.Authorizer = auth - rac.Sender = sender - c.roleAssignmentsClient = rac - - rdc := authorization.NewRoleDefinitionsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&rdc.Client) - rdc.Authorizer = auth - rdc.Sender = sender - c.roleDefinitionsClient = rdc -} - -func (c *ArmClient) registerDatabases(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { - // MySQL - mysqlConfigClient := mysql.NewConfigurationsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlConfigClient.Client) - mysqlConfigClient.Authorizer = auth - mysqlConfigClient.Sender = sender - c.mysqlConfigurationsClient = mysqlConfigClient - - mysqlDBClient := mysql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlDBClient.Client) - mysqlDBClient.Authorizer = auth - mysqlDBClient.Sender = sender - c.mysqlDatabasesClient = mysqlDBClient - - mysqlFWClient := mysql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlFWClient.Client) - mysqlFWClient.Authorizer = auth - mysqlFWClient.Sender = sender - c.mysqlFirewallRulesClient = mysqlFWClient - - mysqlServersClient := mysql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlServersClient.Client) - mysqlServersClient.Authorizer = auth - mysqlServersClient.Sender = sender - c.mysqlServersClient = mysqlServersClient - - // PostgreSQL - postgresqlConfigClient := postgresql.NewConfigurationsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlConfigClient.Client) - postgresqlConfigClient.Authorizer = auth - postgresqlConfigClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlConfigurationsClient = postgresqlConfigClient - - postgresqlDBClient := postgresql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlDBClient.Client) - postgresqlDBClient.Authorizer = auth - postgresqlDBClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlDatabasesClient = postgresqlDBClient - - postgresqlFWClient := postgresql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlFWClient.Client) - postgresqlFWClient.Authorizer = auth - postgresqlFWClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlFirewallRulesClient = postgresqlFWClient - - postgresqlSrvClient := postgresql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlSrvClient.Client) - postgresqlSrvClient.Authorizer = auth - postgresqlSrvClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlServersClient = postgresqlSrvClient - - // SQL Azure - sqlDBClient := sql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlDBClient.Client) - sqlDBClient.Authorizer = auth - sqlDBClient.Sender = sender - c.sqlDatabasesClient = sqlDBClient - - sqlFWClient := sql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlFWClient.Client) - sqlFWClient.Authorizer = auth - sqlFWClient.Sender = sender - c.sqlFirewallRulesClient = sqlFWClient - - sqlEPClient := sql.NewElasticPoolsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlEPClient.Client) - sqlEPClient.Authorizer = auth - sqlEPClient.Sender = sender - c.sqlElasticPoolsClient = sqlEPClient - - sqlSrvClient := sql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlSrvClient.Client) - sqlSrvClient.Authorizer = auth - sqlSrvClient.Sender = sender - c.sqlServersClient = sqlSrvClient -} - -func (c *ArmClient) registerDisks(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { - diskClient := disk.NewDisksClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&diskClient.Client) - diskClient.Authorizer = auth - diskClient.Sender = sender - c.diskClient = diskClient - - snapshotsClient := disk.NewSnapshotsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&snapshotsClient.Client) - snapshotsClient.Authorizer = auth - snapshotsClient.Sender = sender - c.snapshotsClient = snapshotsClient -} - -func (c *ArmClient) registerKeyVaultClients(endpoint, subscriptionId string, auth autorest.Authorizer, keyVaultAuth autorest.Authorizer, sender autorest.Sender) { - keyVaultClient := keyvault.NewVaultsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&keyVaultClient.Client) - keyVaultClient.Authorizer = auth - keyVaultClient.Sender = sender - c.keyVaultClient = keyVaultClient - - keyVaultManagementClient := keyVault.New() - setUserAgent(&keyVaultManagementClient.Client) - keyVaultManagementClient.Authorizer = keyVaultAuth - keyVaultManagementClient.Sender = sender - c.keyVaultManagementClient = keyVaultManagementClient -} - -func (armClient *ArmClient) getKeyForStorageAccount(resourceGroupName, storageAccountName string) (string, bool, error) { - accountKeys, err := armClient.storageServiceClient.ListKeys(resourceGroupName, storageAccountName) - if accountKeys.StatusCode == http.StatusNotFound { - return "", false, nil - } - if err != nil { - // We assume this is a transient error rather than a 404 (which is caught above), so assume the - // account still exists. - return "", true, fmt.Errorf("Error retrieving keys for storage account %q: %s", storageAccountName, err) - } - - if accountKeys.Keys == nil { - return "", false, fmt.Errorf("Nil key returned for storage account %q", storageAccountName) - } - - keys := *accountKeys.Keys - return *keys[0].Value, true, nil -} - -func (armClient *ArmClient) getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.BlobStorageClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - blobClient := storageClient.GetBlobService() - return &blobClient, true, nil -} - -func (armClient *ArmClient) getFileServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.FileServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - fileClient := storageClient.GetFileService() - return &fileClient, true, nil -} - -func (armClient *ArmClient) getTableServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.TableServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - tableClient := storageClient.GetTableService() - return &tableClient, true, nil -} - -func (armClient *ArmClient) getQueueServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.QueueServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - queueClient := storageClient.GetQueueService() - return &queueClient, true, nil -} diff --git a/azurerm/config_REMOTE_7053.go b/azurerm/config_REMOTE_7053.go deleted file mode 100644 index fd44660c2988..000000000000 --- a/azurerm/config_REMOTE_7053.go +++ /dev/null @@ -1,887 +0,0 @@ -package azurerm - -import ( - "context" - "fmt" - "log" - "net/http" - "net/http/httputil" - - "github.com/Azure/azure-sdk-for-go/arm/iothub" - - "github.com/Azure/azure-sdk-for-go/arm/appinsights" - "github.com/Azure/azure-sdk-for-go/arm/authorization" - "github.com/Azure/azure-sdk-for-go/arm/automation" - "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/containerinstance" - "github.com/Azure/azure-sdk-for-go/arm/containerregistry" - "github.com/Azure/azure-sdk-for-go/arm/containerservice" - "github.com/Azure/azure-sdk-for-go/arm/cosmos-db" - "github.com/Azure/azure-sdk-for-go/arm/disk" - "github.com/Azure/azure-sdk-for-go/arm/dns" - "github.com/Azure/azure-sdk-for-go/arm/eventgrid" - "github.com/Azure/azure-sdk-for-go/arm/eventhub" - "github.com/Azure/azure-sdk-for-go/arm/graphrbac" - "github.com/Azure/azure-sdk-for-go/arm/keyvault" - "github.com/Azure/azure-sdk-for-go/arm/mysql" - "github.com/Azure/azure-sdk-for-go/arm/network" - "github.com/Azure/azure-sdk-for-go/arm/operationalinsights" - "github.com/Azure/azure-sdk-for-go/arm/postgresql" - "github.com/Azure/azure-sdk-for-go/arm/redis" - "github.com/Azure/azure-sdk-for-go/arm/resources/resources" - "github.com/Azure/azure-sdk-for-go/arm/resources/subscriptions" - "github.com/Azure/azure-sdk-for-go/arm/scheduler" - "github.com/Azure/azure-sdk-for-go/arm/search" - "github.com/Azure/azure-sdk-for-go/arm/servicebus" - "github.com/Azure/azure-sdk-for-go/arm/sql" - "github.com/Azure/azure-sdk-for-go/arm/storage" - "github.com/Azure/azure-sdk-for-go/arm/trafficmanager" - "github.com/Azure/azure-sdk-for-go/arm/web" - keyVault "github.com/Azure/azure-sdk-for-go/dataplane/keyvault" - mainStorage "github.com/Azure/azure-sdk-for-go/storage" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/hashicorp/terraform/terraform" -) - -// ArmClient contains the handles to all the specific Azure Resource Manager -// resource classes' respective clients. -type ArmClient struct { - clientId string - tenantId string - subscriptionId string - usingServicePrincipal bool - environment azure.Environment - - StopContext context.Context - - availSetClient compute.AvailabilitySetsClient - usageOpsClient compute.UsageClient - vmExtensionImageClient compute.VirtualMachineExtensionImagesClient - vmExtensionClient compute.VirtualMachineExtensionsClient - vmScaleSetClient compute.VirtualMachineScaleSetsClient - vmImageClient compute.VirtualMachineImagesClient - vmClient compute.VirtualMachinesClient - imageClient compute.ImagesClient - - diskClient disk.DisksClient - snapshotsClient disk.SnapshotsClient - cosmosDBClient cosmosdb.DatabaseAccountsClient - automationAccountClient automation.AccountClient - automationRunbookClient automation.RunbookClient - automationCredentialClient automation.CredentialClient - automationScheduleClient automation.ScheduleClient - - appGatewayClient network.ApplicationGatewaysClient - ifaceClient network.InterfacesClient - expressRouteCircuitClient network.ExpressRouteCircuitsClient - loadBalancerClient network.LoadBalancersClient - localNetConnClient network.LocalNetworkGatewaysClient - publicIPClient network.PublicIPAddressesClient - secGroupClient network.SecurityGroupsClient - secRuleClient network.SecurityRulesClient - subnetClient network.SubnetsClient - netUsageClient network.UsagesClient - vnetGatewayConnectionsClient network.VirtualNetworkGatewayConnectionsClient - vnetGatewayClient network.VirtualNetworkGatewaysClient - vnetClient network.VirtualNetworksClient - vnetPeeringsClient network.VirtualNetworkPeeringsClient - routeTablesClient network.RouteTablesClient - routesClient network.RoutesClient - dnsClient dns.RecordSetsClient - zonesClient dns.ZonesClient - - cdnProfilesClient cdn.ProfilesClient - cdnEndpointsClient cdn.EndpointsClient - - containerRegistryClient containerregistry.RegistriesClient - containerServicesClient containerservice.ContainerServicesClient - containerGroupsClient containerinstance.ContainerGroupsClient - - eventGridTopicsClient eventgrid.TopicsClient - eventHubClient eventhub.EventHubsClient - eventHubConsumerGroupClient eventhub.ConsumerGroupsClient - eventHubNamespacesClient eventhub.NamespacesClient - - workspacesClient operationalinsights.WorkspacesClient - - providers resources.ProvidersClient - resourceGroupClient resources.GroupsClient - tagsClient resources.TagsClient - resourceFindClient resources.GroupClient - - subscriptionsGroupClient subscriptions.GroupClient - - jobsClient scheduler.JobsClient - jobsCollectionsClient scheduler.JobCollectionsClient - - storageServiceClient storage.AccountsClient - storageUsageClient storage.UsageClient - - deploymentsClient resources.DeploymentsClient - - redisClient redis.GroupClient - - trafficManagerProfilesClient trafficmanager.ProfilesClient - trafficManagerEndpointsClient trafficmanager.EndpointsClient - - searchServicesClient search.ServicesClient - serviceBusNamespacesClient servicebus.NamespacesClient - serviceBusQueuesClient servicebus.QueuesClient - serviceBusTopicsClient servicebus.TopicsClient - serviceBusSubscriptionsClient servicebus.SubscriptionsClient - - keyVaultClient keyvault.VaultsClient - keyVaultManagementClient keyVault.ManagementClient - - appServicePlansClient web.AppServicePlansClient - appServicesClient web.AppsClient - - appInsightsClient appinsights.ComponentsClient - - // Authentication - roleAssignmentsClient authorization.RoleAssignmentsClient - roleDefinitionsClient authorization.RoleDefinitionsClient - servicePrincipalsClient graphrbac.ServicePrincipalsClient - - // Databases - mysqlConfigurationsClient mysql.ConfigurationsClient - mysqlDatabasesClient mysql.DatabasesClient - mysqlFirewallRulesClient mysql.FirewallRulesClient - mysqlServersClient mysql.ServersClient - postgresqlConfigurationsClient postgresql.ConfigurationsClient - postgresqlDatabasesClient postgresql.DatabasesClient - postgresqlFirewallRulesClient postgresql.FirewallRulesClient - postgresqlServersClient postgresql.ServersClient - sqlDatabasesClient sql.DatabasesClient - sqlElasticPoolsClient sql.ElasticPoolsClient - sqlFirewallRulesClient sql.FirewallRulesClient - sqlServersClient sql.ServersClient - iothubResourceClient iothub.ResourceClient -} - -func withRequestLogging() autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - // dump request to wire format - if dump, err := httputil.DumpRequestOut(r, true); err == nil { - log.Printf("[DEBUG] AzureRM Request: \n%s\n", dump) - } else { - // fallback to basic message - log.Printf("[DEBUG] AzureRM Request: %s to %s\n", r.Method, r.URL) - } - - resp, err := s.Do(r) - if resp != nil { - // dump response to wire format - if dump, err := httputil.DumpResponse(resp, true); err == nil { - log.Printf("[DEBUG] AzureRM Response for %s: \n%s\n", r.URL, dump) - } else { - // fallback to basic message - log.Printf("[DEBUG] AzureRM Response: %s for %s\n", resp.Status, r.URL) - } - } else { - log.Printf("[DEBUG] Request to %s completed with no response", r.URL) - } - return resp, err - }) - } -} - -func setUserAgent(client *autorest.Client) { - version := terraform.VersionString() - client.UserAgent = fmt.Sprintf("HashiCorp-Terraform-v%s", version) -} - -func (c *Config) getAuthorizationToken(oauthConfig *adal.OAuthConfig, endpoint string) (*autorest.BearerAuthorizer, error) { - useServicePrincipal := c.ClientSecret != "" - - if useServicePrincipal { - spt, err := adal.NewServicePrincipalToken(*oauthConfig, c.ClientID, c.ClientSecret, endpoint) - if err != nil { - return nil, err - } - - auth := autorest.NewBearerAuthorizer(spt) - return auth, nil - } - - if c.IsCloudShell { - // load the refreshed tokens from the Azure CLI - err := c.LoadTokensFromAzureCLI() - if err != nil { - return nil, fmt.Errorf("Error loading the refreshed CloudShell tokens: %+v", err) - } - } - - spt, err := adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, c.ClientID, endpoint, *c.AccessToken) - if err != nil { - return nil, err - } - - auth := autorest.NewBearerAuthorizer(spt) - return auth, nil -} - -// getArmClient is a helper method which returns a fully instantiated -// *ArmClient based on the Config's current settings. -func (c *Config) getArmClient() (*ArmClient, error) { - // detect cloud from environment - env, envErr := azure.EnvironmentFromName(c.Environment) - if envErr != nil { - // try again with wrapped value to support readable values like german instead of AZUREGERMANCLOUD - wrapped := fmt.Sprintf("AZURE%sCLOUD", c.Environment) - var innerErr error - if env, innerErr = azure.EnvironmentFromName(wrapped); innerErr != nil { - return nil, envErr - } - } - - // client declarations: - client := ArmClient{ - clientId: c.ClientID, - tenantId: c.TenantID, - subscriptionId: c.SubscriptionID, - environment: env, - usingServicePrincipal: c.ClientSecret != "", - } - - oauthConfig, err := adal.NewOAuthConfig(env.ActiveDirectoryEndpoint, c.TenantID) - if err != nil { - return nil, err - } - - // OAuthConfigForTenant returns a pointer, which can be nil. - if oauthConfig == nil { - return nil, fmt.Errorf("Unable to configure OAuthConfig for tenant %s", c.TenantID) - } - - sender := autorest.CreateSender(withRequestLogging()) - - // Resource Manager endpoints - endpoint := env.ResourceManagerEndpoint - auth, err := c.getAuthorizationToken(oauthConfig, endpoint) - if err != nil { - return nil, err - } - - // Graph Endpoints - graphEndpoint := env.GraphEndpoint - graphAuth, err := c.getAuthorizationToken(oauthConfig, graphEndpoint) - if err != nil { - return nil, err - } - - // Key Vault Endpoints - keyVaultAuth := autorest.NewBearerAuthorizerCallback(sender, func(tenantID, resource string) (*autorest.BearerAuthorizer, error) { - keyVaultSpt, err := c.getAuthorizationToken(oauthConfig, resource) - if err != nil { - return nil, err - } - - return keyVaultSpt, nil - }) - - // NOTE: these declarations should be left separate for clarity should the - // clients be wished to be configured with custom Responders/PollingModes etc... - asc := compute.NewAvailabilitySetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&asc.Client) - asc.Authorizer = auth - asc.Sender = sender - client.availSetClient = asc - - uoc := compute.NewUsageClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&uoc.Client) - uoc.Authorizer = auth - uoc.Sender = sender - client.usageOpsClient = uoc - - vmeic := compute.NewVirtualMachineExtensionImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmeic.Client) - vmeic.Authorizer = auth - vmeic.Sender = sender - client.vmExtensionImageClient = vmeic - - vmec := compute.NewVirtualMachineExtensionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmec.Client) - vmec.Authorizer = auth - vmec.Sender = sender - client.vmExtensionClient = vmec - - vmic := compute.NewVirtualMachineImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmic.Client) - vmic.Authorizer = auth - vmic.Sender = sender - client.vmImageClient = vmic - - vmssc := compute.NewVirtualMachineScaleSetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmssc.Client) - vmssc.Authorizer = auth - vmssc.Sender = sender - client.vmScaleSetClient = vmssc - - vmc := compute.NewVirtualMachinesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vmc.Client) - vmc.Authorizer = auth - vmc.Sender = sender - client.vmClient = vmc - - agc := network.NewApplicationGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&agc.Client) - agc.Authorizer = auth - agc.Sender = sender - client.appGatewayClient = agc - - crc := containerregistry.NewRegistriesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&crc.Client) - crc.Authorizer = auth - crc.Sender = sender - client.containerRegistryClient = crc - - csc := containerservice.NewContainerServicesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&csc.Client) - csc.Authorizer = auth - csc.Sender = sender - client.containerServicesClient = csc - - cgc := containerinstance.NewContainerGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cgc.Client) - cgc.Authorizer = auth - cgc.Sender = autorest.CreateSender(withRequestLogging()) - client.containerGroupsClient = cgc - - cdb := cosmosdb.NewDatabaseAccountsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cdb.Client) - cdb.Authorizer = auth - cdb.Sender = sender - client.cosmosDBClient = cdb - - img := compute.NewImagesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&img.Client) - img.Authorizer = auth - img.Sender = sender - client.imageClient = img - - egtc := eventgrid.NewTopicsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&egtc.Client) - egtc.Authorizer = auth - egtc.Sender = sender - client.eventGridTopicsClient = egtc - - ehc := eventhub.NewEventHubsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ehc.Client) - ehc.Authorizer = auth - ehc.Sender = sender - client.eventHubClient = ehc - - chcgc := eventhub.NewConsumerGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&chcgc.Client) - chcgc.Authorizer = auth - chcgc.Sender = sender - client.eventHubConsumerGroupClient = chcgc - - ehnc := eventhub.NewNamespacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ehnc.Client) - ehnc.Authorizer = auth - ehnc.Sender = sender - client.eventHubNamespacesClient = ehnc - - ifc := network.NewInterfacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ifc.Client) - ifc.Authorizer = auth - ifc.Sender = sender - client.ifaceClient = ifc - - erc := network.NewExpressRouteCircuitsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&erc.Client) - erc.Authorizer = auth - erc.Sender = sender - client.expressRouteCircuitClient = erc - - lbc := network.NewLoadBalancersClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&lbc.Client) - lbc.Authorizer = auth - lbc.Sender = sender - client.loadBalancerClient = lbc - - lgc := network.NewLocalNetworkGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&lgc.Client) - lgc.Authorizer = auth - lgc.Sender = sender - client.localNetConnClient = lgc - - opwc := operationalinsights.NewWorkspacesClient(c.SubscriptionID) - setUserAgent(&opwc.Client) - opwc.Authorizer = auth - opwc.Sender = autorest.CreateSender(withRequestLogging()) - client.workspacesClient = opwc - - pipc := network.NewPublicIPAddressesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&pipc.Client) - pipc.Authorizer = auth - pipc.Sender = sender - client.publicIPClient = pipc - - sgc := network.NewSecurityGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sgc.Client) - sgc.Authorizer = auth - sgc.Sender = sender - client.secGroupClient = sgc - - src := network.NewSecurityRulesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&src.Client) - src.Authorizer = auth - src.Sender = sender - client.secRuleClient = src - - snc := network.NewSubnetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&snc.Client) - snc.Authorizer = auth - snc.Sender = sender - client.subnetClient = snc - - vgcc := network.NewVirtualNetworkGatewayConnectionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vgcc.Client) - vgcc.Authorizer = auth - vgcc.Sender = sender - client.vnetGatewayConnectionsClient = vgcc - - vgc := network.NewVirtualNetworkGatewaysClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vgc.Client) - vgc.Authorizer = auth - vgc.Sender = sender - client.vnetGatewayClient = vgc - - vnc := network.NewVirtualNetworksClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vnc.Client) - vnc.Authorizer = auth - vnc.Sender = sender - client.vnetClient = vnc - - vnpc := network.NewVirtualNetworkPeeringsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&vnpc.Client) - vnpc.Authorizer = auth - vnpc.Sender = sender - client.vnetPeeringsClient = vnpc - - rtc := network.NewRouteTablesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rtc.Client) - rtc.Authorizer = auth - rtc.Sender = sender - client.routeTablesClient = rtc - - rc := network.NewRoutesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rc.Client) - rc.Authorizer = auth - rc.Sender = sender - client.routesClient = rc - - dn := dns.NewRecordSetsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&dn.Client) - dn.Authorizer = auth - dn.Sender = sender - client.dnsClient = dn - - zo := dns.NewZonesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&zo.Client) - zo.Authorizer = auth - zo.Sender = sender - client.zonesClient = zo - - rgc := resources.NewGroupsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rgc.Client) - rgc.Authorizer = auth - rgc.Sender = sender - client.resourceGroupClient = rgc - - pc := resources.NewProvidersClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&pc.Client) - pc.Authorizer = auth - pc.Sender = sender - client.providers = pc - - tc := resources.NewTagsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tc.Client) - tc.Authorizer = auth - tc.Sender = sender - client.tagsClient = tc - - rf := resources.NewGroupClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rf.Client) - rf.Authorizer = auth - rf.Sender = sender - client.resourceFindClient = rf - - subgc := subscriptions.NewGroupClientWithBaseURI(endpoint) - setUserAgent(&subgc.Client) - subgc.Authorizer = auth - subgc.Sender = sender - client.subscriptionsGroupClient = subgc - - jc := scheduler.NewJobsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&jc.Client) - jc.Authorizer = auth - jc.Sender = sender - client.jobsClient = jc - - jcc := scheduler.NewJobCollectionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&jcc.Client) - jcc.Authorizer = auth - jcc.Sender = sender - client.jobsCollectionsClient = jcc - - ssc := storage.NewAccountsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ssc.Client) - ssc.Authorizer = auth - ssc.Sender = sender - client.storageServiceClient = ssc - - suc := storage.NewUsageClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&suc.Client) - suc.Authorizer = auth - suc.Sender = sender - client.storageUsageClient = suc - - cpc := cdn.NewProfilesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cpc.Client) - cpc.Authorizer = auth - cpc.Sender = sender - client.cdnProfilesClient = cpc - - cec := cdn.NewEndpointsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&cec.Client) - cec.Authorizer = auth - cec.Sender = sender - client.cdnEndpointsClient = cec - - dc := resources.NewDeploymentsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&dc.Client) - dc.Authorizer = auth - dc.Sender = sender - client.deploymentsClient = dc - - tmpc := trafficmanager.NewProfilesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tmpc.Client) - tmpc.Authorizer = auth - tmpc.Sender = sender - client.trafficManagerProfilesClient = tmpc - - tmec := trafficmanager.NewEndpointsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&tmec.Client) - tmec.Authorizer = auth - tmec.Sender = sender - client.trafficManagerEndpointsClient = tmec - - rdc := redis.NewGroupClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&rdc.Client) - rdc.Authorizer = auth - rdc.Sender = sender - client.redisClient = rdc - - sesc := search.NewServicesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sesc.Client) - sesc.Authorizer = auth - sesc.Sender = sender - client.searchServicesClient = sesc - - sbnc := servicebus.NewNamespacesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbnc.Client) - sbnc.Authorizer = auth - sbnc.Sender = sender - client.serviceBusNamespacesClient = sbnc - - sbqc := servicebus.NewQueuesClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbqc.Client) - sbqc.Authorizer = auth - sbqc.Sender = sender - client.serviceBusQueuesClient = sbqc - - sbtc := servicebus.NewTopicsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbtc.Client) - sbtc.Authorizer = auth - sbtc.Sender = sender - client.serviceBusTopicsClient = sbtc - - sbsc := servicebus.NewSubscriptionsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&sbsc.Client) - sbsc.Authorizer = auth - sbsc.Sender = sender - client.serviceBusSubscriptionsClient = sbsc - - aspc := web.NewAppServicePlansClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aspc.Client) - aspc.Authorizer = auth - aspc.Sender = sender - client.appServicePlansClient = aspc - - ac := web.NewAppsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ac.Client) - ac.Authorizer = auth - ac.Sender = autorest.CreateSender(withRequestLogging()) - client.appServicesClient = ac - - ai := appinsights.NewComponentsClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ai.Client) - ai.Authorizer = auth - ai.Sender = sender - client.appInsightsClient = ai - - aadb := automation.NewAccountClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aadb.Client) - aadb.Authorizer = auth - aadb.Sender = sender - client.automationAccountClient = aadb - - arc := automation.NewRunbookClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&arc.Client) - arc.Authorizer = auth - arc.Sender = sender - client.automationRunbookClient = arc - - acc := automation.NewCredentialClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&acc.Client) - acc.Authorizer = auth - acc.Sender = sender - client.automationCredentialClient = acc - - aschc := automation.NewScheduleClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&aschc.Client) - aschc.Authorizer = auth - aschc.Sender = sender - client.automationScheduleClient = aschc - - ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ihrc.Client) - ihrc.Authorizer = auth - ihrc.Sender = autorest.CreateSender(withRequestLogging()) - client.iothubResourceClient = ihrc - - client.registerAuthentication(endpoint, graphEndpoint, c.SubscriptionID, c.TenantID, auth, graphAuth, sender) - client.registerDatabases(endpoint, c.SubscriptionID, auth, sender) - client.registerDisks(endpoint, c.SubscriptionID, auth, sender) - client.registerKeyVaultClients(endpoint, c.SubscriptionID, auth, keyVaultAuth, sender) - - return &client, nil -} - -func (c *ArmClient) registerAuthentication(endpoint, graphEndpoint, subscriptionId, tenantId string, auth, graphAuth autorest.Authorizer, sender autorest.Sender) { - spc := graphrbac.NewServicePrincipalsClientWithBaseURI(graphEndpoint, tenantId) - setUserAgent(&spc.Client) - spc.Authorizer = graphAuth - spc.Sender = sender - c.servicePrincipalsClient = spc - - rac := authorization.NewRoleAssignmentsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&rac.Client) - rac.Authorizer = auth - rac.Sender = sender - c.roleAssignmentsClient = rac - - rdc := authorization.NewRoleDefinitionsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&rdc.Client) - rdc.Authorizer = auth - rdc.Sender = sender - c.roleDefinitionsClient = rdc -} - -func (c *ArmClient) registerDatabases(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { - // MySQL - mysqlConfigClient := mysql.NewConfigurationsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlConfigClient.Client) - mysqlConfigClient.Authorizer = auth - mysqlConfigClient.Sender = sender - c.mysqlConfigurationsClient = mysqlConfigClient - - mysqlDBClient := mysql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlDBClient.Client) - mysqlDBClient.Authorizer = auth - mysqlDBClient.Sender = sender - c.mysqlDatabasesClient = mysqlDBClient - - mysqlFWClient := mysql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlFWClient.Client) - mysqlFWClient.Authorizer = auth - mysqlFWClient.Sender = sender - c.mysqlFirewallRulesClient = mysqlFWClient - - mysqlServersClient := mysql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&mysqlServersClient.Client) - mysqlServersClient.Authorizer = auth - mysqlServersClient.Sender = sender - c.mysqlServersClient = mysqlServersClient - - // PostgreSQL - postgresqlConfigClient := postgresql.NewConfigurationsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlConfigClient.Client) - postgresqlConfigClient.Authorizer = auth - postgresqlConfigClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlConfigurationsClient = postgresqlConfigClient - - postgresqlDBClient := postgresql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlDBClient.Client) - postgresqlDBClient.Authorizer = auth - postgresqlDBClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlDatabasesClient = postgresqlDBClient - - postgresqlFWClient := postgresql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlFWClient.Client) - postgresqlFWClient.Authorizer = auth - postgresqlFWClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlFirewallRulesClient = postgresqlFWClient - - postgresqlSrvClient := postgresql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&postgresqlSrvClient.Client) - postgresqlSrvClient.Authorizer = auth - postgresqlSrvClient.Sender = autorest.CreateSender(withRequestLogging()) - c.postgresqlServersClient = postgresqlSrvClient - - // SQL Azure - sqlDBClient := sql.NewDatabasesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlDBClient.Client) - sqlDBClient.Authorizer = auth - sqlDBClient.Sender = sender - c.sqlDatabasesClient = sqlDBClient - - sqlFWClient := sql.NewFirewallRulesClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlFWClient.Client) - sqlFWClient.Authorizer = auth - sqlFWClient.Sender = sender - c.sqlFirewallRulesClient = sqlFWClient - - sqlEPClient := sql.NewElasticPoolsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlEPClient.Client) - sqlEPClient.Authorizer = auth - sqlEPClient.Sender = sender - c.sqlElasticPoolsClient = sqlEPClient - - sqlSrvClient := sql.NewServersClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&sqlSrvClient.Client) - sqlSrvClient.Authorizer = auth - sqlSrvClient.Sender = sender - c.sqlServersClient = sqlSrvClient -} - -func (c *ArmClient) registerDisks(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { - diskClient := disk.NewDisksClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&diskClient.Client) - diskClient.Authorizer = auth - diskClient.Sender = sender - c.diskClient = diskClient - - snapshotsClient := disk.NewSnapshotsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&snapshotsClient.Client) - snapshotsClient.Authorizer = auth - snapshotsClient.Sender = sender - c.snapshotsClient = snapshotsClient -} - -func (c *ArmClient) registerKeyVaultClients(endpoint, subscriptionId string, auth autorest.Authorizer, keyVaultAuth autorest.Authorizer, sender autorest.Sender) { - keyVaultClient := keyvault.NewVaultsClientWithBaseURI(endpoint, subscriptionId) - setUserAgent(&keyVaultClient.Client) - keyVaultClient.Authorizer = auth - keyVaultClient.Sender = sender - c.keyVaultClient = keyVaultClient - - keyVaultManagementClient := keyVault.New() - setUserAgent(&keyVaultManagementClient.Client) - keyVaultManagementClient.Authorizer = keyVaultAuth - keyVaultManagementClient.Sender = sender - c.keyVaultManagementClient = keyVaultManagementClient -} - -func (armClient *ArmClient) getKeyForStorageAccount(resourceGroupName, storageAccountName string) (string, bool, error) { - accountKeys, err := armClient.storageServiceClient.ListKeys(resourceGroupName, storageAccountName) - if accountKeys.StatusCode == http.StatusNotFound { - return "", false, nil - } - if err != nil { - // We assume this is a transient error rather than a 404 (which is caught above), so assume the - // account still exists. - return "", true, fmt.Errorf("Error retrieving keys for storage account %q: %s", storageAccountName, err) - } - - if accountKeys.Keys == nil { - return "", false, fmt.Errorf("Nil key returned for storage account %q", storageAccountName) - } - - keys := *accountKeys.Keys - return *keys[0].Value, true, nil -} - -func (armClient *ArmClient) getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.BlobStorageClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - blobClient := storageClient.GetBlobService() - return &blobClient, true, nil -} - -func (armClient *ArmClient) getFileServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.FileServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - fileClient := storageClient.GetFileService() - return &fileClient, true, nil -} - -func (armClient *ArmClient) getTableServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.TableServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - tableClient := storageClient.GetTableService() - return &tableClient, true, nil -} - -func (armClient *ArmClient) getQueueServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.QueueServiceClient, bool, error) { - key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return nil, accountExists, err - } - if accountExists == false { - return nil, false, nil - } - - storageClient, err := mainStorage.NewClient(storageAccountName, key, armClient.environment.StorageEndpointSuffix, - mainStorage.DefaultAPIVersion, true) - if err != nil { - return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) - } - - queueClient := storageClient.GetQueueService() - return &queueClient, true, nil -} diff --git a/azurerm/provider.go b/azurerm/provider.go index 666c331f3a63..e297c88ea469 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -170,10 +170,7 @@ func Provider() terraform.ResourceProvider { "azurerm_virtual_network": resourceArmVirtualNetwork(), "azurerm_virtual_network_peering": resourceArmVirtualNetworkPeering(), "azurerm_iothub": resourceArmIotHub(), -<<<<<<< HEAD -======= "azurerm_iothub_consumer_group": resourceArmIotHubConsumerGroup(), ->>>>>>> 60cd688486d722c6c36a4ee7155f24252405c0d8 }, } diff --git a/azurerm/resource_arm_iothub_consumer_group.go b/azurerm/resource_arm_iothub_consumer_group.go index aea9604b92d8..84a1300743a0 100644 --- a/azurerm/resource_arm_iothub_consumer_group.go +++ b/azurerm/resource_arm_iothub_consumer_group.go @@ -10,27 +10,10 @@ import ( func resourceArmIotHubConsumerGroup() *schema.Resource { return &schema.Resource{ -<<<<<<< HEAD Create: resourceArmIotHubConsumerGroupCreate, Read: resourceArmIotHubConsumerGroupRead, Delete: resourceArmIotHubConsumerGroupDelete, - Schema: map[string]*schema.Schema{ - "consumer_group_name": { - Type: schema.TypeString, - Required: true, - }, - "resource_group_name": { - Type: schema.TypeString, - Required: true, - }, - "iotHub_name": { -======= - Create: resourceArmIotHubConsumerGroupCreateUpdate, - Read: resourceArmIotHubConsumerGroupRead, - Update: resourceArmIotHubConsumerGroupCreateUpdate, - Delete: resourceArmIotHubConsumerGroupDelete, - Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, @@ -39,36 +22,27 @@ func resourceArmIotHubConsumerGroup() *schema.Resource { }, "resource_group_name": resourceGroupNameSchema(), "iot_hub_name": { ->>>>>>> 60cd688486d722c6c36a4ee7155f24252405c0d8 Type: schema.TypeString, Required: true, + ForceNew: true, }, "event_hub_endpoint": { Type: schema.TypeString, Required: true, + ForceNew: true, }, }, } } -<<<<<<< HEAD func resourceArmIotHubConsumerGroupCreate(d *schema.ResourceData, meta interface{}) error { -======= -func resourceArmIotHubConsumerGroupCreateUpdate(d *schema.ResourceData, meta interface{}) error { ->>>>>>> 60cd688486d722c6c36a4ee7155f24252405c0d8 armClient := meta.(*ArmClient) iothubClient := armClient.iothubResourceClient log.Printf("[INFO} preparing arguments for AzureRM IoTHub Consumer Group creation.") -<<<<<<< HEAD - groupName := d.Get("consumer_group_name").(string) - resourceGroup := d.Get("resource_group_name").(string) - iotHubName := d.Get("iotHub_name").(string) -======= groupName := d.Get("name").(string) resourceGroup := d.Get("resource_group_name").(string) iotHubName := d.Get("iot_hub_name").(string) ->>>>>>> 60cd688486d722c6c36a4ee7155f24252405c0d8 eventhubEndpoint := d.Get("event_hub_endpoint").(string) _, err := iothubClient.CreateEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) @@ -113,15 +87,9 @@ func resourceArmIotHubConsumerGroupRead(d *schema.ResourceData, meta interface{} return fmt.Errorf("Error making read request on Azure IoTHub Consumer Group %s: %+v", groupName, err) } -<<<<<<< HEAD - d.Set("consumer_group_name", groupName) - d.Set("resource_group_name", resourceGroup) - d.Set("iotHub_name", iotHubName) -======= d.Set("name", groupName) d.Set("resource_group_name", resourceGroup) d.Set("iot_hub_name", iotHubName) ->>>>>>> 60cd688486d722c6c36a4ee7155f24252405c0d8 d.Set("event_hub_endpoint", eventhubEndpoint) return nil From 421eda6f667b3b1244ce6fff9da1ac42d1c5eb25 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Tue, 2 Jan 2018 18:13:19 -0600 Subject: [PATCH 44/69] keys datasource initial commit Signed-off-by: shelley.bess --- azurerm/data_source_arm_iothub_keys.go | 98 +++----------------------- 1 file changed, 10 insertions(+), 88 deletions(-) diff --git a/azurerm/data_source_arm_iothub_keys.go b/azurerm/data_source_arm_iothub_keys.go index 2349e475890d..0a2323a7bc5f 100644 --- a/azurerm/data_source_arm_iothub_keys.go +++ b/azurerm/data_source_arm_iothub_keys.go @@ -1,12 +1,10 @@ package azurerm import ( + "fmt" "log" - "github.com/Azure/azure-sdk-for-go/dataplane/keyvault" - "github.com/hashicorp/terraform/helper/schema" - "github.com/hashicorp/terraform/helper/validation" ) func dataSourceArmIotHubKeys() *schema.Resource { @@ -18,109 +16,33 @@ func dataSourceArmIotHubKeys() *schema.Resource { Type: schema.TypeString, Required: true, }, - "key_name": { - Type: schema.TypeString, - Required: true, - }, "resource_group_name": resourceGroupNameForDataSourceSchema(), - "key_type": { + "iot_hub_name": { Type: schema.TypeString, Required: true, - // turns out Azure's *really* sensitive about the casing of these - // issue: https://github.com/Azure/azure-rest-api-specs/issues/1739 - ValidateFunc: validation.StringInSlice([]string{ - // TODO: add `oct` back in once this is fixed - // https://github.com/Azure/azure-rest-api-specs/issues/1739#issuecomment-332236257 - string(keyvault.EC), - string(keyvault.RSA), - string(keyvault.RSAHSM), - }, false), - }, - "key_size": { - Type: schema.TypeInt, - Required: true, - }, - "key_opts": { - Type: schema.TypeList, - Elem: &schema.Schema{ - Type: schema.TypeString, - // turns out Azure's *really* sensitive about the casing of these - // issue: https://github.com/Azure/azure-rest-api-specs/issues/1739 - ValidateFunc: validation.StringInSlice([]string{ - string(keyvault.Decrypt), - string(keyvault.Encrypt), - string(keyvault.Sign), - string(keyvault.UnwrapKey), - string(keyvault.Verify), - string(keyvault.WrapKey), - }, false), - }, - }, - // Computed - "version": { - Type: schema.TypeString, - Computed: true, - }, - - "n": { - Type: schema.TypeString, - Computed: true, }, - - "e": { - Type: schema.TypeString, - Computed: true, - }, - - "tags": tagsSchema(), }, } } func dataSourceArmIotHubKeysRead(d *schema.ResourceData, meta interface{}) error { armClient := meta.(*ArmClient) - + iothubClient := armClient.iothubResourceClient log.Printf("[INFO] Acquiring Keys for Authentication") name := d.Get("name").(string) resourceGroup := d.Get("resource_group_name").(string) - keyName := d.Get("key_name").(string) - resourceId := &ResourceID{ - SubscriptionID: armClient.subscriptionId, - ResourceGroup: resourceGroup, - } - resourceIdString, err := composeAzureResourceID(resourceId) + iotHub := d.Get("iot_hub_name").(string) + keys, err := iothubClient.GetKeysForKeyName(resourceGroup, iotHub, name) if err != nil { - return err + return fmt.Errorf("Error retrieving keys with name: %s", name) } - d.SetId(resourceIdString) - - if err := resourceArmResourceGroupRead(d, meta); err != nil { - return err - } - // query := &iothub.SharedAccessSignatureAuthorizationRule{ - // KeyName: &keyName, - // } - - // subscriptionID := armClient.subscriptionId - // resourceId := &ResourceID{ - // SubscriptionID: armClient.iothubResourceClient.SubscriptionID, - // ResourceGroup: name, - // } - // desc := iothub.Description{ - // Resourcegroup: &resourceGroup, - // Name: &name, - // Subscriptionid: &subscriptionID, - // } - // resourceIdString, err := composeAzureResourceID(resourceId) - - // if err != nil { - // return err - // } - - // d.SetId(resourceIdString) + d.Set("key_name", keys.KeyName) + d.Set("primary_key", keys.PrimaryKey) + d.Set("secondary_key", keys.SecondaryKey) + d.Set("permissions", string(keys.Rights)) return nil } From 67c093bdae342f9bd0ac4c3879c1dc6e89f939b0 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Tue, 2 Jan 2018 19:52:54 -0600 Subject: [PATCH 45/69] sku datasource initial commit Signed-off-by: shelley.bess --- azurerm/data_source_arm_iothub_sku.go | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/azurerm/data_source_arm_iothub_sku.go b/azurerm/data_source_arm_iothub_sku.go index 22e1d8c09ab2..0bd78a5faba7 100644 --- a/azurerm/data_source_arm_iothub_sku.go +++ b/azurerm/data_source_arm_iothub_sku.go @@ -11,12 +11,11 @@ func dataSourceArmIotHubSku() *schema.Resource { Read: dataSourceArmIotHubSkuRead, Schema: map[string]*schema.Schema{ - "name": { + "resource_group_name": resourceGroupNameForDataSourceSchema(), + "iot_hub_name": { Type: schema.TypeString, Required: true, - ForceNew: true, }, - "resource_group_name": resourceGroupNameForDataSourceSchema(), }, } } @@ -24,11 +23,29 @@ func dataSourceArmIotHubSku() *schema.Resource { func dataSourceArmIotHubSkuRead(d *schema.ResourceData, meta interface{}) error { armClient := meta.(*ArmClient) iothubClient := armClient.iothubResourceClient - log.Printf("[INFO] Acquiring IoTHub SKU") - name := d.Get("name").(string) + iothubName := d.Get("iot_hub_name").(string) resourceGroup := d.Get("resource_group_name").(string) + skuResp, err := iothubClient.GetValidSkus(resourceGroup, iothubName) + if err != nil { + return err + } + + var skus []map[string]interface{} + + for _, sku := range *skuResp.Value { + skuMap := make(map[string]interface{}) + skuMap["resource_type"] = *sku.ResourceType + skuMap["capacity"] = *sku.Capacity + skuMap["sku"] = *sku.Sku // SB todo: type SkuInfo Breakdown for map + skus = append(skus, skuMap) + } + + d.Set("resource_group_name", resourceGroup) + d.Set("iot_hub_name", iothubName) + d.Set("sku", skus) + return nil } From 5a82725c2d1e4221b06c366cfad9d47052b89b30 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Tue, 2 Jan 2018 21:01:05 -0600 Subject: [PATCH 46/69] added datasource to the provider list Signed-off-by: shelley.bess --- azurerm/provider.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/azurerm/provider.go b/azurerm/provider.go index e297c88ea469..7d2be46b05f3 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -80,6 +80,8 @@ func Provider() terraform.ResourceProvider { "azurerm_snapshot": dataSourceArmSnapshot(), "azurerm_subnet": dataSourceArmSubnet(), "azurerm_subscription": dataSourceArmSubscription(), + "azurerm_iothub_keys": dataSourceArmIotHubKeys(), + "azurerm_iothub_sku": dataSourceArmIotHubSku(), }, ResourcesMap: map[string]*schema.Resource{ From 4324420588a1c4fcbdc51393d59a799d9580ff26 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Tue, 2 Jan 2018 22:20:27 -0600 Subject: [PATCH 47/69] initial keys test Signed-off-by: shelley.bess --- azurerm/data_source_arm_iothub_keys_test.go | 58 +++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 azurerm/data_source_arm_iothub_keys_test.go diff --git a/azurerm/data_source_arm_iothub_keys_test.go b/azurerm/data_source_arm_iothub_keys_test.go new file mode 100644 index 000000000000..dd2b4e7d6eb4 --- /dev/null +++ b/azurerm/data_source_arm_iothub_keys_test.go @@ -0,0 +1,58 @@ +package azurerm + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccDataSourceAzureRMIotHubKeys_basic(t *testing.T) { + dataSourceName := "data.azurerm_iothub_keys.test" + ri := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceIotHubKeysConfig_basic(ri, testLocation()), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(dataSourceName, "name", "test"), + ), + }, + }, + }) +} + +func testAccDataSourceIotHubKeysConfig_basic(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "foo" { + name = "acctestIot-%d" + location = "%s" +} + +resource "azurerm_iothub" "bar" { + name = "acctestiothub-%d" + location = "${azurerm_resource_group.foo.location}" + resource_group_name = "${azurerm_resource_group.foo.name}" + sku { + name = "S1" + tier = "Standard" + capacity = "1" + } + + tags { + "purpose" = "testing" + } +} + +data "azurerm_iothub_keys" "test" { + name = "test" + resource_group_name = "${azurerm_resource_group.foo.name}" + iot_hub_name = "${azurerm_iothub.bar.name}" +} + + `, rInt, location, rInt) +} From bcf55f52602a13e8eaedcfb197272f393676f3fa Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 3 Jan 2018 11:58:05 -0600 Subject: [PATCH 48/69] initial sku test Signed-off-by: shelley.bess --- azurerm/data_source_arm_iothub_jobs.go | 51 ++++++++++++++++++ azurerm/data_source_arm_iothub_jobs_test.go | 58 +++++++++++++++++++++ azurerm/data_source_arm_iothub_sku_test.go | 56 ++++++++++++++++++++ azurerm/provider.go | 1 + azurerm/resource_arm_iothub_devices.go | 57 -------------------- 5 files changed, 166 insertions(+), 57 deletions(-) create mode 100644 azurerm/data_source_arm_iothub_jobs.go create mode 100644 azurerm/data_source_arm_iothub_jobs_test.go create mode 100644 azurerm/data_source_arm_iothub_sku_test.go delete mode 100644 azurerm/resource_arm_iothub_devices.go diff --git a/azurerm/data_source_arm_iothub_jobs.go b/azurerm/data_source_arm_iothub_jobs.go new file mode 100644 index 000000000000..17153a27af83 --- /dev/null +++ b/azurerm/data_source_arm_iothub_jobs.go @@ -0,0 +1,51 @@ +package azurerm + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform/helper/schema" +) + +func dataSourceArmIotHubJobs() *schema.Resource { + return &schema.Resource{ + Read: dataSourceArmIotHubJobsRead, + + Schema: map[string]*schema.Schema{ + "resource_group_name": resourceGroupNameForDataSourceSchema(), + "iot_hub_name": { + Type: schema.TypeString, + Required: true, + }, + "job_id": { + Type: schema.TypeString, + Required: true, + }, + }, + } +} + +func dataSourceArmIotHubJobsRead(d *schema.ResourceData, meta interface{}) error { + armClient := meta.(*ArmClient) + iothubClient := armClient.iothubResourceClient + log.Printf("[INFO] Acquiring IotHub Job ID") + + iothubName := d.Get("iot_hub_name").(string) + resourceGroup := d.Get("resource_group_name").(string) + jobID := d.Get("job_id").(string) + + jobResp, err := iothubClient.GetJob(resourceGroup, iothubName, jobID) + if err != nil { + return fmt.Errorf("Error retrieving job with id: %s", jobID) + } + + d.Set("job_id", jobResp.JobID) + d.Set("status", jobResp.Status) + d.Set("start", jobResp.StartTimeUtc) + d.Set("end", jobResp.EndTimeUtc) + d.Set("type", jobResp.Type) + if jobResp.Status == "failed" { + d.Set("status_fail", jobResp.FailureReason) + } + return nil +} diff --git a/azurerm/data_source_arm_iothub_jobs_test.go b/azurerm/data_source_arm_iothub_jobs_test.go new file mode 100644 index 000000000000..62dc0bba2f43 --- /dev/null +++ b/azurerm/data_source_arm_iothub_jobs_test.go @@ -0,0 +1,58 @@ +package azurerm + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccDataSourceAzureRMIotHubJobs_basic(t *testing.T) { + dataSourceName := "data.azurerm_iothub_jobs.test" + ri := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceIotHubJobsConfig_basic(ri, testLocation()), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(dataSourceName, "job_id", "test"), + ), + }, + }, + }) +} + +func testAccDataSourceIotHubJobsConfig_basic(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "foo" { + job_id = "acctestIot-%d" + location = "%s" +} + +resource "azurerm_iothub" "bar" { + job_id = "acctestiothub-%d" + location = "${azurerm_resource_group.foo.location}" + resource_group_name = "${azurerm_resource_group.foo.name}" + job { + name = "S1" + tier = "Standard" + capacity = "1" + } + + tags { + "purpose" = "testing" + } +} + +data "azurerm_iothub_keys" "test" { + job_id = "test" + resource_group_name = "${azurerm_resource_group.foo.name}" + iot_hub_name = "${azurerm_iothub.bar.name}" +} + + `, rInt, location, rInt) +} diff --git a/azurerm/data_source_arm_iothub_sku_test.go b/azurerm/data_source_arm_iothub_sku_test.go new file mode 100644 index 000000000000..73d77febd276 --- /dev/null +++ b/azurerm/data_source_arm_iothub_sku_test.go @@ -0,0 +1,56 @@ +package azurerm + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccDataSourceAzureRMIotHubSku_basic(t *testing.T) { + dataSourceName := "data.azurerm_iothub_sku.test" + ri := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceIotHubSkuConfig_basic(ri, testLocation()), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet(dataSourceName, "sku"), + ), + }, + }, + }) +} + +func testAccDataSourceIotHubSkuConfig_basic(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "foo" { + name = "acctestIot-%d" + location = "%s" +} + +resource "azurerm_iothub" "bar" { + name = "acctestiothub-%d" + location = "${azurerm_resource_group.foo.location}" + resource_group_name = "${azurerm_resource_group.foo.name}" + sku { + name = "S1" + tier = "Standard" + capacity = "1" + } + + tags { + "purpose" = "testing" + } +} + +data "azurerm_iothub_keys" "test" { + resource_group_name = "${azurerm_resource_group.foo.name}" + iot_hub_name = "${azurerm_iothub.bar.name}" +} + `, rInt, location, rInt) +} diff --git a/azurerm/provider.go b/azurerm/provider.go index 7d2be46b05f3..15fb3b7806b9 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -82,6 +82,7 @@ func Provider() terraform.ResourceProvider { "azurerm_subscription": dataSourceArmSubscription(), "azurerm_iothub_keys": dataSourceArmIotHubKeys(), "azurerm_iothub_sku": dataSourceArmIotHubSku(), + "azurerm_iothub_jobs": dataSourceArmIotHubJobs(), }, ResourcesMap: map[string]*schema.Resource{ diff --git a/azurerm/resource_arm_iothub_devices.go b/azurerm/resource_arm_iothub_devices.go deleted file mode 100644 index 40828b5b2d83..000000000000 --- a/azurerm/resource_arm_iothub_devices.go +++ /dev/null @@ -1,57 +0,0 @@ -package azurerm - -import ( - "github.com/hashicorp/terraform/helper/schema" -) - -func resourceArmIotHubDevices() *schema.Resource { - return &schema.Resource{ - Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, - }, - Read: resourceArmIotHubDevicesRead, - Update: resourceArmIotHubDevicesUpdate, - Delete: resourceArmIotHubDevicesDelete, - - Schema: map[string]*schema.Schema{ - "device_name": { - Type: schema.TypeString, - Required: true, - }, - "resource_group_name": resourceGroupNameSchema(), - "iotHub_name": { - Type: schema.TypeString, - Required: true, - }, - "import_device_parameters": { - Type: schema.TypeString, - Required: true, - }, - "import_device_request": { - Type: schema.TypeString, - Required: true, - }, - }, - } -} - -func resourceArmIotHubDevicesRead(d *schema.ResourceData, meta interface{}) error { - armClient := meta.(*ArmClient) - iothubClient := armClient.iothubResourceClient - - return nil -} - -func resourceArmIotHubDevicesUpdate(d *schema.ResourceData, meta interface{}) error { - armClient := meta.(*ArmClient) - iothubClient := armClient.iothubResourceClient - - return resourceArmIotHubDevicesRead(d, meta) -} - -func resourceArmIotHubDevicesDelete(d *schema.ResourceData, meta interface{}) error { - armClient := meta.(*ArmClient) - iothubClient := armClient.iothubResourceClient - - return nil -} From b425073015140a9ec378d29a5b6626da3e953ce0 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 3 Jan 2018 14:30:33 -0600 Subject: [PATCH 49/69] keys datasource documentation Signed-off-by: shelley.bess --- azurerm/data_source_arm_iothub_jobs_test.go | 2 +- azurerm/resource_arm_iothub_consumer_group.go | 19 ++++----- website/azurerm.erb | 4 ++ website/docs/d/iothub_keys.html.markdown | 42 +++++++++++++++++++ .../r/iothub_consumer_group.html.markdown | 11 +++-- 5 files changed, 61 insertions(+), 17 deletions(-) create mode 100644 website/docs/d/iothub_keys.html.markdown diff --git a/azurerm/data_source_arm_iothub_jobs_test.go b/azurerm/data_source_arm_iothub_jobs_test.go index 62dc0bba2f43..6a4bb589151a 100644 --- a/azurerm/data_source_arm_iothub_jobs_test.go +++ b/azurerm/data_source_arm_iothub_jobs_test.go @@ -48,7 +48,7 @@ resource "azurerm_iothub" "bar" { } } -data "azurerm_iothub_keys" "test" { +data "azurerm_iothub_jobs" "test" { job_id = "test" resource_group_name = "${azurerm_resource_group.foo.name}" iot_hub_name = "${azurerm_iothub.bar.name}" diff --git a/azurerm/resource_arm_iothub_consumer_group.go b/azurerm/resource_arm_iothub_consumer_group.go index 84a1300743a0..2e27a62c2656 100644 --- a/azurerm/resource_arm_iothub_consumer_group.go +++ b/azurerm/resource_arm_iothub_consumer_group.go @@ -31,6 +31,7 @@ func resourceArmIotHubConsumerGroup() *schema.Resource { Required: true, ForceNew: true, }, + "tags": tagsSchema(), }, } } @@ -74,9 +75,9 @@ func resourceArmIotHubConsumerGroupRead(d *schema.ResourceData, meta interface{} } resourceGroup := id.ResourceGroup - groupName := id.Path["consumergroups"] - iotHubName := id.Path["resourcename"] - eventhubEndpoint := id.Path["eventhubs"] + groupName := id.Path["name"] + iotHubName := id.Path["resourceName"] + eventhubEndpoint := id.Path["eventHubEndpointName"] resp, err := iothubClient.GetEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) if err != nil { @@ -87,10 +88,8 @@ func resourceArmIotHubConsumerGroupRead(d *schema.ResourceData, meta interface{} return fmt.Errorf("Error making read request on Azure IoTHub Consumer Group %s: %+v", groupName, err) } - d.Set("name", groupName) - d.Set("resource_group_name", resourceGroup) - d.Set("iot_hub_name", iotHubName) - d.Set("event_hub_endpoint", eventhubEndpoint) + d.Set("name", *resp.Name) + flattenAndSetTags(d, resp.Tags) return nil } @@ -105,9 +104,9 @@ func resourceArmIotHubConsumerGroupDelete(d *schema.ResourceData, meta interface } resourceGroup := id.ResourceGroup - groupName := id.Path["consumergroups"] - iotHubName := id.Path["resourcename"] - eventhubEndpoint := id.Path["eventhubs"] + groupName := id.Path["name"] + iotHubName := id.Path["resourceName"] + eventhubEndpoint := id.Path["eventHubEndpointName"] resp, err := iothubClient.DeleteEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) if err != nil { diff --git a/website/azurerm.erb b/website/azurerm.erb index bbffc5a3115b..743132835826 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -35,6 +35,10 @@ azurerm_image + > + azurerm_iothub_keys + + > azurerm_key_vault_access_policy diff --git a/website/docs/d/iothub_keys.html.markdown b/website/docs/d/iothub_keys.html.markdown new file mode 100644 index 000000000000..4331c124e4f2 --- /dev/null +++ b/website/docs/d/iothub_keys.html.markdown @@ -0,0 +1,42 @@ +--- +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_iothub_keys" +sidebar_current: "docs-azurerm-datasource-iothub-keys" +description: |- + Get shared access policy +--- + +# azurerm\_iothub_keys + +Get a shared access policy by name from an IoT hub. + +## Example Usage + +```hcl +data "azurerm_iothub_keys" "test" { + name = "Shared Access Policy" + resource_group_name = "ResourceGroupTest" + iot_hub_name = "IoTHub" +} + +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Specifies the name of the shared access policy which contains access keys and permissions. + +* `resource_group_name` - (Required) The name of the resource group that contains the IoT hub. + +* `iot_hub_name` - (Required) The name of the IoT hub. + +## Attributes Reference + +The following attributes are exported: + +* `primary_key` - The primary key. + +* `secondary_key` - The secondary key. + +* `permissions` - The permissions assigned to the shared access policy. diff --git a/website/docs/r/iothub_consumer_group.html.markdown b/website/docs/r/iothub_consumer_group.html.markdown index 727a82047504..c1530a8fdc47 100644 --- a/website/docs/r/iothub_consumer_group.html.markdown +++ b/website/docs/r/iothub_consumer_group.html.markdown @@ -47,17 +47,16 @@ resource "azurerm_iothub_consumer_group" "test" { The following arguments are supported: -* `name` (Required) Specifies the name of the Consumer Group resource. Changing this forces a new resource to be created. +* `name` - (Required) Specifies the name of the Consumer Group resource. Changing this forces a new resource to be created. -* `resource_group_name` (Required) The name of the resource group that contains the IoT hub. +* `resource_group_name` - (Required) The name of the resource group that contains the IoT hub. -* `iot_hub_name` (Required) The name of the IoT hub. +* `iot_hub_name` - (Required) The name of the IoT hub. -* `event_hub_endpoint` (Required) The name of the Event Hub-compatible endpoint in the IoT hub. +* `event_hub_endpoint` - (Required) The name of the Event Hub-compatible endpoint in the IoT hub. ## Attributes Reference The following attributes are exported: -WIP - +* `id` - The Event Hub-compatible consumer group identifier. From abbedb06f1bb6984c4995229c8a597016e5941c5 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 3 Jan 2018 18:08:30 -0600 Subject: [PATCH 50/69] sku datasource documentation Signed-off-by: shelley.bess --- azurerm/data_source_arm_iothub_jobs.go | 51 -------- azurerm/data_source_arm_iothub_jobs_test.go | 58 --------- azurerm/data_source_arm_iothub_keys.go | 18 ++- azurerm/data_source_arm_iothub_sku_test.go | 2 +- azurerm/provider.go | 2 - azurerm/resource_arm_iothub_consumer_group.go | 119 ------------------ ...resource_arm_iothub_consumer_group_test.go | 118 ----------------- .../resource_arm_iothub_resource_provider.go | 2 - ...ource_arm_iothub_resource_provider_test.go | 28 +++-- website/azurerm.erb | 17 +-- website/docs/d/iothub_sku.html.markdown | 37 ++++++ .../r/iothub_consumer_group.html.markdown | 62 --------- 12 files changed, 69 insertions(+), 445 deletions(-) delete mode 100644 azurerm/data_source_arm_iothub_jobs.go delete mode 100644 azurerm/data_source_arm_iothub_jobs_test.go delete mode 100644 azurerm/resource_arm_iothub_consumer_group.go delete mode 100644 azurerm/resource_arm_iothub_consumer_group_test.go create mode 100644 website/docs/d/iothub_sku.html.markdown delete mode 100644 website/docs/r/iothub_consumer_group.html.markdown diff --git a/azurerm/data_source_arm_iothub_jobs.go b/azurerm/data_source_arm_iothub_jobs.go deleted file mode 100644 index 17153a27af83..000000000000 --- a/azurerm/data_source_arm_iothub_jobs.go +++ /dev/null @@ -1,51 +0,0 @@ -package azurerm - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform/helper/schema" -) - -func dataSourceArmIotHubJobs() *schema.Resource { - return &schema.Resource{ - Read: dataSourceArmIotHubJobsRead, - - Schema: map[string]*schema.Schema{ - "resource_group_name": resourceGroupNameForDataSourceSchema(), - "iot_hub_name": { - Type: schema.TypeString, - Required: true, - }, - "job_id": { - Type: schema.TypeString, - Required: true, - }, - }, - } -} - -func dataSourceArmIotHubJobsRead(d *schema.ResourceData, meta interface{}) error { - armClient := meta.(*ArmClient) - iothubClient := armClient.iothubResourceClient - log.Printf("[INFO] Acquiring IotHub Job ID") - - iothubName := d.Get("iot_hub_name").(string) - resourceGroup := d.Get("resource_group_name").(string) - jobID := d.Get("job_id").(string) - - jobResp, err := iothubClient.GetJob(resourceGroup, iothubName, jobID) - if err != nil { - return fmt.Errorf("Error retrieving job with id: %s", jobID) - } - - d.Set("job_id", jobResp.JobID) - d.Set("status", jobResp.Status) - d.Set("start", jobResp.StartTimeUtc) - d.Set("end", jobResp.EndTimeUtc) - d.Set("type", jobResp.Type) - if jobResp.Status == "failed" { - d.Set("status_fail", jobResp.FailureReason) - } - return nil -} diff --git a/azurerm/data_source_arm_iothub_jobs_test.go b/azurerm/data_source_arm_iothub_jobs_test.go deleted file mode 100644 index 6a4bb589151a..000000000000 --- a/azurerm/data_source_arm_iothub_jobs_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package azurerm - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform/helper/acctest" - "github.com/hashicorp/terraform/helper/resource" -) - -func TestAccDataSourceAzureRMIotHubJobs_basic(t *testing.T) { - dataSourceName := "data.azurerm_iothub_jobs.test" - ri := acctest.RandInt() - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: testAccDataSourceIotHubJobsConfig_basic(ri, testLocation()), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(dataSourceName, "job_id", "test"), - ), - }, - }, - }) -} - -func testAccDataSourceIotHubJobsConfig_basic(rInt int, location string) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "foo" { - job_id = "acctestIot-%d" - location = "%s" -} - -resource "azurerm_iothub" "bar" { - job_id = "acctestiothub-%d" - location = "${azurerm_resource_group.foo.location}" - resource_group_name = "${azurerm_resource_group.foo.name}" - job { - name = "S1" - tier = "Standard" - capacity = "1" - } - - tags { - "purpose" = "testing" - } -} - -data "azurerm_iothub_jobs" "test" { - job_id = "test" - resource_group_name = "${azurerm_resource_group.foo.name}" - iot_hub_name = "${azurerm_iothub.bar.name}" -} - - `, rInt, location, rInt) -} diff --git a/azurerm/data_source_arm_iothub_keys.go b/azurerm/data_source_arm_iothub_keys.go index 0a2323a7bc5f..3925cff07f4f 100644 --- a/azurerm/data_source_arm_iothub_keys.go +++ b/azurerm/data_source_arm_iothub_keys.go @@ -9,7 +9,7 @@ import ( func dataSourceArmIotHubKeys() *schema.Resource { return &schema.Resource{ - Read: dataSourceArmIotHubSkuRead, + Read: dataSourceArmIotHubKeysRead, Schema: map[string]*schema.Schema{ "name": { @@ -34,15 +34,21 @@ func dataSourceArmIotHubKeysRead(d *schema.ResourceData, meta interface{}) error resourceGroup := d.Get("resource_group_name").(string) iotHub := d.Get("iot_hub_name").(string) - keys, err := iothubClient.GetKeysForKeyName(resourceGroup, iotHub, name) + key, err := iothubClient.GetKeysForKeyName(resourceGroup, iotHub, name) if err != nil { return fmt.Errorf("Error retrieving keys with name: %s", name) } - d.Set("key_name", keys.KeyName) - d.Set("primary_key", keys.PrimaryKey) - d.Set("secondary_key", keys.SecondaryKey) - d.Set("permissions", string(keys.Rights)) + var keys []map[string]interface{} + keyMap := make(map[string]interface{}) + keyMap["key_name"] = *key.KeyName + keyMap["primary_key"] = *key.PrimaryKey + keyMap["secondary_key"] = *key.SecondaryKey + keyMap["permissions"] = string(key.Rights) + keys = append(keys, keyMap) + + d.SetId(name) + d.Set("shared_access_policy", keys) return nil } diff --git a/azurerm/data_source_arm_iothub_sku_test.go b/azurerm/data_source_arm_iothub_sku_test.go index 73d77febd276..1effd045b2b9 100644 --- a/azurerm/data_source_arm_iothub_sku_test.go +++ b/azurerm/data_source_arm_iothub_sku_test.go @@ -48,7 +48,7 @@ resource "azurerm_iothub" "bar" { } } -data "azurerm_iothub_keys" "test" { +data "azurerm_iothub_sku" "test" { resource_group_name = "${azurerm_resource_group.foo.name}" iot_hub_name = "${azurerm_iothub.bar.name}" } diff --git a/azurerm/provider.go b/azurerm/provider.go index 15fb3b7806b9..18a591b32384 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -82,7 +82,6 @@ func Provider() terraform.ResourceProvider { "azurerm_subscription": dataSourceArmSubscription(), "azurerm_iothub_keys": dataSourceArmIotHubKeys(), "azurerm_iothub_sku": dataSourceArmIotHubSku(), - "azurerm_iothub_jobs": dataSourceArmIotHubJobs(), }, ResourcesMap: map[string]*schema.Resource{ @@ -173,7 +172,6 @@ func Provider() terraform.ResourceProvider { "azurerm_virtual_network": resourceArmVirtualNetwork(), "azurerm_virtual_network_peering": resourceArmVirtualNetworkPeering(), "azurerm_iothub": resourceArmIotHub(), - "azurerm_iothub_consumer_group": resourceArmIotHubConsumerGroup(), }, } diff --git a/azurerm/resource_arm_iothub_consumer_group.go b/azurerm/resource_arm_iothub_consumer_group.go deleted file mode 100644 index 2e27a62c2656..000000000000 --- a/azurerm/resource_arm_iothub_consumer_group.go +++ /dev/null @@ -1,119 +0,0 @@ -package azurerm - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform/helper/schema" - "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" -) - -func resourceArmIotHubConsumerGroup() *schema.Resource { - return &schema.Resource{ - Create: resourceArmIotHubConsumerGroupCreate, - Read: resourceArmIotHubConsumerGroupRead, - Delete: resourceArmIotHubConsumerGroupDelete, - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - "resource_group_name": resourceGroupNameSchema(), - "iot_hub_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - "event_hub_endpoint": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - "tags": tagsSchema(), - }, - } -} - -func resourceArmIotHubConsumerGroupCreate(d *schema.ResourceData, meta interface{}) error { - armClient := meta.(*ArmClient) - iothubClient := armClient.iothubResourceClient - log.Printf("[INFO} preparing arguments for AzureRM IoTHub Consumer Group creation.") - - groupName := d.Get("name").(string) - resourceGroup := d.Get("resource_group_name").(string) - iotHubName := d.Get("iot_hub_name").(string) - eventhubEndpoint := d.Get("event_hub_endpoint").(string) - - _, err := iothubClient.CreateEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) - if err != nil { - return err - } - - check, err := iothubClient.GetEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) - if err != nil { - return err - } - - if check.ID == nil { - return fmt.Errorf("Cannot read IoTHub Consumer Group %s (resource group %s) ID", groupName, resourceGroup) - } - - d.SetId(*check.ID) - - return resourceArmIotHubConsumerGroupRead(d, meta) -} - -func resourceArmIotHubConsumerGroupRead(d *schema.ResourceData, meta interface{}) error { - armClient := meta.(*ArmClient) - iothubClient := armClient.iothubResourceClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - - resourceGroup := id.ResourceGroup - groupName := id.Path["name"] - iotHubName := id.Path["resourceName"] - eventhubEndpoint := id.Path["eventHubEndpointName"] - - resp, err := iothubClient.GetEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) - if err != nil { - if utils.ResponseWasNotFound(resp.Response) { - d.SetId("") - return nil - } - return fmt.Errorf("Error making read request on Azure IoTHub Consumer Group %s: %+v", groupName, err) - } - - d.Set("name", *resp.Name) - flattenAndSetTags(d, resp.Tags) - - return nil -} - -func resourceArmIotHubConsumerGroupDelete(d *schema.ResourceData, meta interface{}) error { - armClient := meta.(*ArmClient) - iothubClient := armClient.iothubResourceClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - - resourceGroup := id.ResourceGroup - groupName := id.Path["name"] - iotHubName := id.Path["resourceName"] - eventhubEndpoint := id.Path["eventHubEndpointName"] - - resp, err := iothubClient.DeleteEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) - if err != nil { - if !utils.ResponseWasNotFound(resp) { - return fmt.Errorf("Error issuing Azure ARM delete request of IoTHub Consumer Group '%s' : %+v", groupName, err) - } - } - - return nil -} diff --git a/azurerm/resource_arm_iothub_consumer_group_test.go b/azurerm/resource_arm_iothub_consumer_group_test.go deleted file mode 100644 index 9fd3ac14e0e8..000000000000 --- a/azurerm/resource_arm_iothub_consumer_group_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package azurerm - -import ( - "fmt" - "net/http" - "testing" - - "github.com/hashicorp/terraform/helper/acctest" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" -) - -func TestAccAzureRMIotHubConsumerGroup_basic(t *testing.T) { - ri := acctest.RandInt() - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMIotHubConsumerGroupDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAzureRMIotHubConsumerGroupConfig(ri, testLocation()), - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMIotHubConsumerGroupExists("azurerm_iothub_consumer_group.foo"), - ), - }, - }, - }) -} - -func testCheckAzureRMIotHubConsumerGroupExists(name string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - groupName := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for IoT Hub Consumer Group: %s", groupName) - } - - conn := testAccProvider.Meta().(*ArmClient).iothubResourceClient - - iotHubName := rs.Primary.Attributes["iot_hub_name"] - eventhubEndpoint := rs.Primary.Attributes["event_hub_endpoint"] - - resp, err := conn.GetEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) - if err != nil { - return fmt.Errorf("Bad: Error on GetEventHubConsumerGroup: %+v", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: IotHub Get Event hub consumer group %q (resource group: %q) does not exist", groupName, resourceGroup) - } - - return nil - } -} - -func testCheckAzureRMIotHubConsumerGroupDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*ArmClient).iothubResourceClient - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_eventhub_consuemr_group" { - continue - } - - groupName := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - iotHubName := rs.Primary.Attributes["iot_hub_name"] - eventhubEndpoint := rs.Primary.Attributes["event_hub_endpoint"] - - resp, err := conn.GetEventHubConsumerGroup(resourceGroup, iotHubName, eventhubEndpoint, groupName) - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("IoTHub endpoint consumer group still exists: %q", groupName) - } - } - - return nil -} - -func testAccAzureRMIotHubConsumerGroupConfig(rInt int, location string) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "foo" { - name = "acctestIot-%d" - location = "%s" -} - -resource "azurerm_iothub" "bar" { - name = "acctestiothub-%d" - location = "${azurerm_resource_group.foo.location}" - resource_group_name = "${azurerm_resource_group.foo.name}" - sku { - name = "S1" - tier = "Standard" - capacity = "1" - } - - tags { - "purpose" = "testing" - } -} - -resource "azurerm_iothub_consumer_group" "foo" { - name = "acctestiothubgroup-%d" - resource_group_name = "${azurerm_resource_group.foo.location}" - iot_hub_name = "${azurerm_iothub.bar.name}" - event_hub_endpoint = "test" -} -`, rInt, location, rInt, rInt) - -} diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 295065eecc4e..e09f6ac6247e 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -2,7 +2,6 @@ package azurerm import ( "errors" - "log" "github.com/Azure/azure-sdk-for-go/arm/iothub" "github.com/hashicorp/terraform/helper/schema" @@ -218,7 +217,6 @@ func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { if err != nil { return err } - log.Println("[GIRISH]", keys) d.Set("shared_access_policy", keys) d.Set("hostname", *properties.HostName) diff --git a/azurerm/resource_arm_iothub_resource_provider_test.go b/azurerm/resource_arm_iothub_resource_provider_test.go index 3a21fd6bbf25..1d5fbdde7a76 100644 --- a/azurerm/resource_arm_iothub_resource_provider_test.go +++ b/azurerm/resource_arm_iothub_resource_provider_test.go @@ -10,18 +10,17 @@ import ( "github.com/hashicorp/terraform/terraform" ) -// change this to use ephemeral dynamic resource groups -const TestResourceGroup = "girishsandbox" - func TestAccAzureRMIotHub_basicStandard(t *testing.T) { name := acctest.RandString(6) + rgname := acctest.RandString(5) + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testCheckAzureRMIotHubDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMIotHub_basicStandard(name, TestResourceGroup, testLocation()), + Config: testAccAzureRMIotHub_basicStandard(name, rgname), Check: resource.ComposeTestCheckFunc( testCheckAzureRMIotHubExists("azurerm_iothub.test"), ), @@ -83,23 +82,26 @@ func testCheckAzureRMIotHubExists(name string) resource.TestCheckFunc { } } -func testAccAzureRMIotHub_basicStandard(name, rg, location string) string { +func testAccAzureRMIotHub_basicStandard(name, rgname string) string { return fmt.Sprintf(` - resource "azurerm_iothub" "test" { +resource "azurerm_resource_group" "foo" { + name = "acctestRG-%s" + location = "East Us" +} + +resource "azurerm_iothub" "test" { name = "%s" - resource_group_name = "%s" - location = "%s" + resource_group_name = "${azurerm_resource_group.foo.name}" + location = "eastus" sku { name = "S1" tier = "Standard" - capacity = "1" + capacity = "1" } tags { "purpose" = "testing" } - } - - - `, name, rg, location) +} +`, rgname, name) } diff --git a/website/azurerm.erb b/website/azurerm.erb index 743132835826..468fdf8b5920 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -39,6 +39,10 @@ azurerm_iothub_keys + > + azurerm_iothub_sku + + > azurerm_key_vault_access_policy @@ -546,18 +550,6 @@ > azurerm_iothub - > - azurerm_iothub_consumer_group - - - - - > - IotHub Resources - @@ -565,7 +557,6 @@ Azure Service Management Provider » - <% end %> diff --git a/website/docs/d/iothub_sku.html.markdown b/website/docs/d/iothub_sku.html.markdown new file mode 100644 index 000000000000..0ac17b6e2d52 --- /dev/null +++ b/website/docs/d/iothub_sku.html.markdown @@ -0,0 +1,37 @@ +--- +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_iothub_sku" +sidebar_current: "docs-azurerm-datasource-iothub-sku" +description: |- + Get sku +--- + +# azurerm\_iothub_sku + +Get the list of valid SKUs for an IoT hub. + +## Example Usage + +```hcl +data "azurerm_iothub_sku" "test" { + resource_group_name = "ResourceGroupTest" + iot_hub_name = "IoTHub" +} + +``` + +## Argument Reference + +The following arguments are supported: + +* `resource_group_name` - (Required) The name of the resource group that contains the IoT hub. + +* `iot_hub_name` - (Required) The name of the IoT hub. + +## Attributes Reference + +The following attributes are exported: + +* `tier` - The billing tier for the IoT hub. + +* `name` - The name of the SKU. diff --git a/website/docs/r/iothub_consumer_group.html.markdown b/website/docs/r/iothub_consumer_group.html.markdown deleted file mode 100644 index c1530a8fdc47..000000000000 --- a/website/docs/r/iothub_consumer_group.html.markdown +++ /dev/null @@ -1,62 +0,0 @@ ---- -layout: "azurerm" -page_title: "Azure Resource Manager: azurerm_iothub_consumer_group" -sidebar_current: "docs-azurerm-resource-iothub-consumer-group" -description: |- - Adds a consumer group to an Event Hub-compatible endpoint in an IoT hub. ---- - -# azurerm\_iothub\_consumer\_group - -Creates a new consumer group - -## Example Usage - -```hcl -resource "azurerm_resource_group" "test" { - name = "acctestIot-%d" - location = "West US" -} - -resource "azurerm_iothub" "test" { - name = "test" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - sku { - name = "S1" - tier = "Standard" - capacity = "1" - } - - tags { - "purpose" = "testing" - } -} - -resource "azurerm_iothub_consumer_group" "test" { - name = "test" - resource_group_name = "${azurerm_resource_group.test.location}" - iot_hub_name = "${azurerm_iothub.test.name}" - event_hub_endpoint = "test" -} - - -``` - -## Argument Reference - -The following arguments are supported: - -* `name` - (Required) Specifies the name of the Consumer Group resource. Changing this forces a new resource to be created. - -* `resource_group_name` - (Required) The name of the resource group that contains the IoT hub. - -* `iot_hub_name` - (Required) The name of the IoT hub. - -* `event_hub_endpoint` - (Required) The name of the Event Hub-compatible endpoint in the IoT hub. - -## Attributes Reference - -The following attributes are exported: - -* `id` - The Event Hub-compatible consumer group identifier. From 44b85f2f85d6882c59e6c18dd22dfafcc237137b Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Tue, 27 Feb 2018 10:24:03 -0600 Subject: [PATCH 51/69] Modify for dependencies --- azurerm/config.go | 16 ++-- azurerm/provider.go | 2 +- .../mgmt/2017-07-01/devices/certificates.go | 2 +- .../iothub/mgmt/2017-07-01/devices/client.go | 2 +- .../mgmt/2017-07-01/devices/iothubresource.go | 2 +- .../iothub/mgmt/2017-07-01/devices/models.go | 2 +- .../mgmt/2017-07-01/devices/operations.go | 2 +- .../iothub/mgmt/2017-07-01/devices/version.go | 2 +- .../Azure/azure-sdk-for-go/version/version.go | 21 +++++ .../Azure/go-autorest/autorest/azure/async.go | 87 ++++++++++++++---- .../Azure/go-autorest/autorest/azure/azure.go | 88 ++++++++++++++++--- .../autorest/azure/environments.go | 13 ++- .../Azure/go-autorest/autorest/azure/rp.go | 7 +- .../go-autorest/autorest/validation/error.go | 48 ++++++++++ .../autorest/validation/validation.go | 4 +- vendor/vendor.json | 26 ++++-- 16 files changed, 262 insertions(+), 62 deletions(-) create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/version/version.go create mode 100644 vendor/github.com/Azure/go-autorest/autorest/validation/error.go diff --git a/azurerm/config.go b/azurerm/config.go index 042ec140a4e7..590f0a9b8ccd 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -18,12 +18,12 @@ import ( "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-02-01-preview/containerinstance" "github.com/Azure/azure-sdk-for-go/services/containerregistry/mgmt/2017-10-01/containerregistry" "github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2017-09-30/containerservice" - "github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices" "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2015-04-08/documentdb" "github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2016-04-01/dns" "github.com/Azure/azure-sdk-for-go/services/eventgrid/mgmt/2017-09-15-preview/eventgrid" "github.com/Azure/azure-sdk-for-go/services/eventhub/mgmt/2017-04-01/eventhub" "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" + "github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices" keyVault "github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault" "github.com/Azure/azure-sdk-for-go/services/keyvault/mgmt/2016-10-01/keyvault" "github.com/Azure/azure-sdk-for-go/services/monitor/mgmt/2017-05-01-preview/insights" @@ -113,7 +113,7 @@ type ArmClient struct { vmClient compute.VirtualMachinesClient // Devices - iothubResourceClient iothub.ResourceClient + iothubResourceClient devices.IotHubResourceClient // Databases mysqlConfigurationsClient mysql.ConfigurationsClient @@ -590,12 +590,12 @@ func (c *ArmClient) registerDatabases(endpoint, subscriptionId string, auth auto c.sqlServersClient = sqlSrvClient } -func (c *ArmClient) registerDeviceClienrs(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { - ihrc := iothub.NewResourceClientWithBaseURI(endpoint, c.SubscriptionID) - setUserAgent(&ihrc.Client) - ihrc.Authorizer = auth - ihrc.Sender = autorest.CreateSender(withRequestLogging()) - client.iothubResourceClient = ihrc +func (c *ArmClient) registerDeviceClients(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { + ihrc := devices.NewIotHubResourceClientWithBaseURI(endpoint, subscriptionId) + setUserAgent(&ihrc.Client) + ihrc.Authorizer = auth + ihrc.Sender = autorest.CreateSender(withRequestLogging()) + c.iothubResourceClient = ihrc } func (c *ArmClient) registerDNSClients(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { diff --git a/azurerm/provider.go b/azurerm/provider.go index b3458ae279dd..af41858624a5 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -122,7 +122,7 @@ func Provider() terraform.ResourceProvider { "azurerm_express_route_circuit": resourceArmExpressRouteCircuit(), "azurerm_function_app": resourceArmFunctionApp(), "azurerm_image": resourceArmImage(), - "azurerm_iothub": resourceArmIotHub(), + "azurerm_iothub": resourceArmIotHub(), "azurerm_key_vault": resourceArmKeyVault(), "azurerm_key_vault_certificate": resourceArmKeyVaultCertificate(), "azurerm_key_vault_key": resourceArmKeyVaultKey(), diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/certificates.go b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/certificates.go index d3186732ac50..5067b3021d4a 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/certificates.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/certificates.go @@ -490,4 +490,4 @@ func (client CertificatesClient) VerifyResponder(resp *http.Response) (result Ce autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return -} \ No newline at end of file +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/client.go index 3141f13dcf60..e57aac2e56b1 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/client.go @@ -48,4 +48,4 @@ func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { BaseURI: baseURI, SubscriptionID: subscriptionID, } -} \ No newline at end of file +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/iothubresource.go b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/iothubresource.go index 1dd5dce76fa8..300c05df7e92 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/iothubresource.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/iothubresource.go @@ -1589,4 +1589,4 @@ func (client IotHubResourceClient) listKeysNextResults(lastResults SharedAccessS func (client IotHubResourceClient) ListKeysComplete(ctx context.Context, resourceGroupName string, resourceName string) (result SharedAccessSignatureAuthorizationRuleListResultIterator, err error) { result.page, err = client.ListKeys(ctx, resourceGroupName, resourceName) return -} \ No newline at end of file +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/models.go index 5412c0b729ef..12be324f1a5b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/models.go @@ -1627,4 +1627,4 @@ type StorageEndpointProperties struct { ConnectionString *string `json:"connectionString,omitempty"` // ContainerName - The name of the root container where you upload files. The container need not exist but should be creatable using the connectionString specified. ContainerName *string `json:"containerName,omitempty"` -} \ No newline at end of file +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/operations.go index 1e12af66eb1f..6419b6e4a385 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/operations.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/operations.go @@ -123,4 +123,4 @@ func (client OperationsClient) listNextResults(lastResults OperationListResult) func (client OperationsClient) ListComplete(ctx context.Context) (result OperationListResultIterator, err error) { result.page, err = client.List(ctx) return -} \ No newline at end of file +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/version.go index b8bc096b8be2..d03b1f2e8ac9 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices/version.go @@ -27,4 +27,4 @@ func UserAgent() string { // Version returns the semantic version (see http://semver.org) of the client. func Version() string { return version.Number -} \ No newline at end of file +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/version/version.go b/vendor/github.com/Azure/azure-sdk-for-go/version/version.go new file mode 100644 index 000000000000..477d6ab7e087 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/version/version.go @@ -0,0 +1,21 @@ +package version + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +// Number contains the semantic version of this SDK. +const Number = "v14.1.1" diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go index f90699f6cc38..a18b61041654 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go @@ -39,7 +39,7 @@ const ( operationSucceeded string = "Succeeded" ) -var pollingCodes = [...]int{http.StatusAccepted, http.StatusCreated, http.StatusOK} +var pollingCodes = [...]int{http.StatusNoContent, http.StatusAccepted, http.StatusCreated, http.StatusOK} // Future provides a mechanism to access the status and results of an asynchronous request. // Since futures are stateful they should be passed by value to avoid race conditions. @@ -78,13 +78,39 @@ func (f *Future) Done(sender autorest.Sender) (bool, error) { if f.ps.hasTerminated() { return true, f.errorInfo() } - resp, err := sender.Do(f.req) f.resp = resp - if err != nil || !autorest.ResponseHasStatusCode(resp, pollingCodes[:]...) { + if err != nil { return false, err } + if !autorest.ResponseHasStatusCode(resp, pollingCodes[:]...) { + // check response body for error content + if resp.Body != nil { + type respErr struct { + ServiceError ServiceError `json:"error"` + } + re := respErr{} + + defer resp.Body.Close() + b, err := ioutil.ReadAll(resp.Body) + if err != nil { + return false, err + } + err = json.Unmarshal(b, &re) + if err != nil { + return false, err + } + return false, re.ServiceError + } + + // try to return something meaningful + return false, ServiceError{ + Code: fmt.Sprintf("%v", resp.StatusCode), + Message: resp.Status, + } + } + err = updatePollingState(resp, &f.ps) if err != nil { return false, err @@ -185,6 +211,12 @@ func (f *Future) UnmarshalJSON(data []byte) error { return err } +// PollingURL returns the URL used for retrieving the status of the long-running operation. +// For LROs that use the Location header the final URL value is used to retrieve the result. +func (f Future) PollingURL() string { + return f.ps.URI +} + // DoPollForAsynchronous returns a SendDecorator that polls if the http.Response is for an Azure // long-running operation. It will delay between requests for the duration specified in the // RetryAfter header or, if the header is absent, the passed delay. Polling may be canceled by @@ -300,7 +332,9 @@ func (ps provisioningStatus) hasTerminated() bool { } func (ps provisioningStatus) hasProvisioningError() bool { - return ps.ProvisioningError != ServiceError{} + // code and message are required fields so only check them + return len(ps.ProvisioningError.Code) > 0 || + len(ps.ProvisioningError.Message) > 0 } // PollingMethodType defines a type used for enumerating polling mechanisms. @@ -321,8 +355,7 @@ type pollingState struct { PollingMethod PollingMethodType `json:"pollingMethod"` URI string `json:"uri"` State string `json:"state"` - Code string `json:"code"` - Message string `json:"message"` + ServiceError *ServiceError `json:"error,omitempty"` } func (ps pollingState) hasSucceeded() bool { @@ -338,7 +371,11 @@ func (ps pollingState) hasFailed() bool { } func (ps pollingState) Error() string { - return fmt.Sprintf("Long running operation terminated with status '%s': Code=%q Message=%q", ps.State, ps.Code, ps.Message) + s := fmt.Sprintf("Long running operation terminated with status '%s'", ps.State) + if ps.ServiceError != nil { + s = fmt.Sprintf("%s: %+v", s, *ps.ServiceError) + } + return s } // updatePollingState maps the operation status -- retrieved from either a provisioningState @@ -430,18 +467,14 @@ func updatePollingState(resp *http.Response, ps *pollingState) error { // -- Response // -- Otherwise, Unknown if ps.hasFailed() { - if ps.PollingMethod == PollingAsyncOperation { - or := pt.(*operationResource) - ps.Code = or.OperationError.Code - ps.Message = or.OperationError.Message + if or, ok := pt.(*operationResource); ok { + ps.ServiceError = &or.OperationError + } else if p, ok := pt.(*provisioningStatus); ok && p.hasProvisioningError() { + ps.ServiceError = &p.ProvisioningError } else { - p := pt.(*provisioningStatus) - if p.hasProvisioningError() { - ps.Code = p.ProvisioningError.Code - ps.Message = p.ProvisioningError.Message - } else { - ps.Code = "Unknown" - ps.Message = "None" + ps.ServiceError = &ServiceError{ + Code: "Unknown", + Message: "None", } } } @@ -458,3 +491,21 @@ func newPollingRequest(ps pollingState) (*http.Request, error) { return reqPoll, nil } + +// AsyncOpIncompleteError is the type that's returned from a future that has not completed. +type AsyncOpIncompleteError struct { + // FutureType is the name of the type composed of a azure.Future. + FutureType string +} + +// Error returns an error message including the originating type name of the error. +func (e AsyncOpIncompleteError) Error() string { + return fmt.Sprintf("%s: asynchronous operation has not completed", e.FutureType) +} + +// NewAsyncOpIncompleteError creates a new AsyncOpIncompleteError with the specified parameters. +func NewAsyncOpIncompleteError(futureType string) AsyncOpIncompleteError { + return AsyncOpIncompleteError{ + FutureType: futureType, + } +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go b/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go index fa18356476b9..2383b2d74428 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go @@ -1,8 +1,5 @@ -/* -Package azure provides Azure-specific implementations used with AutoRest. - -See the included examples for more detail. -*/ +// Package azure provides Azure-specific implementations used with AutoRest. +// See the included examples for more detail. package azure // Copyright 2017 Microsoft Corporation @@ -43,21 +40,88 @@ const ( ) // ServiceError encapsulates the error response from an Azure service. +// It adhears to the OData v4 specification for error responses. type ServiceError struct { - Code string `json:"code"` - Message string `json:"message"` - Details *[]interface{} `json:"details"` + Code string `json:"code"` + Message string `json:"message"` + Target *string `json:"target"` + Details []map[string]interface{} `json:"details"` + InnerError map[string]interface{} `json:"innererror"` } func (se ServiceError) Error() string { + result := fmt.Sprintf("Code=%q Message=%q", se.Code, se.Message) + + if se.Target != nil { + result += fmt.Sprintf(" Target=%q", *se.Target) + } + if se.Details != nil { - d, err := json.Marshal(*(se.Details)) + d, err := json.Marshal(se.Details) if err != nil { - return fmt.Sprintf("Code=%q Message=%q Details=%v", se.Code, se.Message, *se.Details) + result += fmt.Sprintf(" Details=%v", se.Details) } - return fmt.Sprintf("Code=%q Message=%q Details=%v", se.Code, se.Message, string(d)) + result += fmt.Sprintf(" Details=%v", string(d)) } - return fmt.Sprintf("Code=%q Message=%q", se.Code, se.Message) + + if se.InnerError != nil { + d, err := json.Marshal(se.InnerError) + if err != nil { + result += fmt.Sprintf(" InnerError=%v", se.InnerError) + } + result += fmt.Sprintf(" InnerError=%v", string(d)) + } + + return result +} + +// UnmarshalJSON implements the json.Unmarshaler interface for the ServiceError type. +func (se *ServiceError) UnmarshalJSON(b []byte) error { + // per the OData v4 spec the details field must be an array of JSON objects. + // unfortunately not all services adhear to the spec and just return a single + // object instead of an array with one object. so we have to perform some + // shenanigans to accommodate both cases. + // http://docs.oasis-open.org/odata/odata-json-format/v4.0/os/odata-json-format-v4.0-os.html#_Toc372793091 + + type serviceError1 struct { + Code string `json:"code"` + Message string `json:"message"` + Target *string `json:"target"` + Details []map[string]interface{} `json:"details"` + InnerError map[string]interface{} `json:"innererror"` + } + + type serviceError2 struct { + Code string `json:"code"` + Message string `json:"message"` + Target *string `json:"target"` + Details map[string]interface{} `json:"details"` + InnerError map[string]interface{} `json:"innererror"` + } + + se1 := serviceError1{} + err := json.Unmarshal(b, &se1) + if err == nil { + se.populate(se1.Code, se1.Message, se1.Target, se1.Details, se1.InnerError) + return nil + } + + se2 := serviceError2{} + err = json.Unmarshal(b, &se2) + if err == nil { + se.populate(se2.Code, se2.Message, se2.Target, nil, se2.InnerError) + se.Details = append(se.Details, se2.Details) + return nil + } + return err +} + +func (se *ServiceError) populate(code, message string, target *string, details []map[string]interface{}, inner map[string]interface{}) { + se.Code = code + se.Message = message + se.Target = target + se.Details = details + se.InnerError = inner } // RequestError describes an error response returned by Azure service. diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go index efdab6a110cf..0916b14f34ae 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go @@ -44,6 +44,7 @@ type Environment struct { GalleryEndpoint string `json:"galleryEndpoint"` KeyVaultEndpoint string `json:"keyVaultEndpoint"` GraphEndpoint string `json:"graphEndpoint"` + ServiceBusEndpoint string `json:"serviceBusEndpoint"` StorageEndpointSuffix string `json:"storageEndpointSuffix"` SQLDatabaseDNSSuffix string `json:"sqlDatabaseDNSSuffix"` TrafficManagerDNSSuffix string `json:"trafficManagerDNSSuffix"` @@ -66,11 +67,12 @@ var ( GalleryEndpoint: "https://gallery.azure.com/", KeyVaultEndpoint: "https://vault.azure.net/", GraphEndpoint: "https://graph.windows.net/", + ServiceBusEndpoint: "https://servicebus.windows.net/", StorageEndpointSuffix: "core.windows.net", SQLDatabaseDNSSuffix: "database.windows.net", TrafficManagerDNSSuffix: "trafficmanager.net", KeyVaultDNSSuffix: "vault.azure.net", - ServiceBusEndpointSuffix: "servicebus.azure.com", + ServiceBusEndpointSuffix: "servicebus.windows.net", ServiceManagementVMDNSSuffix: "cloudapp.net", ResourceManagerVMDNSSuffix: "cloudapp.azure.com", ContainerRegistryDNSSuffix: "azurecr.io", @@ -83,10 +85,11 @@ var ( PublishSettingsURL: "https://manage.windowsazure.us/publishsettings/index", ServiceManagementEndpoint: "https://management.core.usgovcloudapi.net/", ResourceManagerEndpoint: "https://management.usgovcloudapi.net/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.com/", + ActiveDirectoryEndpoint: "https://login.microsoftonline.us/", GalleryEndpoint: "https://gallery.usgovcloudapi.net/", KeyVaultEndpoint: "https://vault.usgovcloudapi.net/", - GraphEndpoint: "https://graph.usgovcloudapi.net/", + GraphEndpoint: "https://graph.windows.net/", + ServiceBusEndpoint: "https://servicebus.usgovcloudapi.net/", StorageEndpointSuffix: "core.usgovcloudapi.net", SQLDatabaseDNSSuffix: "database.usgovcloudapi.net", TrafficManagerDNSSuffix: "usgovtrafficmanager.net", @@ -108,11 +111,12 @@ var ( GalleryEndpoint: "https://gallery.chinacloudapi.cn/", KeyVaultEndpoint: "https://vault.azure.cn/", GraphEndpoint: "https://graph.chinacloudapi.cn/", + ServiceBusEndpoint: "https://servicebus.chinacloudapi.cn/", StorageEndpointSuffix: "core.chinacloudapi.cn", SQLDatabaseDNSSuffix: "database.chinacloudapi.cn", TrafficManagerDNSSuffix: "trafficmanager.cn", KeyVaultDNSSuffix: "vault.azure.cn", - ServiceBusEndpointSuffix: "servicebus.chinacloudapi.net", + ServiceBusEndpointSuffix: "servicebus.chinacloudapi.cn", ServiceManagementVMDNSSuffix: "chinacloudapp.cn", ResourceManagerVMDNSSuffix: "cloudapp.azure.cn", ContainerRegistryDNSSuffix: "azurecr.io", @@ -129,6 +133,7 @@ var ( GalleryEndpoint: "https://gallery.cloudapi.de/", KeyVaultEndpoint: "https://vault.microsoftazure.de/", GraphEndpoint: "https://graph.cloudapi.de/", + ServiceBusEndpoint: "https://servicebus.cloudapi.de/", StorageEndpointSuffix: "core.cloudapi.de", SQLDatabaseDNSSuffix: "database.cloudapi.de", TrafficManagerDNSSuffix: "azuretrafficmanager.de", diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go b/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go index b6b95d6fdbcb..2c88d60ba6c6 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go @@ -70,11 +70,8 @@ func DoRetryWithRegistration(client autorest.Client) autorest.SendDecorator { } func getProvider(re RequestError) (string, error) { - if re.ServiceError != nil { - if re.ServiceError.Details != nil && len(*re.ServiceError.Details) > 0 { - detail := (*re.ServiceError.Details)[0].(map[string]interface{}) - return detail["target"].(string), nil - } + if re.ServiceError != nil && len(re.ServiceError.Details) > 0 { + return re.ServiceError.Details[0]["target"].(string), nil } return "", errors.New("provider was not found in the response") } diff --git a/vendor/github.com/Azure/go-autorest/autorest/validation/error.go b/vendor/github.com/Azure/go-autorest/autorest/validation/error.go new file mode 100644 index 000000000000..fed156dbf6e6 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/validation/error.go @@ -0,0 +1,48 @@ +package validation + +// Copyright 2017 Microsoft Corporation +// +// 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. + +import ( + "fmt" +) + +// Error is the type that's returned when the validation of an APIs arguments constraints fails. +type Error struct { + // PackageType is the package type of the object emitting the error. For types, the value + // matches that produced the the '%T' format specifier of the fmt package. For other elements, + // such as functions, it is just the package name (e.g., "autorest"). + PackageType string + + // Method is the name of the method raising the error. + Method string + + // Message is the error message. + Message string +} + +// Error returns a string containing the details of the validation failure. +func (e Error) Error() string { + return fmt.Sprintf("%s#%s: Invalid input: %s", e.PackageType, e.Method, e.Message) +} + +// NewError creates a new Error object with the specified parameters. +// message is treated as a format string to which the optional args apply. +func NewError(packageType string, method string, message string, args ...interface{}) Error { + return Error{ + PackageType: packageType, + Method: method, + Message: fmt.Sprintf(message, args...), + } +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go b/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go index 3fe62c93056d..d886e0b3fbfc 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go +++ b/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go @@ -390,6 +390,8 @@ func createError(x reflect.Value, v Constraint, err string) error { // NewErrorWithValidationError appends package type and method name in // validation error. +// +// Deprecated: Please use validation.NewError() instead. func NewErrorWithValidationError(err error, packageType, method string) error { - return fmt.Errorf("%s#%s: Invalid input: %v", packageType, method, err) + return NewError(packageType, method, err.Error()) } diff --git a/vendor/vendor.json b/vendor/vendor.json index 758c2183d77f..fde68c1b5402 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -1,6 +1,6 @@ { "comment": "", - "ignore": "test github.com/hashicorp/terraform/backend", + "ignore": "test", "package": [ { "checksumSHA1": "04RpBRvxCFIrlZr4QGlWxEYu5jk=", @@ -106,6 +106,12 @@ "version": "v12.5.0-beta", "versionExact": "v12.5.0-beta" }, + { + "checksumSHA1": "l4BaDOG5showWuLiGBjsY4eVhtk=", + "path": "github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices", + "revision": "1e334c402ea1460704b0263e5d188f28ad946ce1", + "revisionTime": "2018-02-16T17:41:56Z" + }, { "checksumSHA1": "Qyvr+VKOVBA9x/PYyaLBNaPD6CA=", "path": "github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault", @@ -258,6 +264,12 @@ "version": "v12.5.0-beta", "versionExact": "v12.5.0-beta" }, + { + "checksumSHA1": "0f2bCAIQjO9op810x5LnuZnAmM0=", + "path": "github.com/Azure/azure-sdk-for-go/version", + "revision": "1e334c402ea1460704b0263e5d188f28ad946ce1", + "revisionTime": "2018-02-16T17:41:56Z" + }, { "checksumSHA1": "RzIYmvG1ReOud+kafFsZTDIZSK0=", "comment": "v9.7.0", @@ -277,11 +289,11 @@ "versionExact": "v9.7.0" }, { - "checksumSHA1": "PwTnRhiCu8p2D1M2nsM0ADL4FM0=", + "checksumSHA1": "KFHzaLA4zo34W0FJ5ah/1WBbB9Q=", "comment": "v9.7.0", "path": "github.com/Azure/go-autorest/autorest/azure", - "revision": "8c58b4788dedd95779efe0ac2055bb6a1b9b8e01", - "revisionTime": "2018-01-06T16:29:27Z", + "revision": "1e3943ee722538420f21945f4bc820347abe433d", + "revisionTime": "2018-02-15T17:42:55Z", "version": "v9.7.0", "versionExact": "v9.7.0" }, @@ -313,11 +325,11 @@ "versionExact": "v9.7.0" }, { - "checksumSHA1": "HfqZyKllcHQDvTwgCaYL1jUPmW0=", + "checksumSHA1": "5UH4IFIB/98iowPCzzVs4M4MXiQ=", "comment": "v9.7.0", "path": "github.com/Azure/go-autorest/autorest/validation", - "revision": "8c58b4788dedd95779efe0ac2055bb6a1b9b8e01", - "revisionTime": "2018-01-06T16:29:27Z", + "revision": "1e3943ee722538420f21945f4bc820347abe433d", + "revisionTime": "2018-02-15T17:42:55Z", "version": "v9.7.0", "versionExact": "v9.7.0" }, From 57a22e3090d63af150cedc3a7c6b7b41ce68bb9a Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Tue, 27 Feb 2018 15:50:34 -0600 Subject: [PATCH 52/69] Modify IoTHub resource for updated SDK --- azurerm/provider_test.go | 3 - .../resource_arm_iothub_resource_provider.go | 73 ++++++++++++------- ...ource_arm_iothub_resource_provider_test.go | 21 +++--- 3 files changed, 54 insertions(+), 43 deletions(-) diff --git a/azurerm/provider_test.go b/azurerm/provider_test.go index 72493f4529b5..0593d093a286 100644 --- a/azurerm/provider_test.go +++ b/azurerm/provider_test.go @@ -36,11 +36,8 @@ func TestProvider_impl(t *testing.T) { func testAccPreCheck(t *testing.T) { variables := []string{ "ARM_SUBSCRIPTION_ID", - "ARM_CLIENT_ID", - "ARM_CLIENT_SECRET", "ARM_TENANT_ID", "ARM_TEST_LOCATION", - "ARM_TEST_LOCATION_ALT", } for _, variable := range variables { diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 45a931f79af6..c4e1753d2306 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -2,6 +2,7 @@ package azurerm import ( "errors" + "fmt" "github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices" "github.com/hashicorp/terraform/helper/schema" @@ -38,10 +39,10 @@ func resourceArmIotHub() *schema.Resource { Type: schema.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(iothub.F1), - string(iothub.S1), - string(iothub.S2), - string(iothub.S3), + string(devices.F1), + string(devices.S1), + string(devices.S2), + string(devices.S3), }, true), }, @@ -49,8 +50,8 @@ func resourceArmIotHub() *schema.Resource { Type: schema.TypeString, Required: true, ValidateFunc: validation.StringInSlice([]string{ - string(iothub.Free), - string(iothub.Standard), + string(devices.Free), + string(devices.Standard), }, true), }, @@ -112,11 +113,12 @@ func resourceArmIotHubCreateAndUpdate(d *schema.ResourceData, meta interface{}) armClient := meta.(*ArmClient) iothubClient := armClient.iothubResourceClient + ctx := armClient.StopContext rg := d.Get("resource_group_name").(string) name := d.Get("name").(string) - res, err := iothubClient.CheckNameAvailability(iothub.OperationInputs{ + res, err := iothubClient.CheckNameAvailability(ctx, devices.OperationInputs{ Name: &name, }) @@ -133,7 +135,7 @@ func resourceArmIotHubCreateAndUpdate(d *schema.ResourceData, meta interface{}) subscriptionID := armClient.subscriptionId skuInfo := expandAzureRmIotHubSku(d) - desc := iothub.Description{ + desc := devices.IotHubDescription{ Resourcegroup: &rg, Name: &name, Location: &location, @@ -143,24 +145,28 @@ func resourceArmIotHubCreateAndUpdate(d *schema.ResourceData, meta interface{}) if tagsI, ok := d.GetOk("tags"); ok { tags := tagsI.(map[string]interface{}) - desc.Tags = expandTags(tags) + desc.Tags = *expandTags(tags) } + match := "" + if etagI, ok := d.GetOk("etag"); ok { etag := etagI.(string) desc.Etag = &etag + match = etag } - cancel := make(chan struct{}) - - _, errChan := iothubClient.CreateOrUpdate(rg, name, desc, cancel) - err = <-errChan - + future, err := iothubClient.CreateOrUpdate(ctx, rg, name, desc, match) if err != nil { return err } - desc, err = iothubClient.Get(rg, name) + err = future.WaitForCompletion(ctx, iothubClient.Client) + if err != nil { + return fmt.Errorf("Error creating or updating IotHub %q (Resource Group %q): %+v", name, rg, err) + } + + desc, err = iothubClient.Get(ctx, rg, name) if err != nil { return err } @@ -170,20 +176,23 @@ func resourceArmIotHubCreateAndUpdate(d *schema.ResourceData, meta interface{}) } -func expandAzureRmIotHubSku(d *schema.ResourceData) iothub.SkuInfo { +func expandAzureRmIotHubSku(d *schema.ResourceData) devices.IotHubSkuInfo { skuList := d.Get("sku").([]interface{}) skuMap := skuList[0].(map[string]interface{}) cap := int64(skuMap["capacity"].(int)) - return iothub.SkuInfo{ - Name: iothub.Sku(skuMap["name"].(string)), - Tier: iothub.SkuTier(skuMap["tier"].(string)), + return devices.IotHubSkuInfo{ + Name: devices.IotHubSku(skuMap["name"].(string)), + Tier: devices.IotHubSkuTier(skuMap["tier"].(string)), Capacity: &cap, } } func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { + armClient := meta.(*ArmClient) + iothubClient := armClient.iothubResourceClient + ctx := armClient.StopContext id, err := parseAzureResourceID(d.Id()) @@ -191,10 +200,8 @@ func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { return err } - armClient := meta.(*ArmClient) - iothubClient := armClient.iothubResourceClient iothubName := id.Path["IotHubs"] - desc, err := iothubClient.Get(id.ResourceGroup, iothubName) + desc, err := iothubClient.Get(ctx, id.ResourceGroup, iothubName) if err != nil { return err @@ -202,10 +209,11 @@ func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { properties := desc.Properties - keysResp, err := iothubClient.ListKeys(id.ResourceGroup, iothubName) + keysResp, err := iothubClient.ListKeys(ctx, id.ResourceGroup, iothubName) + keyList := keysResp.Response() var keys []map[string]interface{} - for _, key := range *keysResp.Value { + for _, key := range *keyList.Value { keyMap := make(map[string]interface{}) keyMap["key_name"] = *key.KeyName keyMap["primary_key"] = *key.PrimaryKey @@ -222,7 +230,7 @@ func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { d.Set("hostname", *properties.HostName) d.Set("etag", *desc.Etag) d.Set("type", *desc.Type) - flattenAndSetTags(d, desc.Tags) + flattenAndSetTags(d, &desc.Tags) return nil } @@ -237,8 +245,17 @@ func resourceArmIotHubDelete(d *schema.ResourceData, meta interface{}) error { armClient := meta.(*ArmClient) iothubClient := armClient.iothubResourceClient + ctx := armClient.StopContext + + future, err := iothubClient.Delete(ctx, id.ResourceGroup, id.Path["IotHubs"]) + if err != nil { + return err + } + + status := future.Status() + if status == "unkown" { + return fmt.Errorf("Error Waiting for the deletion of IoTHub %q (Resource Group %q): %+v", id.Path["IotHubs"], id.ResourceGroup, err) + } - _, errChan := iothubClient.Delete(id.ResourceGroup, id.Path["IotHubs"], make(chan struct{})) - err = <-errChan - return err + return nil } diff --git a/azurerm/resource_arm_iothub_resource_provider_test.go b/azurerm/resource_arm_iothub_resource_provider_test.go index 1d5fbdde7a76..e7c213b718c2 100644 --- a/azurerm/resource_arm_iothub_resource_provider_test.go +++ b/azurerm/resource_arm_iothub_resource_provider_test.go @@ -12,7 +12,6 @@ import ( func TestAccAzureRMIotHub_basicStandard(t *testing.T) { name := acctest.RandString(6) - rgname := acctest.RandString(5) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -20,7 +19,7 @@ func TestAccAzureRMIotHub_basicStandard(t *testing.T) { CheckDestroy: testCheckAzureRMIotHubDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMIotHub_basicStandard(name, rgname), + Config: testAccAzureRMIotHub_basicStandard(name), Check: resource.ComposeTestCheckFunc( testCheckAzureRMIotHubExists("azurerm_iothub.test"), ), @@ -31,6 +30,7 @@ func TestAccAzureRMIotHub_basicStandard(t *testing.T) { } func testCheckAzureRMIotHubDestroy(s *terraform.State) error { + ctx := testAccProvider.Meta().(*ArmClient).StopContext conn := testAccProvider.Meta().(*ArmClient).expressRouteCircuitClient @@ -42,7 +42,7 @@ func testCheckAzureRMIotHubDestroy(s *terraform.State) error { name := rs.Primary.Attributes["name"] resourceGroup := rs.Primary.Attributes["resource_group_name"] - resp, err := conn.Get(resourceGroup, name) + resp, err := conn.Get(ctx, resourceGroup, name) if err != nil { return nil @@ -56,6 +56,8 @@ func testCheckAzureRMIotHubDestroy(s *terraform.State) error { } func testCheckAzureRMIotHubExists(name string) resource.TestCheckFunc { return func(s *terraform.State) error { + ctx := testAccProvider.Meta().(*ArmClient).StopContext + rs, ok := s.RootModule().Resources[name] if !ok { return fmt.Errorf("Not found: %s", name) @@ -68,7 +70,7 @@ func testCheckAzureRMIotHubExists(name string) resource.TestCheckFunc { conn := testAccProvider.Meta().(*ArmClient).iothubResourceClient - resp, err := conn.Get(resourceGroup, iothubName) + resp, err := conn.Get(ctx, resourceGroup, iothubName) if err != nil { if resp.StatusCode == http.StatusNotFound { return fmt.Errorf("Bad: IotHub %q (resource group: %q) does not exist", iothubName, resourceGroup) @@ -82,16 +84,11 @@ func testCheckAzureRMIotHubExists(name string) resource.TestCheckFunc { } } -func testAccAzureRMIotHub_basicStandard(name, rgname string) string { +func testAccAzureRMIotHub_basicStandard(name string) string { return fmt.Sprintf(` -resource "azurerm_resource_group" "foo" { - name = "acctestRG-%s" - location = "East Us" -} - resource "azurerm_iothub" "test" { name = "%s" - resource_group_name = "${azurerm_resource_group.foo.name}" + resource_group_name = "shelley.bess" location = "eastus" sku { name = "S1" @@ -103,5 +100,5 @@ resource "azurerm_iothub" "test" { "purpose" = "testing" } } -`, rgname, name) +`, name) } From e96d5ca84146f02224096138930e141738078b17 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Tue, 27 Feb 2018 16:10:00 -0600 Subject: [PATCH 53/69] Formatting --- azurerm/provider.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/provider.go b/azurerm/provider.go index 7ec940b39794..38b0800a96e9 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -122,7 +122,7 @@ func Provider() terraform.ResourceProvider { "azurerm_express_route_circuit": resourceArmExpressRouteCircuit(), "azurerm_function_app": resourceArmFunctionApp(), "azurerm_image": resourceArmImage(), - "azurerm_iothub": resourceArmIotHub(), + "azurerm_iothub": resourceArmIotHub(), "azurerm_key_vault": resourceArmKeyVault(), "azurerm_key_vault_certificate": resourceArmKeyVaultCertificate(), "azurerm_key_vault_key": resourceArmKeyVaultKey(), From daa1ba8179296f7936d1a2cac7316e8b9eb5a520 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Tue, 27 Feb 2018 16:28:30 -0600 Subject: [PATCH 54/69] Test changes --- azurerm/provider_test.go | 3 +++ .../resource_arm_iothub_resource_provider_test.go | 14 ++++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/azurerm/provider_test.go b/azurerm/provider_test.go index 0593d093a286..4c8fc5ff3d8c 100644 --- a/azurerm/provider_test.go +++ b/azurerm/provider_test.go @@ -35,9 +35,12 @@ func TestProvider_impl(t *testing.T) { func testAccPreCheck(t *testing.T) { variables := []string{ + "ARM_CLIENT_ID", + "ARM_CLIENT_SECRET", "ARM_SUBSCRIPTION_ID", "ARM_TENANT_ID", "ARM_TEST_LOCATION", + "ARM_TEST_LOCATION_ALT", } for _, variable := range variables { diff --git a/azurerm/resource_arm_iothub_resource_provider_test.go b/azurerm/resource_arm_iothub_resource_provider_test.go index e7c213b718c2..ed6de986f59d 100644 --- a/azurerm/resource_arm_iothub_resource_provider_test.go +++ b/azurerm/resource_arm_iothub_resource_provider_test.go @@ -12,6 +12,7 @@ import ( func TestAccAzureRMIotHub_basicStandard(t *testing.T) { name := acctest.RandString(6) + rgname := acctest.RandString(5) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -19,7 +20,7 @@ func TestAccAzureRMIotHub_basicStandard(t *testing.T) { CheckDestroy: testCheckAzureRMIotHubDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMIotHub_basicStandard(name), + Config: testAccAzureRMIotHub_basicStandard(name, rgname), Check: resource.ComposeTestCheckFunc( testCheckAzureRMIotHubExists("azurerm_iothub.test"), ), @@ -84,11 +85,16 @@ func testCheckAzureRMIotHubExists(name string) resource.TestCheckFunc { } } -func testAccAzureRMIotHub_basicStandard(name string) string { +func testAccAzureRMIotHub_basicStandard(name, rgname string) string { return fmt.Sprintf(` +resource "azurerm_resource_group" "foo" { + name = "acctestRG-%s" + location = "East Us" +} + resource "azurerm_iothub" "test" { name = "%s" - resource_group_name = "shelley.bess" + resource_group_name = "${azurerm_resource_group.foo.name}" location = "eastus" sku { name = "S1" @@ -100,5 +106,5 @@ resource "azurerm_iothub" "test" { "purpose" = "testing" } } -`, name) +`, rgname, name) } From a9076366325cba6190e8f31d0c8b35c552fb0611 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 28 Feb 2018 14:22:17 -0600 Subject: [PATCH 55/69] Error details and schema updates --- .../resource_arm_iothub_resource_provider.go | 34 +++++++++++++------ 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index c4e1753d2306..3d0a4f24e48e 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -7,6 +7,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/iothub/mgmt/2017-07-01/devices" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response" ) func resourceArmIotHub() *schema.Resource { @@ -36,8 +37,9 @@ func resourceArmIotHub() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, ValidateFunc: validation.StringInSlice([]string{ string(devices.F1), string(devices.S1), @@ -47,8 +49,9 @@ func resourceArmIotHub() *schema.Resource { }, "tier": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, ValidateFunc: validation.StringInSlice([]string{ string(devices.Free), string(devices.Standard), @@ -181,9 +184,12 @@ func expandAzureRmIotHubSku(d *schema.ResourceData) devices.IotHubSkuInfo { skuMap := skuList[0].(map[string]interface{}) cap := int64(skuMap["capacity"].(int)) + name := skuMap["name"].(string) + tier := skuMap["tier"].(string) + return devices.IotHubSkuInfo{ - Name: devices.IotHubSku(skuMap["name"].(string)), - Tier: devices.IotHubSkuTier(skuMap["tier"].(string)), + Name: devices.IotHubSku(name), + Tier: devices.IotHubSkuTier(tier), Capacity: &cap, } @@ -223,7 +229,7 @@ func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { } if err != nil { - return err + return fmt.Errorf("Error flattening `shared_access_policy` in IoTHub %q: %+v", iothubName, err) } d.Set("shared_access_policy", keys) @@ -247,14 +253,20 @@ func resourceArmIotHubDelete(d *schema.ResourceData, meta interface{}) error { iothubClient := armClient.iothubResourceClient ctx := armClient.StopContext - future, err := iothubClient.Delete(ctx, id.ResourceGroup, id.Path["IotHubs"]) + iotHubName := id.Path["IotHubs"] + + future, err := iothubClient.Delete(ctx, id.ResourceGroup, iotHubName) if err != nil { return err } - status := future.Status() - if status == "unkown" { - return fmt.Errorf("Error Waiting for the deletion of IoTHub %q (Resource Group %q): %+v", id.Path["IotHubs"], id.ResourceGroup, err) + err = future.WaitForCompletion(ctx, iothubClient.Client) + if err != nil { + if response.WasNotFound(future.Response()) { + return nil + } + + return fmt.Errorf("Error waiting for the deletion of IoTHub %q", iotHubName) } return nil From ffd3c56cbf97be72b7dd2ac487e58c3ff5793e07 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 28 Feb 2018 15:43:17 -0600 Subject: [PATCH 56/69] Resource now correctly updates. Removed Etag from Schema --- .../resource_arm_iothub_resource_provider.go | 29 +++++++------------ 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index 3d0a4f24e48e..b243592dd9a9 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -72,12 +72,6 @@ func resourceArmIotHub() *schema.Resource { Computed: true, }, - "etag": { - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - "hostname": { Type: schema.TypeString, Computed: true, @@ -121,6 +115,8 @@ func resourceArmIotHubCreateAndUpdate(d *schema.ResourceData, meta interface{}) rg := d.Get("resource_group_name").(string) name := d.Get("name").(string) + updateIoT := "" + res, err := iothubClient.CheckNameAvailability(ctx, devices.OperationInputs{ Name: &name, }) @@ -130,7 +126,11 @@ func resourceArmIotHubCreateAndUpdate(d *schema.ResourceData, meta interface{}) } if !*res.NameAvailable { - return errors.New(string(res.Reason)) + getETag, err := iothubClient.Get(ctx, rg, name) + if err != nil { + return errors.New(string(res.Reason)) + } + updateIoT = *getETag.Etag } location := d.Get("location").(string) @@ -151,15 +151,7 @@ func resourceArmIotHubCreateAndUpdate(d *schema.ResourceData, meta interface{}) desc.Tags = *expandTags(tags) } - match := "" - - if etagI, ok := d.GetOk("etag"); ok { - etag := etagI.(string) - desc.Etag = &etag - match = etag - } - - future, err := iothubClient.CreateOrUpdate(ctx, rg, name, desc, match) + future, err := iothubClient.CreateOrUpdate(ctx, rg, name, desc, updateIoT) if err != nil { return err } @@ -233,9 +225,8 @@ func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { } d.Set("shared_access_policy", keys) - d.Set("hostname", *properties.HostName) - d.Set("etag", *desc.Etag) - d.Set("type", *desc.Type) + d.Set("hostname", properties.HostName) + d.Set("type", desc.Type) flattenAndSetTags(d, &desc.Tags) return nil From 106c0de8ef52eb704e1ceb00ce660eb815bb24a8 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 28 Feb 2018 16:37:32 -0600 Subject: [PATCH 57/69] IoTHub doc update --- website/docs/r/iothub.html.markdown | 36 +++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/website/docs/r/iothub.html.markdown b/website/docs/r/iothub.html.markdown index 474a0087e3eb..a1fcf85da961 100644 --- a/website/docs/r/iothub.html.markdown +++ b/website/docs/r/iothub.html.markdown @@ -6,7 +6,7 @@ description: |- Creates a new IotHub resource --- -# azurerm\_iothub +# azurerm_iothub Creates a new IotHub @@ -22,7 +22,7 @@ resource "azurerm_resource_group" "test" { resource "azurerm_iothub" "test" { name = "test" resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" + location = "${azurerm_resource_group.test.location}" sku { name = "S1" tier = "Standard" @@ -47,10 +47,20 @@ The following arguments are supported: * `location` - (Required) Specifies the supported Azure location where the resource has to be createc. Changing this forces a new resource to be created. -* `sku` - (Required) Specifies the capacity and tier of the IotHub. +* `sku` - (Required) A `sku` block as defined below. * `tags` - (Optional) A mapping of tags to assign to the resource. +--- + +A `sku` block supports the following: + +* `name` - (Required) The name of the sku. Supports `F1`, `S1`, `S2`, and `S3`. + +* `tier` - (Required) The billing tier for the IoT Hub. `Free` or `Standard`. + +* `capacity` - (Required) The number of provisioned IoT Hub units. + ## Attributes Reference The following attributes are exported: @@ -61,6 +71,24 @@ The following attributes are exported: * `hostname` - The hostname of the IotHub Resource. -* `shared_access_policy` - The list of access policy which contain access keys and permissions. +* `shared_access_policy` - A list of `shared_access_policy` blocks as defined below. + +--- +A `shared access policy` block contains the following: +* `key_name` - The name of the shared access policy. + +* `primary_key` - The primary key. + +* `secondary_key` - The secondary key. + +* `permissions` - The permissions assigned to the shared access policy. + +## Import + +IoTHubs can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_iothub.hub1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.Devices/IotHubs/hub1 +``` From fabaef4e594325c12058b97c7791250278025245 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 28 Feb 2018 16:44:07 -0600 Subject: [PATCH 58/69] Devices alphabetized --- azurerm/provider.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azurerm/provider.go b/azurerm/provider.go index 38b0800a96e9..ce4ccb07f0b9 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -280,6 +280,7 @@ func determineAzureResourceProvidersToRegister(providerList []resources.Provider "Microsoft.ContainerService": {}, "Microsoft.DBforMySQL": {}, "Microsoft.DBforPostgreSQL": {}, + "Microsoft.Devices": {}, "Microsoft.DocumentDB": {}, "Microsoft.EventGrid": {}, "Microsoft.EventHub": {}, @@ -292,7 +293,6 @@ func determineAzureResourceProvidersToRegister(providerList []resources.Provider "Microsoft.ServiceBus": {}, "Microsoft.Sql": {}, "Microsoft.Storage": {}, - "Microsoft.Devices": {}, } // filter out any providers already registered From 16cac290c685bb9d548b189dca635fad0f3dfad7 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 28 Feb 2018 16:53:54 -0600 Subject: [PATCH 59/69] accTest changes --- ...esource_arm_iothub_resource_provider_test.go | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/azurerm/resource_arm_iothub_resource_provider_test.go b/azurerm/resource_arm_iothub_resource_provider_test.go index ed6de986f59d..1032906e853f 100644 --- a/azurerm/resource_arm_iothub_resource_provider_test.go +++ b/azurerm/resource_arm_iothub_resource_provider_test.go @@ -11,8 +11,7 @@ import ( ) func TestAccAzureRMIotHub_basicStandard(t *testing.T) { - name := acctest.RandString(6) - rgname := acctest.RandString(5) + rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -20,7 +19,7 @@ func TestAccAzureRMIotHub_basicStandard(t *testing.T) { CheckDestroy: testCheckAzureRMIotHubDestroy, Steps: []resource.TestStep{ { - Config: testAccAzureRMIotHub_basicStandard(name, rgname), + Config: testAccAzureRMIotHub_basicStandard(rInt, testLocation()), Check: resource.ComposeTestCheckFunc( testCheckAzureRMIotHubExists("azurerm_iothub.test"), ), @@ -85,17 +84,17 @@ func testCheckAzureRMIotHubExists(name string) resource.TestCheckFunc { } } -func testAccAzureRMIotHub_basicStandard(name, rgname string) string { +func testAccAzureRMIotHub_basicStandard(rInt int, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "foo" { - name = "acctestRG-%s" - location = "East Us" + name = "acctestRG-%d" + location = "%s" } resource "azurerm_iothub" "test" { - name = "%s" + name = "acctestIoTHub-%d" resource_group_name = "${azurerm_resource_group.foo.name}" - location = "eastus" + location = "${azurerm_resource_group.foo.location}" sku { name = "S1" tier = "Standard" @@ -106,5 +105,5 @@ resource "azurerm_iothub" "test" { "purpose" = "testing" } } -`, rgname, name) +`, rInt, location, rInt) } From 3e927a6d96d0c91b3dc132d9b9e83f4b1fc96650 Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 28 Feb 2018 17:35:45 -0600 Subject: [PATCH 60/69] IotHub import test --- azurerm/import_arm_iothub_test.go | 31 +++++++++++++++++++ ...ource_arm_iothub_resource_provider_test.go | 2 +- 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 azurerm/import_arm_iothub_test.go diff --git a/azurerm/import_arm_iothub_test.go b/azurerm/import_arm_iothub_test.go new file mode 100644 index 000000000000..5e8991b94602 --- /dev/null +++ b/azurerm/import_arm_iothub_test.go @@ -0,0 +1,31 @@ +package azurerm + +import ( + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccAzureRMIotHub_importBasic(t *testing.T) { + resourceName := "azurerm_iothub.test" + + ri := acctest.RandInt() + config := testAccAzureRMIotHub_basicStandard(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMSubnetDestroy, + Steps: []resource.TestStep{ + { + Config: config, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} diff --git a/azurerm/resource_arm_iothub_resource_provider_test.go b/azurerm/resource_arm_iothub_resource_provider_test.go index 1032906e853f..ecefe1abdc9e 100644 --- a/azurerm/resource_arm_iothub_resource_provider_test.go +++ b/azurerm/resource_arm_iothub_resource_provider_test.go @@ -90,7 +90,7 @@ resource "azurerm_resource_group" "foo" { name = "acctestRG-%d" location = "%s" } - + resource "azurerm_iothub" "test" { name = "acctestIoTHub-%d" resource_group_name = "${azurerm_resource_group.foo.name}" From 2ea2cfc8882ea068cf756d77c456b9475b531aca Mon Sep 17 00:00:00 2001 From: "shelley.bess" Date: Wed, 28 Feb 2018 20:51:38 -0600 Subject: [PATCH 61/69] Modify IotHub docs --- azurerm/import_arm_iothub_test.go | 2 +- .../resource_arm_iothub_resource_provider.go | 3 +-- ...ource_arm_iothub_resource_provider_test.go | 21 ++++++++++--------- website/azurerm.erb | 15 ++++--------- website/docs/r/iothub.html.markdown | 2 -- 5 files changed, 17 insertions(+), 26 deletions(-) diff --git a/azurerm/import_arm_iothub_test.go b/azurerm/import_arm_iothub_test.go index 5e8991b94602..6e33e6a1a7b9 100644 --- a/azurerm/import_arm_iothub_test.go +++ b/azurerm/import_arm_iothub_test.go @@ -16,7 +16,7 @@ func TestAccAzureRMIotHub_importBasic(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, - CheckDestroy: testCheckAzureRMSubnetDestroy, + CheckDestroy: testCheckAzureRMIotHubDestroy, Steps: []resource.TestStep{ { Config: config, diff --git a/azurerm/resource_arm_iothub_resource_provider.go b/azurerm/resource_arm_iothub_resource_provider.go index b243592dd9a9..710da3d8ccb3 100644 --- a/azurerm/resource_arm_iothub_resource_provider.go +++ b/azurerm/resource_arm_iothub_resource_provider.go @@ -220,11 +220,10 @@ func resourceArmIotHubRead(d *schema.ResourceData, meta interface{}) error { keys = append(keys, keyMap) } - if err != nil { + if err := d.Set("shared_access_policy", keys); err != nil { return fmt.Errorf("Error flattening `shared_access_policy` in IoTHub %q: %+v", iothubName, err) } - d.Set("shared_access_policy", keys) d.Set("hostname", properties.HostName) d.Set("type", desc.Type) flattenAndSetTags(d, &desc.Tags) diff --git a/azurerm/resource_arm_iothub_resource_provider_test.go b/azurerm/resource_arm_iothub_resource_provider_test.go index ecefe1abdc9e..f06063846858 100644 --- a/azurerm/resource_arm_iothub_resource_provider_test.go +++ b/azurerm/resource_arm_iothub_resource_provider_test.go @@ -32,7 +32,7 @@ func TestAccAzureRMIotHub_basicStandard(t *testing.T) { func testCheckAzureRMIotHubDestroy(s *terraform.State) error { ctx := testAccProvider.Meta().(*ArmClient).StopContext - conn := testAccProvider.Meta().(*ArmClient).expressRouteCircuitClient + conn := testAccProvider.Meta().(*ArmClient).iothubResourceClient for _, rs := range s.RootModule().Resources { if rs.Type != "azurerm_iothub" { @@ -49,7 +49,7 @@ func testCheckAzureRMIotHubDestroy(s *terraform.State) error { } if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("IotHub still exists:\n%#v", resp.ExpressRouteCircuitPropertiesFormat) + return fmt.Errorf("IotHub %s still exists in resource group %s", name, resourceGroup) } } return nil @@ -95,15 +95,16 @@ resource "azurerm_iothub" "test" { name = "acctestIoTHub-%d" resource_group_name = "${azurerm_resource_group.foo.name}" location = "${azurerm_resource_group.foo.location}" - sku { - name = "S1" - tier = "Standard" - capacity = "1" - } + sku { + name = "S1" + tier = "Standard" + capacity = "1" + } - tags { - "purpose" = "testing" - } + tags { + "purpose" = "testing" + } } + `, rInt, location, rInt) } diff --git a/website/azurerm.erb b/website/azurerm.erb index 45dd78f4ebda..329ad1210026 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -359,17 +359,6 @@ - > - IotHub Resources - - - > Key Vault Resources