provider/azurerm: Use new library configuration

Most resources are commented out at this stage, as they require surgery
to make them work with the new world of the Azure SDK.
This commit is contained in:
James Nugent 2016-06-01 15:17:21 -05:00
parent a669cd30fa
commit 0769674c54
34 changed files with 8085 additions and 8117 deletions

View File

@ -4,10 +4,7 @@ import (
"fmt" "fmt"
"log" "log"
"net/http" "net/http"
"time"
"github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest"
"github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/azure-sdk-for-go/arm/cdn" "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/compute"
"github.com/Azure/azure-sdk-for-go/arm/network" "github.com/Azure/azure-sdk-for-go/arm/network"
@ -15,6 +12,8 @@ import (
"github.com/Azure/azure-sdk-for-go/arm/scheduler" "github.com/Azure/azure-sdk-for-go/arm/scheduler"
"github.com/Azure/azure-sdk-for-go/arm/storage" "github.com/Azure/azure-sdk-for-go/arm/storage"
mainStorage "github.com/Azure/azure-sdk-for-go/storage" mainStorage "github.com/Azure/azure-sdk-for-go/storage"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/hashicorp/terraform/terraform" "github.com/hashicorp/terraform/terraform"
riviera "github.com/jen20/riviera/azure" riviera "github.com/jen20/riviera/azure"
) )
@ -77,22 +76,6 @@ func withRequestLogging() autorest.SendDecorator {
} }
} }
func withPollWatcher() autorest.SendDecorator {
return func(s autorest.Sender) autorest.Sender {
return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) {
fmt.Printf("[DEBUG] Sending Azure RM Request %q to %q\n", r.Method, r.URL)
resp, err := s.Do(r)
fmt.Printf("[DEBUG] Received Azure RM Request status code %s for %s\n", resp.Status, r.URL)
if autorest.ResponseRequiresPolling(resp) {
fmt.Printf("[DEBUG] Azure RM request will poll %s after %d seconds\n",
autorest.GetPollingLocation(resp),
int(autorest.GetPollingDelay(resp, time.Duration(0))/time.Second))
}
return resp, err
})
}
}
func setUserAgent(client *autorest.Client) { func setUserAgent(client *autorest.Client) {
var version string var version string
if terraform.VersionPrerelease != "" { if terraform.VersionPrerelease != "" {
@ -130,7 +113,23 @@ func (c *Config) getArmClient() (*ArmClient, error) {
} }
client.rivieraClient = rivieraClient client.rivieraClient = rivieraClient
spt, err := azure.NewServicePrincipalToken(c.ClientID, c.ClientSecret, c.TenantID, azure.AzureResourceManagerScope) oauthConfig, err := azure.PublicCloud.OAuthConfigForTenant(c.TenantID)
if err != nil {
return nil, err
}
// This is necessary because no-one thought about API usability. OAuthConfigForTenant
// returns a pointer, which can be nil. NewServicePrincipalToken does not take a pointer.
// Consequently we have to nil check this and do _something_ if it is nil, which should
// be either an invariant of OAuthConfigForTenant (guarantee the token is not nil if
// there is no error), or NewServicePrincipalToken should error out if the configuration
// is required and is nil. This is the worst of all worlds, however.
if oauthConfig == nil {
return nil, fmt.Errorf("Unable to configure OAuthConfig for tenant %s", c.TenantID)
}
spt, err := azure.NewServicePrincipalToken(*oauthConfig, c.ClientID, c.ClientSecret,
azure.PublicCloud.ResourceManagerEndpoint)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -284,7 +283,7 @@ func (c *Config) getArmClient() (*ArmClient, error) {
ssc := storage.NewAccountsClient(c.SubscriptionID) ssc := storage.NewAccountsClient(c.SubscriptionID)
setUserAgent(&ssc.Client) setUserAgent(&ssc.Client)
ssc.Authorizer = spt ssc.Authorizer = spt
ssc.Sender = autorest.CreateSender(withRequestLogging(), withPollWatcher()) ssc.Sender = autorest.CreateSender(withRequestLogging())
client.storageServiceClient = ssc client.storageServiceClient = ssc
suc := storage.NewUsageOperationsClient(c.SubscriptionID) suc := storage.NewUsageOperationsClient(c.SubscriptionID)
@ -349,6 +348,7 @@ func (armClient *ArmClient) getBlobStorageClientForStorageAccount(resourceGroupN
blobClient := storageClient.GetBlobService() blobClient := storageClient.GetBlobService()
return &blobClient, true, nil return &blobClient, true, nil
} }
func (armClient *ArmClient) getQueueServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.QueueServiceClient, bool, error) { func (armClient *ArmClient) getQueueServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.QueueServiceClient, bool, error) {
key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName)
if err != nil { if err != nil {

View File

@ -2,12 +2,9 @@ package azurerm
import ( import (
"fmt" "fmt"
"log"
"net/http"
"reflect" "reflect"
"strings" "strings"
"github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest"
"github.com/hashicorp/go-multierror" "github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform/helper/mutexkv" "github.com/hashicorp/terraform/helper/mutexkv"
"github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/resource"
@ -21,25 +18,25 @@ import (
func Provider() terraform.ResourceProvider { func Provider() terraform.ResourceProvider {
return &schema.Provider{ return &schema.Provider{
Schema: map[string]*schema.Schema{ Schema: map[string]*schema.Schema{
"subscription_id": &schema.Schema{ "subscription_id": {
Type: schema.TypeString, Type: schema.TypeString,
Required: true, Required: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_SUBSCRIPTION_ID", ""), DefaultFunc: schema.EnvDefaultFunc("ARM_SUBSCRIPTION_ID", ""),
}, },
"client_id": &schema.Schema{ "client_id": {
Type: schema.TypeString, Type: schema.TypeString,
Required: true, Required: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_ID", ""), DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_ID", ""),
}, },
"client_secret": &schema.Schema{ "client_secret": {
Type: schema.TypeString, Type: schema.TypeString,
Required: true, Required: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_SECRET", ""), DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_SECRET", ""),
}, },
"tenant_id": &schema.Schema{ "tenant_id": {
Type: schema.TypeString, Type: schema.TypeString,
Required: true, Required: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_TENANT_ID", ""), DefaultFunc: schema.EnvDefaultFunc("ARM_TENANT_ID", ""),
@ -47,37 +44,40 @@ func Provider() terraform.ResourceProvider {
}, },
ResourcesMap: map[string]*schema.Resource{ ResourcesMap: map[string]*schema.Resource{
"azurerm_availability_set": resourceArmAvailabilitySet(), // These resources use the Azure ARM SDK
"azurerm_cdn_endpoint": resourceArmCdnEndpoint(), "azurerm_availability_set": resourceArmAvailabilitySet(),
"azurerm_cdn_profile": resourceArmCdnProfile(), //"azurerm_cdn_endpoint": resourceArmCdnEndpoint(),
"azurerm_dns_a_record": resourceArmDnsARecord(), //"azurerm_cdn_profile": resourceArmCdnProfile(),
"azurerm_dns_aaaa_record": resourceArmDnsAAAARecord(), //"azurerm_local_network_gateway": resourceArmLocalNetworkGateway(),
"azurerm_dns_cname_record": resourceArmDnsCNameRecord(), //"azurerm_network_interface": resourceArmNetworkInterface(),
"azurerm_dns_mx_record": resourceArmDnsMxRecord(), //"azurerm_network_security_group": resourceArmNetworkSecurityGroup(),
"azurerm_dns_ns_record": resourceArmDnsNsRecord(), //"azurerm_network_security_rule": resourceArmNetworkSecurityRule(),
"azurerm_dns_srv_record": resourceArmDnsSrvRecord(), //"azurerm_public_ip": resourceArmPublicIp(),
"azurerm_dns_txt_record": resourceArmDnsTxtRecord(), //"azurerm_route": resourceArmRoute(),
"azurerm_dns_zone": resourceArmDnsZone(), //"azurerm_route_table": resourceArmRouteTable(),
"azurerm_local_network_gateway": resourceArmLocalNetworkGateway(), //"azurerm_storage_account": resourceArmStorageAccount(),
"azurerm_network_interface": resourceArmNetworkInterface(), "azurerm_storage_blob": resourceArmStorageBlob(),
"azurerm_network_security_group": resourceArmNetworkSecurityGroup(), //"azurerm_storage_container": resourceArmStorageContainer(),
"azurerm_network_security_rule": resourceArmNetworkSecurityRule(), "azurerm_storage_queue": resourceArmStorageQueue(),
"azurerm_public_ip": resourceArmPublicIp(), //"azurerm_subnet": resourceArmSubnet(),
"azurerm_resource_group": resourceArmResourceGroup(), //"azurerm_template_deployment": resourceArmTemplateDeployment(),
"azurerm_route": resourceArmRoute(), //"azurerm_virtual_machine": resourceArmVirtualMachine(),
"azurerm_route_table": resourceArmRouteTable(), //"azurerm_virtual_network": resourceArmVirtualNetwork(),
"azurerm_search_service": resourceArmSearchService(),
"azurerm_sql_database": resourceArmSqlDatabase(), // These resources use the Riviera SDK
"azurerm_sql_firewall_rule": resourceArmSqlFirewallRule(), "azurerm_dns_a_record": resourceArmDnsARecord(),
"azurerm_sql_server": resourceArmSqlServer(), "azurerm_dns_aaaa_record": resourceArmDnsAAAARecord(),
"azurerm_storage_account": resourceArmStorageAccount(), "azurerm_dns_cname_record": resourceArmDnsCNameRecord(),
"azurerm_storage_blob": resourceArmStorageBlob(), "azurerm_dns_mx_record": resourceArmDnsMxRecord(),
"azurerm_storage_container": resourceArmStorageContainer(), "azurerm_dns_ns_record": resourceArmDnsNsRecord(),
"azurerm_storage_queue": resourceArmStorageQueue(), "azurerm_dns_srv_record": resourceArmDnsSrvRecord(),
"azurerm_subnet": resourceArmSubnet(), "azurerm_dns_txt_record": resourceArmDnsTxtRecord(),
"azurerm_template_deployment": resourceArmTemplateDeployment(), "azurerm_dns_zone": resourceArmDnsZone(),
"azurerm_virtual_machine": resourceArmVirtualMachine(), "azurerm_resource_group": resourceArmResourceGroup(),
"azurerm_virtual_network": resourceArmVirtualNetwork(), "azurerm_search_service": resourceArmSearchService(),
"azurerm_sql_database": resourceArmSqlDatabase(),
"azurerm_sql_firewall_rule": resourceArmSqlFirewallRule(),
"azurerm_sql_server": resourceArmSqlServer(),
}, },
ConfigureFunc: providerConfigure, ConfigureFunc: providerConfigure,
} }
@ -197,39 +197,6 @@ func azureRMNormalizeLocation(location interface{}) string {
return strings.Replace(strings.ToLower(input), " ", "", -1) return strings.Replace(strings.ToLower(input), " ", "", -1)
} }
// pollIndefinitelyAsNeeded is a terrible hack which is necessary because the Azure
// Storage API (and perhaps others) can have response times way beyond the default
// retry timeouts, with no apparent upper bound. This effectively causes the client
// to continue polling when it reaches the configured timeout. My investigations
// suggest that this is neccesary when deleting and recreating a storage account with
// the same name in a short (though undetermined) time period.
//
// It is possible that this will give Terraform the appearance of being slow in
// future: I have attempted to mitigate this by logging whenever this happens. We
// may want to revisit this with configurable timeouts in the future as clearly
// unbounded wait loops is not ideal. It does seem preferable to the current situation
// where our polling loop will time out _with an operation in progress_, but no ID
// for the resource - so the state will not know about it, and conflicts will occur
// on the next run.
func pollIndefinitelyAsNeeded(client autorest.Client, response *http.Response, acceptableCodes ...int) (*http.Response, error) {
var resp *http.Response
var err error
for {
resp, err = client.PollAsNeeded(response, acceptableCodes...)
if err != nil {
if resp.StatusCode != http.StatusAccepted {
log.Printf("[DEBUG] Starting new polling loop for %q", response.Request.URL.Path)
continue
}
return resp, err
}
return resp, nil
}
}
// armMutexKV is the instance of MutexKV for ARM resources // armMutexKV is the instance of MutexKV for ARM resources
var armMutexKV = mutexkv.NewMutexKV() var armMutexKV = mutexkv.NewMutexKV()

View File

@ -17,26 +17,26 @@ func resourceArmAvailabilitySet() *schema.Resource {
Delete: resourceArmAvailabilitySetDelete, Delete: resourceArmAvailabilitySetDelete,
Schema: map[string]*schema.Schema{ Schema: map[string]*schema.Schema{
"name": &schema.Schema{ "name": {
Type: schema.TypeString, Type: schema.TypeString,
Required: true, Required: true,
ForceNew: true, ForceNew: true,
}, },
"resource_group_name": &schema.Schema{ "resource_group_name": {
Type: schema.TypeString, Type: schema.TypeString,
Required: true, Required: true,
ForceNew: true, ForceNew: true,
}, },
"location": &schema.Schema{ "location": {
Type: schema.TypeString, Type: schema.TypeString,
Required: true, Required: true,
ForceNew: true, ForceNew: true,
StateFunc: azureRMNormalizeLocation, StateFunc: azureRMNormalizeLocation,
}, },
"platform_update_domain_count": &schema.Schema{ "platform_update_domain_count": {
Type: schema.TypeInt, Type: schema.TypeInt,
Optional: true, Optional: true,
Default: 5, Default: 5,
@ -50,7 +50,7 @@ func resourceArmAvailabilitySet() *schema.Resource {
}, },
}, },
"platform_fault_domain_count": &schema.Schema{ "platform_fault_domain_count": {
Type: schema.TypeInt, Type: schema.TypeInt,
Optional: true, Optional: true,
Default: 3, Default: 3,
@ -78,8 +78,8 @@ func resourceArmAvailabilitySetCreate(d *schema.ResourceData, meta interface{})
name := d.Get("name").(string) name := d.Get("name").(string)
location := d.Get("location").(string) location := d.Get("location").(string)
resGroup := d.Get("resource_group_name").(string) resGroup := d.Get("resource_group_name").(string)
updateDomainCount := d.Get("platform_update_domain_count").(int) updateDomainCount := d.Get("platform_update_domain_count").(int32)
faultDomainCount := d.Get("platform_fault_domain_count").(int) faultDomainCount := d.Get("platform_fault_domain_count").(int32)
tags := d.Get("tags").(map[string]interface{}) tags := d.Get("tags").(map[string]interface{})
availSet := compute.AvailabilitySet{ availSet := compute.AvailabilitySet{

View File

@ -1,451 +1,451 @@
package azurerm package azurerm
import ( //import (
"bytes" // "bytes"
"fmt" // "fmt"
"log" // "log"
"net/http" // "net/http"
"strings" // "strings"
"time" // "time"
//
"github.com/Azure/azure-sdk-for-go/arm/cdn" // "github.com/Azure/azure-sdk-for-go/arm/cdn"
"github.com/hashicorp/terraform/helper/hashcode" // "github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema" // "github.com/hashicorp/terraform/helper/schema"
) //)
//
func resourceArmCdnEndpoint() *schema.Resource { //func resourceArmCdnEndpoint() *schema.Resource {
return &schema.Resource{ // return &schema.Resource{
Create: resourceArmCdnEndpointCreate, // Create: resourceArmCdnEndpointCreate,
Read: resourceArmCdnEndpointRead, // Read: resourceArmCdnEndpointRead,
Update: resourceArmCdnEndpointUpdate, // Update: resourceArmCdnEndpointUpdate,
Delete: resourceArmCdnEndpointDelete, // Delete: resourceArmCdnEndpointDelete,
//
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"location": &schema.Schema{ // "location": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
StateFunc: azureRMNormalizeLocation, // StateFunc: azureRMNormalizeLocation,
}, // },
//
"resource_group_name": &schema.Schema{ // "resource_group_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"profile_name": &schema.Schema{ // "profile_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"origin_host_header": &schema.Schema{ // "origin_host_header": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
}, // },
//
"is_http_allowed": &schema.Schema{ // "is_http_allowed": &schema.Schema{
Type: schema.TypeBool, // Type: schema.TypeBool,
Optional: true, // Optional: true,
Default: true, // Default: true,
}, // },
//
"is_https_allowed": &schema.Schema{ // "is_https_allowed": &schema.Schema{
Type: schema.TypeBool, // Type: schema.TypeBool,
Optional: true, // Optional: true,
Default: true, // Default: true,
}, // },
//
"origin": &schema.Schema{ // "origin": &schema.Schema{
Type: schema.TypeSet, // Type: schema.TypeSet,
Required: true, // Required: true,
Elem: &schema.Resource{ // Elem: &schema.Resource{
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"host_name": &schema.Schema{ // "host_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"http_port": &schema.Schema{ // "http_port": &schema.Schema{
Type: schema.TypeInt, // Type: schema.TypeInt,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
}, // },
//
"https_port": &schema.Schema{ // "https_port": &schema.Schema{
Type: schema.TypeInt, // Type: schema.TypeInt,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
}, // },
}, // },
}, // },
Set: resourceArmCdnEndpointOriginHash, // Set: resourceArmCdnEndpointOriginHash,
}, // },
//
"origin_path": &schema.Schema{ // "origin_path": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
}, // },
//
"querystring_caching_behaviour": &schema.Schema{ // "querystring_caching_behaviour": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
Default: "IgnoreQueryString", // Default: "IgnoreQueryString",
ValidateFunc: validateCdnEndpointQuerystringCachingBehaviour, // ValidateFunc: validateCdnEndpointQuerystringCachingBehaviour,
}, // },
//
"content_types_to_compress": &schema.Schema{ // "content_types_to_compress": &schema.Schema{
Type: schema.TypeSet, // Type: schema.TypeSet,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
Elem: &schema.Schema{Type: schema.TypeString}, // Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString, // Set: schema.HashString,
}, // },
//
"is_compression_enabled": &schema.Schema{ // "is_compression_enabled": &schema.Schema{
Type: schema.TypeBool, // Type: schema.TypeBool,
Optional: true, // Optional: true,
Default: false, // Default: false,
}, // },
//
"host_name": &schema.Schema{ // "host_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Computed: true, // Computed: true,
}, // },
//
"tags": tagsSchema(), // "tags": tagsSchema(),
}, // },
} // }
} //}
//
func resourceArmCdnEndpointCreate(d *schema.ResourceData, meta interface{}) error { //func resourceArmCdnEndpointCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient) // client := meta.(*ArmClient)
cdnEndpointsClient := client.cdnEndpointsClient // cdnEndpointsClient := client.cdnEndpointsClient
//
log.Printf("[INFO] preparing arguments for Azure ARM CDN EndPoint creation.") // log.Printf("[INFO] preparing arguments for Azure ARM CDN EndPoint creation.")
//
name := d.Get("name").(string) // name := d.Get("name").(string)
location := d.Get("location").(string) // location := d.Get("location").(string)
resGroup := d.Get("resource_group_name").(string) // resGroup := d.Get("resource_group_name").(string)
profileName := d.Get("profile_name").(string) // profileName := d.Get("profile_name").(string)
http_allowed := d.Get("is_http_allowed").(bool) // http_allowed := d.Get("is_http_allowed").(bool)
https_allowed := d.Get("is_https_allowed").(bool) // https_allowed := d.Get("is_https_allowed").(bool)
compression_enabled := d.Get("is_compression_enabled").(bool) // compression_enabled := d.Get("is_compression_enabled").(bool)
caching_behaviour := d.Get("querystring_caching_behaviour").(string) // caching_behaviour := d.Get("querystring_caching_behaviour").(string)
tags := d.Get("tags").(map[string]interface{}) // tags := d.Get("tags").(map[string]interface{})
//
properties := cdn.EndpointPropertiesCreateUpdateParameters{ // properties := cdn.EndpointPropertiesCreateUpdateParameters{
IsHTTPAllowed: &http_allowed, // IsHTTPAllowed: &http_allowed,
IsHTTPSAllowed: &https_allowed, // IsHTTPSAllowed: &https_allowed,
IsCompressionEnabled: &compression_enabled, // IsCompressionEnabled: &compression_enabled,
QueryStringCachingBehavior: cdn.QueryStringCachingBehavior(caching_behaviour), // QueryStringCachingBehavior: cdn.QueryStringCachingBehavior(caching_behaviour),
} // }
//
origins, originsErr := expandAzureRmCdnEndpointOrigins(d) // origins, originsErr := expandAzureRmCdnEndpointOrigins(d)
if originsErr != nil { // if originsErr != nil {
return fmt.Errorf("Error Building list of CDN Endpoint Origins: %s", originsErr) // return fmt.Errorf("Error Building list of CDN Endpoint Origins: %s", originsErr)
} // }
if len(origins) > 0 { // if len(origins) > 0 {
properties.Origins = &origins // properties.Origins = &origins
} // }
//
if v, ok := d.GetOk("origin_host_header"); ok { // if v, ok := d.GetOk("origin_host_header"); ok {
host_header := v.(string) // host_header := v.(string)
properties.OriginHostHeader = &host_header // properties.OriginHostHeader = &host_header
} // }
//
if v, ok := d.GetOk("origin_path"); ok { // if v, ok := d.GetOk("origin_path"); ok {
origin_path := v.(string) // origin_path := v.(string)
properties.OriginPath = &origin_path // properties.OriginPath = &origin_path
} // }
//
if v, ok := d.GetOk("content_types_to_compress"); ok { // if v, ok := d.GetOk("content_types_to_compress"); ok {
var content_types []string // var content_types []string
ctypes := v.(*schema.Set).List() // ctypes := v.(*schema.Set).List()
for _, ct := range ctypes { // for _, ct := range ctypes {
str := ct.(string) // str := ct.(string)
content_types = append(content_types, str) // content_types = append(content_types, str)
} // }
//
properties.ContentTypesToCompress = &content_types // properties.ContentTypesToCompress = &content_types
} // }
//
cdnEndpoint := cdn.EndpointCreateParameters{ // cdnEndpoint := cdn.EndpointCreateParameters{
Location: &location, // Location: &location,
Properties: &properties, // Properties: &properties,
Tags: expandTags(tags), // Tags: expandTags(tags),
} // }
//
resp, err := cdnEndpointsClient.Create(name, cdnEndpoint, profileName, resGroup) // resp, err := cdnEndpointsClient.Create(name, cdnEndpoint, profileName, resGroup)
if err != nil { // if err != nil {
return err // return err
} // }
//
d.SetId(*resp.ID) // d.SetId(*resp.ID)
//
log.Printf("[DEBUG] Waiting for CDN Endpoint (%s) to become available", name) // log.Printf("[DEBUG] Waiting for CDN Endpoint (%s) to become available", name)
stateConf := &resource.StateChangeConf{ // stateConf := &resource.StateChangeConf{
Pending: []string{"Accepted", "Updating", "Creating"}, // Pending: []string{"Accepted", "Updating", "Creating"},
Target: []string{"Succeeded"}, // Target: []string{"Succeeded"},
Refresh: cdnEndpointStateRefreshFunc(client, resGroup, profileName, name), // Refresh: cdnEndpointStateRefreshFunc(client, resGroup, profileName, name),
Timeout: 10 * time.Minute, // Timeout: 10 * time.Minute,
} // }
if _, err := stateConf.WaitForState(); err != nil { // if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for CDN Endpoint (%s) to become available: %s", name, err) // return fmt.Errorf("Error waiting for CDN Endpoint (%s) to become available: %s", name, err)
} // }
//
return resourceArmCdnEndpointRead(d, meta) // return resourceArmCdnEndpointRead(d, meta)
} //}
//
func resourceArmCdnEndpointRead(d *schema.ResourceData, meta interface{}) error { //func resourceArmCdnEndpointRead(d *schema.ResourceData, meta interface{}) error {
cdnEndpointsClient := meta.(*ArmClient).cdnEndpointsClient // cdnEndpointsClient := meta.(*ArmClient).cdnEndpointsClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["endpoints"] // name := id.Path["endpoints"]
profileName := id.Path["profiles"] // profileName := id.Path["profiles"]
if profileName == "" { // if profileName == "" {
profileName = id.Path["Profiles"] // profileName = id.Path["Profiles"]
} // }
log.Printf("[INFO] Trying to find the AzureRM CDN Endpoint %s (Profile: %s, RG: %s)", name, profileName, resGroup) // log.Printf("[INFO] Trying to find the AzureRM CDN Endpoint %s (Profile: %s, RG: %s)", name, profileName, resGroup)
resp, err := cdnEndpointsClient.Get(name, profileName, resGroup) // resp, err := cdnEndpointsClient.Get(name, profileName, resGroup)
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
d.SetId("") // d.SetId("")
return nil // return nil
} // }
if err != nil { // if err != nil {
return fmt.Errorf("Error making Read request on Azure CDN Endpoint %s: %s", name, err) // return fmt.Errorf("Error making Read request on Azure CDN Endpoint %s: %s", name, err)
} // }
//
d.Set("name", resp.Name) // d.Set("name", resp.Name)
d.Set("host_name", resp.Properties.HostName) // d.Set("host_name", resp.Properties.HostName)
d.Set("is_compression_enabled", resp.Properties.IsCompressionEnabled) // d.Set("is_compression_enabled", resp.Properties.IsCompressionEnabled)
d.Set("is_http_allowed", resp.Properties.IsHTTPAllowed) // d.Set("is_http_allowed", resp.Properties.IsHTTPAllowed)
d.Set("is_https_allowed", resp.Properties.IsHTTPSAllowed) // d.Set("is_https_allowed", resp.Properties.IsHTTPSAllowed)
d.Set("querystring_caching_behaviour", resp.Properties.QueryStringCachingBehavior) // d.Set("querystring_caching_behaviour", resp.Properties.QueryStringCachingBehavior)
if resp.Properties.OriginHostHeader != nil && *resp.Properties.OriginHostHeader != "" { // if resp.Properties.OriginHostHeader != nil && *resp.Properties.OriginHostHeader != "" {
d.Set("origin_host_header", resp.Properties.OriginHostHeader) // d.Set("origin_host_header", resp.Properties.OriginHostHeader)
} // }
if resp.Properties.OriginPath != nil && *resp.Properties.OriginPath != "" { // if resp.Properties.OriginPath != nil && *resp.Properties.OriginPath != "" {
d.Set("origin_path", resp.Properties.OriginPath) // d.Set("origin_path", resp.Properties.OriginPath)
} // }
if resp.Properties.ContentTypesToCompress != nil && len(*resp.Properties.ContentTypesToCompress) > 0 { // if resp.Properties.ContentTypesToCompress != nil && len(*resp.Properties.ContentTypesToCompress) > 0 {
d.Set("content_types_to_compress", flattenAzureRMCdnEndpointContentTypes(resp.Properties.ContentTypesToCompress)) // d.Set("content_types_to_compress", flattenAzureRMCdnEndpointContentTypes(resp.Properties.ContentTypesToCompress))
} // }
d.Set("origin", flattenAzureRMCdnEndpointOrigin(resp.Properties.Origins)) // d.Set("origin", flattenAzureRMCdnEndpointOrigin(resp.Properties.Origins))
//
flattenAndSetTags(d, resp.Tags) // flattenAndSetTags(d, resp.Tags)
//
return nil // return nil
} //}
//
func resourceArmCdnEndpointUpdate(d *schema.ResourceData, meta interface{}) error { //func resourceArmCdnEndpointUpdate(d *schema.ResourceData, meta interface{}) error {
cdnEndpointsClient := meta.(*ArmClient).cdnEndpointsClient // cdnEndpointsClient := meta.(*ArmClient).cdnEndpointsClient
//
if !d.HasChange("tags") { // if !d.HasChange("tags") {
return nil // return nil
} // }
//
name := d.Get("name").(string) // name := d.Get("name").(string)
resGroup := d.Get("resource_group_name").(string) // resGroup := d.Get("resource_group_name").(string)
profileName := d.Get("profile_name").(string) // profileName := d.Get("profile_name").(string)
http_allowed := d.Get("is_http_allowed").(bool) // http_allowed := d.Get("is_http_allowed").(bool)
https_allowed := d.Get("is_https_allowed").(bool) // https_allowed := d.Get("is_https_allowed").(bool)
compression_enabled := d.Get("is_compression_enabled").(bool) // compression_enabled := d.Get("is_compression_enabled").(bool)
caching_behaviour := d.Get("querystring_caching_behaviour").(string) // caching_behaviour := d.Get("querystring_caching_behaviour").(string)
newTags := d.Get("tags").(map[string]interface{}) // newTags := d.Get("tags").(map[string]interface{})
//
properties := cdn.EndpointPropertiesCreateUpdateParameters{ // properties := cdn.EndpointPropertiesCreateUpdateParameters{
IsHTTPAllowed: &http_allowed, // IsHTTPAllowed: &http_allowed,
IsHTTPSAllowed: &https_allowed, // IsHTTPSAllowed: &https_allowed,
IsCompressionEnabled: &compression_enabled, // IsCompressionEnabled: &compression_enabled,
QueryStringCachingBehavior: cdn.QueryStringCachingBehavior(caching_behaviour), // QueryStringCachingBehavior: cdn.QueryStringCachingBehavior(caching_behaviour),
} // }
//
if d.HasChange("origin") { // if d.HasChange("origin") {
origins, originsErr := expandAzureRmCdnEndpointOrigins(d) // origins, originsErr := expandAzureRmCdnEndpointOrigins(d)
if originsErr != nil { // if originsErr != nil {
return fmt.Errorf("Error Building list of CDN Endpoint Origins: %s", originsErr) // return fmt.Errorf("Error Building list of CDN Endpoint Origins: %s", originsErr)
} // }
if len(origins) > 0 { // if len(origins) > 0 {
properties.Origins = &origins // properties.Origins = &origins
} // }
} // }
//
if d.HasChange("origin_host_header") { // if d.HasChange("origin_host_header") {
host_header := d.Get("origin_host_header").(string) // host_header := d.Get("origin_host_header").(string)
properties.OriginHostHeader = &host_header // properties.OriginHostHeader = &host_header
} // }
//
if d.HasChange("origin_path") { // if d.HasChange("origin_path") {
origin_path := d.Get("origin_path").(string) // origin_path := d.Get("origin_path").(string)
properties.OriginPath = &origin_path // properties.OriginPath = &origin_path
} // }
//
if d.HasChange("content_types_to_compress") { // if d.HasChange("content_types_to_compress") {
var content_types []string // var content_types []string
ctypes := d.Get("content_types_to_compress").(*schema.Set).List() // ctypes := d.Get("content_types_to_compress").(*schema.Set).List()
for _, ct := range ctypes { // for _, ct := range ctypes {
str := ct.(string) // str := ct.(string)
content_types = append(content_types, str) // content_types = append(content_types, str)
} // }
//
properties.ContentTypesToCompress = &content_types // properties.ContentTypesToCompress = &content_types
} // }
//
updateProps := cdn.EndpointUpdateParameters{ // updateProps := cdn.EndpointUpdateParameters{
Tags: expandTags(newTags), // Tags: expandTags(newTags),
Properties: &properties, // Properties: &properties,
} // }
//
_, err := cdnEndpointsClient.Update(name, updateProps, profileName, resGroup) // _, err := cdnEndpointsClient.Update(name, updateProps, profileName, resGroup)
if err != nil { // if err != nil {
return fmt.Errorf("Error issuing Azure ARM update request to update CDN Endpoint %q: %s", name, err) // return fmt.Errorf("Error issuing Azure ARM update request to update CDN Endpoint %q: %s", name, err)
} // }
//
return resourceArmCdnEndpointRead(d, meta) // return resourceArmCdnEndpointRead(d, meta)
} //}
//
func resourceArmCdnEndpointDelete(d *schema.ResourceData, meta interface{}) error { //func resourceArmCdnEndpointDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).cdnEndpointsClient // client := meta.(*ArmClient).cdnEndpointsClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
profileName := id.Path["profiles"] // profileName := id.Path["profiles"]
if profileName == "" { // if profileName == "" {
profileName = id.Path["Profiles"] // profileName = id.Path["Profiles"]
} // }
name := id.Path["endpoints"] // name := id.Path["endpoints"]
//
accResp, err := client.DeleteIfExists(name, profileName, resGroup) // accResp, err := client.DeleteIfExists(name, profileName, resGroup)
if err != nil { // if err != nil {
if accResp.StatusCode == http.StatusNotFound { // if accResp.StatusCode == http.StatusNotFound {
return nil // return nil
} // }
return fmt.Errorf("Error issuing AzureRM delete request for CDN Endpoint %q: %s", name, err) // return fmt.Errorf("Error issuing AzureRM delete request for CDN Endpoint %q: %s", name, err)
} // }
_, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response, http.StatusNotFound) // _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response, http.StatusNotFound)
if err != nil { // if err != nil {
return fmt.Errorf("Error polling for AzureRM delete request for CDN Endpoint %q: %s", name, err) // return fmt.Errorf("Error polling for AzureRM delete request for CDN Endpoint %q: %s", name, err)
} // }
//
return err // return err
} //}
//
func cdnEndpointStateRefreshFunc(client *ArmClient, resourceGroupName string, profileName string, name string) resource.StateRefreshFunc { //func cdnEndpointStateRefreshFunc(client *ArmClient, resourceGroupName string, profileName string, name string) resource.StateRefreshFunc {
return func() (interface{}, string, error) { // return func() (interface{}, string, error) {
res, err := client.cdnEndpointsClient.Get(name, profileName, resourceGroupName) // res, err := client.cdnEndpointsClient.Get(name, profileName, resourceGroupName)
if err != nil { // if err != nil {
return nil, "", fmt.Errorf("Error issuing read request in cdnEndpointStateRefreshFunc to Azure ARM for CDN Endpoint '%s' (RG: '%s'): %s", name, resourceGroupName, err) // return nil, "", fmt.Errorf("Error issuing read request in cdnEndpointStateRefreshFunc to Azure ARM for CDN Endpoint '%s' (RG: '%s'): %s", name, resourceGroupName, err)
} // }
return res, string(res.Properties.ProvisioningState), nil // return res, string(res.Properties.ProvisioningState), nil
} // }
} //}
//
func validateCdnEndpointQuerystringCachingBehaviour(v interface{}, k string) (ws []string, errors []error) { //func validateCdnEndpointQuerystringCachingBehaviour(v interface{}, k string) (ws []string, errors []error) {
value := strings.ToLower(v.(string)) // value := strings.ToLower(v.(string))
cachingTypes := map[string]bool{ // cachingTypes := map[string]bool{
"ignorequerystring": true, // "ignorequerystring": true,
"bypasscaching": true, // "bypasscaching": true,
"usequerystring": true, // "usequerystring": true,
} // }
//
if !cachingTypes[value] { // if !cachingTypes[value] {
errors = append(errors, fmt.Errorf("CDN Endpoint querystringCachingBehaviours can only be IgnoreQueryString, BypassCaching or UseQueryString")) // errors = append(errors, fmt.Errorf("CDN Endpoint querystringCachingBehaviours can only be IgnoreQueryString, BypassCaching or UseQueryString"))
} // }
return // return
} //}
//
func resourceArmCdnEndpointOriginHash(v interface{}) int { //func resourceArmCdnEndpointOriginHash(v interface{}) int {
var buf bytes.Buffer // var buf bytes.Buffer
m := v.(map[string]interface{}) // m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["name"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["host_name"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["host_name"].(string)))
//
return hashcode.String(buf.String()) // return hashcode.String(buf.String())
} //}
//
func expandAzureRmCdnEndpointOrigins(d *schema.ResourceData) ([]cdn.DeepCreatedOrigin, error) { //func expandAzureRmCdnEndpointOrigins(d *schema.ResourceData) ([]cdn.DeepCreatedOrigin, error) {
configs := d.Get("origin").(*schema.Set).List() // configs := d.Get("origin").(*schema.Set).List()
origins := make([]cdn.DeepCreatedOrigin, 0, len(configs)) // origins := make([]cdn.DeepCreatedOrigin, 0, len(configs))
//
for _, configRaw := range configs { // for _, configRaw := range configs {
data := configRaw.(map[string]interface{}) // data := configRaw.(map[string]interface{})
//
host_name := data["host_name"].(string) // host_name := data["host_name"].(string)
//
properties := cdn.DeepCreatedOriginProperties{ // properties := cdn.DeepCreatedOriginProperties{
HostName: &host_name, // HostName: &host_name,
} // }
//
if v, ok := data["https_port"]; ok { // if v, ok := data["https_port"]; ok {
https_port := v.(int) // https_port := v.(int)
properties.HTTPSPort = &https_port // properties.HTTPSPort = &https_port
//
} // }
//
if v, ok := data["http_port"]; ok { // if v, ok := data["http_port"]; ok {
http_port := v.(int) // http_port := v.(int)
properties.HTTPPort = &http_port // properties.HTTPPort = &http_port
} // }
//
name := data["name"].(string) // name := data["name"].(string)
//
origin := cdn.DeepCreatedOrigin{ // origin := cdn.DeepCreatedOrigin{
Name: &name, // Name: &name,
Properties: &properties, // Properties: &properties,
} // }
//
origins = append(origins, origin) // origins = append(origins, origin)
} // }
//
return origins, nil // return origins, nil
} //}
//
func flattenAzureRMCdnEndpointOrigin(list *[]cdn.DeepCreatedOrigin) []map[string]interface{} { //func flattenAzureRMCdnEndpointOrigin(list *[]cdn.DeepCreatedOrigin) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(*list)) // result := make([]map[string]interface{}, 0, len(*list))
for _, i := range *list { // for _, i := range *list {
l := map[string]interface{}{ // l := map[string]interface{}{
"name": *i.Name, // "name": *i.Name,
"host_name": *i.Properties.HostName, // "host_name": *i.Properties.HostName,
} // }
//
if i.Properties.HTTPPort != nil { // if i.Properties.HTTPPort != nil {
l["http_port"] = *i.Properties.HTTPPort // l["http_port"] = *i.Properties.HTTPPort
} // }
if i.Properties.HTTPSPort != nil { // if i.Properties.HTTPSPort != nil {
l["https_port"] = *i.Properties.HTTPSPort // l["https_port"] = *i.Properties.HTTPSPort
} // }
result = append(result, l) // result = append(result, l)
} // }
return result // return result
} //}
//
func flattenAzureRMCdnEndpointContentTypes(list *[]string) []interface{} { //func flattenAzureRMCdnEndpointContentTypes(list *[]string) []interface{} {
vs := make([]interface{}, 0, len(*list)) // vs := make([]interface{}, 0, len(*list))
for _, v := range *list { // for _, v := range *list {
vs = append(vs, v) // vs = append(vs, v)
} // }
return vs // return vs
} //}

View File

@ -1,215 +1,215 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"net/http" // "net/http"
"testing" // "testing"
//
"github.com/hashicorp/terraform/helper/acctest" // "github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" // "github.com/hashicorp/terraform/terraform"
) //)
//
func TestAccAzureRMCdnEndpoint_basic(t *testing.T) { //func TestAccAzureRMCdnEndpoint_basic(t *testing.T) {
//
ri := acctest.RandInt() // ri := acctest.RandInt()
config := fmt.Sprintf(testAccAzureRMCdnEndpoint_basic, ri, ri, ri) // config := fmt.Sprintf(testAccAzureRMCdnEndpoint_basic, ri, ri, ri)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMCdnEndpointDestroy, // CheckDestroy: testCheckAzureRMCdnEndpointDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: config, // Config: config,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"), // testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func TestAccAzureRMCdnEndpoints_withTags(t *testing.T) { //func TestAccAzureRMCdnEndpoints_withTags(t *testing.T) {
//
ri := acctest.RandInt() // ri := acctest.RandInt()
preConfig := fmt.Sprintf(testAccAzureRMCdnEndpoint_withTags, ri, ri, ri) // preConfig := fmt.Sprintf(testAccAzureRMCdnEndpoint_withTags, ri, ri, ri)
postConfig := fmt.Sprintf(testAccAzureRMCdnEndpoint_withTagsUpdate, ri, ri, ri) // postConfig := fmt.Sprintf(testAccAzureRMCdnEndpoint_withTagsUpdate, ri, ri, ri)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMCdnEndpointDestroy, // CheckDestroy: testCheckAzureRMCdnEndpointDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: preConfig, // Config: preConfig,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"), // testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_cdn_endpoint.test", "tags.#", "2"), // "azurerm_cdn_endpoint.test", "tags.#", "2"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_cdn_endpoint.test", "tags.environment", "Production"), // "azurerm_cdn_endpoint.test", "tags.environment", "Production"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_cdn_endpoint.test", "tags.cost_center", "MSFT"), // "azurerm_cdn_endpoint.test", "tags.cost_center", "MSFT"),
), // ),
}, // },
//
resource.TestStep{ // resource.TestStep{
Config: postConfig, // Config: postConfig,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"), // testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_cdn_endpoint.test", "tags.#", "1"), // "azurerm_cdn_endpoint.test", "tags.#", "1"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_cdn_endpoint.test", "tags.environment", "staging"), // "azurerm_cdn_endpoint.test", "tags.environment", "staging"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func testCheckAzureRMCdnEndpointExists(name string) resource.TestCheckFunc { //func testCheckAzureRMCdnEndpointExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error { // return func(s *terraform.State) error {
// Ensure we have enough information in state to look up in API // // Ensure we have enough information in state to look up in API
rs, ok := s.RootModule().Resources[name] // rs, ok := s.RootModule().Resources[name]
if !ok { // if !ok {
return fmt.Errorf("Not found: %s", name) // return fmt.Errorf("Not found: %s", name)
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
profileName := rs.Primary.Attributes["profile_name"] // profileName := rs.Primary.Attributes["profile_name"]
resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
if !hasResourceGroup { // if !hasResourceGroup {
return fmt.Errorf("Bad: no resource group found in state for cdn endpoint: %s", name) // return fmt.Errorf("Bad: no resource group found in state for cdn endpoint: %s", name)
} // }
//
conn := testAccProvider.Meta().(*ArmClient).cdnEndpointsClient // conn := testAccProvider.Meta().(*ArmClient).cdnEndpointsClient
//
resp, err := conn.Get(name, profileName, resourceGroup) // resp, err := conn.Get(name, profileName, resourceGroup)
if err != nil { // if err != nil {
return fmt.Errorf("Bad: Get on cdnEndpointsClient: %s", err) // return fmt.Errorf("Bad: Get on cdnEndpointsClient: %s", err)
} // }
//
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("Bad: CDN Endpoint %q (resource group: %q) does not exist", name, resourceGroup) // return fmt.Errorf("Bad: CDN Endpoint %q (resource group: %q) does not exist", name, resourceGroup)
} // }
//
return nil // return nil
} // }
} //}
//
func testCheckAzureRMCdnEndpointDestroy(s *terraform.State) error { //func testCheckAzureRMCdnEndpointDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*ArmClient).cdnEndpointsClient // conn := testAccProvider.Meta().(*ArmClient).cdnEndpointsClient
//
for _, rs := range s.RootModule().Resources { // for _, rs := range s.RootModule().Resources {
if rs.Type != "azurerm_cdn_endpoint" { // if rs.Type != "azurerm_cdn_endpoint" {
continue // continue
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup := rs.Primary.Attributes["resource_group_name"]
profileName := rs.Primary.Attributes["profile_name"] // profileName := rs.Primary.Attributes["profile_name"]
//
resp, err := conn.Get(name, profileName, resourceGroup) // resp, err := conn.Get(name, profileName, resourceGroup)
//
if err != nil { // if err != nil {
return nil // return nil
} // }
//
if resp.StatusCode != http.StatusNotFound { // if resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("CDN Endpoint still exists:\n%#v", resp.Properties) // return fmt.Errorf("CDN Endpoint still exists:\n%#v", resp.Properties)
} // }
} // }
//
return nil // return nil
} //}
//
var testAccAzureRMCdnEndpoint_basic = ` //var testAccAzureRMCdnEndpoint_basic = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
resource "azurerm_cdn_profile" "test" { //resource "azurerm_cdn_profile" "test" {
name = "acctestcdnprof%d" // name = "acctestcdnprof%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
sku = "Standard" // sku = "Standard"
} //}
//
resource "azurerm_cdn_endpoint" "test" { //resource "azurerm_cdn_endpoint" "test" {
name = "acctestcdnend%d" // name = "acctestcdnend%d"
profile_name = "${azurerm_cdn_profile.test.name}" // profile_name = "${azurerm_cdn_profile.test.name}"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
//
origin { // origin {
name = "acceptanceTestCdnOrigin1" // name = "acceptanceTestCdnOrigin1"
host_name = "www.example.com" // host_name = "www.example.com"
https_port = 443 // https_port = 443
http_port = 80 // http_port = 80
} // }
} //}
` //`
//
var testAccAzureRMCdnEndpoint_withTags = ` //var testAccAzureRMCdnEndpoint_withTags = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
resource "azurerm_cdn_profile" "test" { //resource "azurerm_cdn_profile" "test" {
name = "acctestcdnprof%d" // name = "acctestcdnprof%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
sku = "Standard" // sku = "Standard"
} //}
//
resource "azurerm_cdn_endpoint" "test" { //resource "azurerm_cdn_endpoint" "test" {
name = "acctestcdnend%d" // name = "acctestcdnend%d"
profile_name = "${azurerm_cdn_profile.test.name}" // profile_name = "${azurerm_cdn_profile.test.name}"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
//
origin { // origin {
name = "acceptanceTestCdnOrigin2" // name = "acceptanceTestCdnOrigin2"
host_name = "www.example.com" // host_name = "www.example.com"
https_port = 443 // https_port = 443
http_port = 80 // http_port = 80
} // }
//
tags { // tags {
environment = "Production" // environment = "Production"
cost_center = "MSFT" // cost_center = "MSFT"
} // }
} //}
` //`
//
var testAccAzureRMCdnEndpoint_withTagsUpdate = ` //var testAccAzureRMCdnEndpoint_withTagsUpdate = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
resource "azurerm_cdn_profile" "test" { //resource "azurerm_cdn_profile" "test" {
name = "acctestcdnprof%d" // name = "acctestcdnprof%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
sku = "Standard" // sku = "Standard"
} //}
//
resource "azurerm_cdn_endpoint" "test" { //resource "azurerm_cdn_endpoint" "test" {
name = "acctestcdnend%d" // name = "acctestcdnend%d"
profile_name = "${azurerm_cdn_profile.test.name}" // profile_name = "${azurerm_cdn_profile.test.name}"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
//
origin { // origin {
name = "acceptanceTestCdnOrigin2" // name = "acceptanceTestCdnOrigin2"
host_name = "www.example.com" // host_name = "www.example.com"
https_port = 443 // https_port = 443
http_port = 80 // http_port = 80
} // }
//
tags { // tags {
environment = "staging" // environment = "staging"
} // }
} //}
` //`

View File

@ -1,186 +1,186 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"log" // "log"
"net/http" // "net/http"
"strings" // "strings"
"time" // "time"
//
"github.com/Azure/azure-sdk-for-go/arm/cdn" // "github.com/Azure/azure-sdk-for-go/arm/cdn"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema" // "github.com/hashicorp/terraform/helper/schema"
) //)
//
func resourceArmCdnProfile() *schema.Resource { //func resourceArmCdnProfile() *schema.Resource {
return &schema.Resource{ // return &schema.Resource{
Create: resourceArmCdnProfileCreate, // Create: resourceArmCdnProfileCreate,
Read: resourceArmCdnProfileRead, // Read: resourceArmCdnProfileRead,
Update: resourceArmCdnProfileUpdate, // Update: resourceArmCdnProfileUpdate,
Delete: resourceArmCdnProfileDelete, // Delete: resourceArmCdnProfileDelete,
//
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"location": &schema.Schema{ // "location": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
StateFunc: azureRMNormalizeLocation, // StateFunc: azureRMNormalizeLocation,
}, // },
//
"resource_group_name": &schema.Schema{ // "resource_group_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"sku": &schema.Schema{ // "sku": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
ValidateFunc: validateCdnProfileSku, // ValidateFunc: validateCdnProfileSku,
}, // },
//
"tags": tagsSchema(), // "tags": tagsSchema(),
}, // },
} // }
} //}
//
func resourceArmCdnProfileCreate(d *schema.ResourceData, meta interface{}) error { //func resourceArmCdnProfileCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient) // client := meta.(*ArmClient)
cdnProfilesClient := client.cdnProfilesClient // cdnProfilesClient := client.cdnProfilesClient
//
log.Printf("[INFO] preparing arguments for Azure ARM CDN Profile creation.") // log.Printf("[INFO] preparing arguments for Azure ARM CDN Profile creation.")
//
name := d.Get("name").(string) // name := d.Get("name").(string)
location := d.Get("location").(string) // location := d.Get("location").(string)
resGroup := d.Get("resource_group_name").(string) // resGroup := d.Get("resource_group_name").(string)
sku := d.Get("sku").(string) // sku := d.Get("sku").(string)
tags := d.Get("tags").(map[string]interface{}) // tags := d.Get("tags").(map[string]interface{})
//
properties := cdn.ProfilePropertiesCreateParameters{ // properties := cdn.ProfilePropertiesCreateParameters{
Sku: &cdn.Sku{ // Sku: &cdn.Sku{
Name: cdn.SkuName(sku), // Name: cdn.SkuName(sku),
}, // },
} // }
//
cdnProfile := cdn.ProfileCreateParameters{ // cdnProfile := cdn.ProfileCreateParameters{
Location: &location, // Location: &location,
Properties: &properties, // Properties: &properties,
Tags: expandTags(tags), // Tags: expandTags(tags),
} // }
//
resp, err := cdnProfilesClient.Create(name, cdnProfile, resGroup) // resp, err := cdnProfilesClient.Create(name, cdnProfile, resGroup)
if err != nil { // if err != nil {
return err // return err
} // }
//
d.SetId(*resp.ID) // d.SetId(*resp.ID)
//
log.Printf("[DEBUG] Waiting for CDN Profile (%s) to become available", name) // log.Printf("[DEBUG] Waiting for CDN Profile (%s) to become available", name)
stateConf := &resource.StateChangeConf{ // stateConf := &resource.StateChangeConf{
Pending: []string{"Accepted", "Updating", "Creating"}, // Pending: []string{"Accepted", "Updating", "Creating"},
Target: []string{"Succeeded"}, // Target: []string{"Succeeded"},
Refresh: cdnProfileStateRefreshFunc(client, resGroup, name), // Refresh: cdnProfileStateRefreshFunc(client, resGroup, name),
Timeout: 10 * time.Minute, // Timeout: 10 * time.Minute,
} // }
if _, err := stateConf.WaitForState(); err != nil { // if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for CDN Profile (%s) to become available: %s", name, err) // return fmt.Errorf("Error waiting for CDN Profile (%s) to become available: %s", name, err)
} // }
//
return resourceArmCdnProfileRead(d, meta) // return resourceArmCdnProfileRead(d, meta)
} //}
//
func resourceArmCdnProfileRead(d *schema.ResourceData, meta interface{}) error { //func resourceArmCdnProfileRead(d *schema.ResourceData, meta interface{}) error {
cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient // cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["Profiles"] // name := id.Path["Profiles"]
//
resp, err := cdnProfilesClient.Get(name, resGroup) // resp, err := cdnProfilesClient.Get(name, resGroup)
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
d.SetId("") // d.SetId("")
return nil // return nil
} // }
if err != nil { // if err != nil {
return fmt.Errorf("Error making Read request on Azure CDN Profile %s: %s", name, err) // return fmt.Errorf("Error making Read request on Azure CDN Profile %s: %s", name, err)
} // }
//
if resp.Properties != nil && resp.Properties.Sku != nil { // if resp.Properties != nil && resp.Properties.Sku != nil {
d.Set("sku", string(resp.Properties.Sku.Name)) // d.Set("sku", string(resp.Properties.Sku.Name))
} // }
//
flattenAndSetTags(d, resp.Tags) // flattenAndSetTags(d, resp.Tags)
//
return nil // return nil
} //}
//
func resourceArmCdnProfileUpdate(d *schema.ResourceData, meta interface{}) error { //func resourceArmCdnProfileUpdate(d *schema.ResourceData, meta interface{}) error {
cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient // cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient
//
if !d.HasChange("tags") { // if !d.HasChange("tags") {
return nil // return nil
} // }
//
name := d.Get("name").(string) // name := d.Get("name").(string)
resGroup := d.Get("resource_group_name").(string) // resGroup := d.Get("resource_group_name").(string)
newTags := d.Get("tags").(map[string]interface{}) // newTags := d.Get("tags").(map[string]interface{})
//
props := cdn.ProfileUpdateParameters{ // props := cdn.ProfileUpdateParameters{
Tags: expandTags(newTags), // Tags: expandTags(newTags),
} // }
//
_, err := cdnProfilesClient.Update(name, props, resGroup) // _, err := cdnProfilesClient.Update(name, props, resGroup)
if err != nil { // if err != nil {
return fmt.Errorf("Error issuing Azure ARM update request to update CDN Profile %q: %s", name, err) // return fmt.Errorf("Error issuing Azure ARM update request to update CDN Profile %q: %s", name, err)
} // }
//
return resourceArmCdnProfileRead(d, meta) // return resourceArmCdnProfileRead(d, meta)
} //}
//
func resourceArmCdnProfileDelete(d *schema.ResourceData, meta interface{}) error { //func resourceArmCdnProfileDelete(d *schema.ResourceData, meta interface{}) error {
cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient // cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["Profiles"] // name := id.Path["Profiles"]
//
_, err = cdnProfilesClient.DeleteIfExists(name, resGroup) // _, err = cdnProfilesClient.DeleteIfExists(name, resGroup)
//
return err // return err
} //}
//
func cdnProfileStateRefreshFunc(client *ArmClient, resourceGroupName string, cdnProfileName string) resource.StateRefreshFunc { //func cdnProfileStateRefreshFunc(client *ArmClient, resourceGroupName string, cdnProfileName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) { // return func() (interface{}, string, error) {
res, err := client.cdnProfilesClient.Get(cdnProfileName, resourceGroupName) // res, err := client.cdnProfilesClient.Get(cdnProfileName, resourceGroupName)
if err != nil { // if err != nil {
return nil, "", fmt.Errorf("Error issuing read request in cdnProfileStateRefreshFunc to Azure ARM for CND Profile '%s' (RG: '%s'): %s", cdnProfileName, resourceGroupName, err) // return nil, "", fmt.Errorf("Error issuing read request in cdnProfileStateRefreshFunc to Azure ARM for CND Profile '%s' (RG: '%s'): %s", cdnProfileName, resourceGroupName, err)
} // }
return res, string(res.Properties.ProvisioningState), nil // return res, string(res.Properties.ProvisioningState), nil
} // }
} //}
//
func validateCdnProfileSku(v interface{}, k string) (ws []string, errors []error) { //func validateCdnProfileSku(v interface{}, k string) (ws []string, errors []error) {
value := strings.ToLower(v.(string)) // value := strings.ToLower(v.(string))
skus := map[string]bool{ // skus := map[string]bool{
"standard": true, // "standard": true,
"premium": true, // "premium": true,
} // }
//
if !skus[value] { // if !skus[value] {
errors = append(errors, fmt.Errorf("CDN Profile SKU can only be Standard or Premium")) // errors = append(errors, fmt.Errorf("CDN Profile SKU can only be Standard or Premium"))
} // }
return // return
} //}

View File

@ -1,207 +1,207 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"net/http" // "net/http"
"testing" // "testing"
//
"github.com/hashicorp/terraform/helper/acctest" // "github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" // "github.com/hashicorp/terraform/terraform"
) //)
//
func TestResourceAzureRMCdnProfileSKU_validation(t *testing.T) { //func TestResourceAzureRMCdnProfileSKU_validation(t *testing.T) {
cases := []struct { // cases := []struct {
Value string // Value string
ErrCount int // ErrCount int
}{ // }{
{ // {
Value: "Random", // Value: "Random",
ErrCount: 1, // ErrCount: 1,
}, // },
{ // {
Value: "Standard", // Value: "Standard",
ErrCount: 0, // ErrCount: 0,
}, // },
{ // {
Value: "Premium", // Value: "Premium",
ErrCount: 0, // ErrCount: 0,
}, // },
{ // {
Value: "STANDARD", // Value: "STANDARD",
ErrCount: 0, // ErrCount: 0,
}, // },
{ // {
Value: "PREMIUM", // Value: "PREMIUM",
ErrCount: 0, // ErrCount: 0,
}, // },
} // }
//
for _, tc := range cases { // for _, tc := range cases {
_, errors := validateCdnProfileSku(tc.Value, "azurerm_cdn_profile") // _, errors := validateCdnProfileSku(tc.Value, "azurerm_cdn_profile")
//
if len(errors) != tc.ErrCount { // if len(errors) != tc.ErrCount {
t.Fatalf("Expected the Azure RM CDN Profile SKU to trigger a validation error") // t.Fatalf("Expected the Azure RM CDN Profile SKU to trigger a validation error")
} // }
} // }
} //}
//
func TestAccAzureRMCdnProfile_basic(t *testing.T) { //func TestAccAzureRMCdnProfile_basic(t *testing.T) {
//
ri := acctest.RandInt() // ri := acctest.RandInt()
config := fmt.Sprintf(testAccAzureRMCdnProfile_basic, ri, ri) // config := fmt.Sprintf(testAccAzureRMCdnProfile_basic, ri, ri)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMCdnProfileDestroy, // CheckDestroy: testCheckAzureRMCdnProfileDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: config, // Config: config,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"), // testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func TestAccAzureRMCdnProfile_withTags(t *testing.T) { //func TestAccAzureRMCdnProfile_withTags(t *testing.T) {
//
ri := acctest.RandInt() // ri := acctest.RandInt()
preConfig := fmt.Sprintf(testAccAzureRMCdnProfile_withTags, ri, ri) // preConfig := fmt.Sprintf(testAccAzureRMCdnProfile_withTags, ri, ri)
postConfig := fmt.Sprintf(testAccAzureRMCdnProfile_withTagsUpdate, ri, ri) // postConfig := fmt.Sprintf(testAccAzureRMCdnProfile_withTagsUpdate, ri, ri)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMCdnProfileDestroy, // CheckDestroy: testCheckAzureRMCdnProfileDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: preConfig, // Config: preConfig,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"), // testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_cdn_profile.test", "tags.#", "2"), // "azurerm_cdn_profile.test", "tags.#", "2"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_cdn_profile.test", "tags.environment", "Production"), // "azurerm_cdn_profile.test", "tags.environment", "Production"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_cdn_profile.test", "tags.cost_center", "MSFT"), // "azurerm_cdn_profile.test", "tags.cost_center", "MSFT"),
), // ),
}, // },
//
resource.TestStep{ // resource.TestStep{
Config: postConfig, // Config: postConfig,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"), // testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_cdn_profile.test", "tags.#", "1"), // "azurerm_cdn_profile.test", "tags.#", "1"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_cdn_profile.test", "tags.environment", "staging"), // "azurerm_cdn_profile.test", "tags.environment", "staging"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func testCheckAzureRMCdnProfileExists(name string) resource.TestCheckFunc { //func testCheckAzureRMCdnProfileExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error { // return func(s *terraform.State) error {
// Ensure we have enough information in state to look up in API // // Ensure we have enough information in state to look up in API
rs, ok := s.RootModule().Resources[name] // rs, ok := s.RootModule().Resources[name]
if !ok { // if !ok {
return fmt.Errorf("Not found: %s", name) // return fmt.Errorf("Not found: %s", name)
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
if !hasResourceGroup { // if !hasResourceGroup {
return fmt.Errorf("Bad: no resource group found in state for cdn profile: %s", name) // return fmt.Errorf("Bad: no resource group found in state for cdn profile: %s", name)
} // }
//
conn := testAccProvider.Meta().(*ArmClient).cdnProfilesClient // conn := testAccProvider.Meta().(*ArmClient).cdnProfilesClient
//
resp, err := conn.Get(name, resourceGroup) // resp, err := conn.Get(name, resourceGroup)
if err != nil { // if err != nil {
return fmt.Errorf("Bad: Get on cdnProfilesClient: %s", err) // return fmt.Errorf("Bad: Get on cdnProfilesClient: %s", err)
} // }
//
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("Bad: CDN Profile %q (resource group: %q) does not exist", name, resourceGroup) // return fmt.Errorf("Bad: CDN Profile %q (resource group: %q) does not exist", name, resourceGroup)
} // }
//
return nil // return nil
} // }
} //}
//
func testCheckAzureRMCdnProfileDestroy(s *terraform.State) error { //func testCheckAzureRMCdnProfileDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*ArmClient).cdnProfilesClient // conn := testAccProvider.Meta().(*ArmClient).cdnProfilesClient
//
for _, rs := range s.RootModule().Resources { // for _, rs := range s.RootModule().Resources {
if rs.Type != "azurerm_cdn_profile" { // if rs.Type != "azurerm_cdn_profile" {
continue // continue
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup := rs.Primary.Attributes["resource_group_name"]
//
resp, err := conn.Get(name, resourceGroup) // resp, err := conn.Get(name, resourceGroup)
//
if err != nil { // if err != nil {
return nil // return nil
} // }
//
if resp.StatusCode != http.StatusNotFound { // if resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("CDN Profile still exists:\n%#v", resp.Properties) // return fmt.Errorf("CDN Profile still exists:\n%#v", resp.Properties)
} // }
} // }
//
return nil // return nil
} //}
//
var testAccAzureRMCdnProfile_basic = ` //var testAccAzureRMCdnProfile_basic = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
resource "azurerm_cdn_profile" "test" { //resource "azurerm_cdn_profile" "test" {
name = "acctestcdnprof%d" // name = "acctestcdnprof%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
sku = "Standard" // sku = "Standard"
} //}
` //`
//
var testAccAzureRMCdnProfile_withTags = ` //var testAccAzureRMCdnProfile_withTags = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
resource "azurerm_cdn_profile" "test" { //resource "azurerm_cdn_profile" "test" {
name = "acctestcdnprof%d" // name = "acctestcdnprof%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
sku = "Standard" // sku = "Standard"
//
tags { // tags {
environment = "Production" // environment = "Production"
cost_center = "MSFT" // cost_center = "MSFT"
} // }
} //}
` //`
//
var testAccAzureRMCdnProfile_withTagsUpdate = ` //var testAccAzureRMCdnProfile_withTagsUpdate = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
resource "azurerm_cdn_profile" "test" { //resource "azurerm_cdn_profile" "test" {
name = "acctestcdnprof%d" // name = "acctestcdnprof%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
sku = "Standard" // sku = "Standard"
//
tags { // tags {
environment = "staging" // environment = "staging"
} // }
} //}
` //`

View File

@ -1,136 +1,136 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
//
"github.com/Azure/azure-sdk-for-go/arm/network" // "github.com/Azure/azure-sdk-for-go/arm/network"
"github.com/Azure/azure-sdk-for-go/core/http" // "github.com/Azure/azure-sdk-for-go/core/http"
"github.com/hashicorp/terraform/helper/schema" // "github.com/hashicorp/terraform/helper/schema"
) //)
//
func resourceArmLocalNetworkGateway() *schema.Resource { //func resourceArmLocalNetworkGateway() *schema.Resource {
return &schema.Resource{ // return &schema.Resource{
Create: resourceArmLocalNetworkGatewayCreate, // Create: resourceArmLocalNetworkGatewayCreate,
Read: resourceArmLocalNetworkGatewayRead, // Read: resourceArmLocalNetworkGatewayRead,
Update: resourceArmLocalNetworkGatewayCreate, // Update: resourceArmLocalNetworkGatewayCreate,
Delete: resourceArmLocalNetworkGatewayDelete, // Delete: resourceArmLocalNetworkGatewayDelete,
//
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"location": &schema.Schema{ // "location": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
ForceNew: true, // ForceNew: true,
StateFunc: azureRMNormalizeLocation, // StateFunc: azureRMNormalizeLocation,
}, // },
//
"resource_group_name": &schema.Schema{ // "resource_group_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"gateway_address": &schema.Schema{ // "gateway_address": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"address_space": &schema.Schema{ // "address_space": &schema.Schema{
Type: schema.TypeList, // Type: schema.TypeList,
Required: true, // Required: true,
Elem: &schema.Schema{ // Elem: &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
}, // },
}, // },
}, // },
} // }
} //}
//
func resourceArmLocalNetworkGatewayCreate(d *schema.ResourceData, meta interface{}) error { //func resourceArmLocalNetworkGatewayCreate(d *schema.ResourceData, meta interface{}) error {
lnetClient := meta.(*ArmClient).localNetConnClient // lnetClient := meta.(*ArmClient).localNetConnClient
//
name := d.Get("name").(string) // name := d.Get("name").(string)
location := d.Get("location").(string) // location := d.Get("location").(string)
resGroup := d.Get("resource_group_name").(string) // resGroup := d.Get("resource_group_name").(string)
ipAddress := d.Get("gateway_address").(string) // ipAddress := d.Get("gateway_address").(string)
//
// fetch the 'address_space_prefixes: // // fetch the 'address_space_prefixes:
prefixes := []string{} // prefixes := []string{}
for _, pref := range d.Get("address_space").([]interface{}) { // for _, pref := range d.Get("address_space").([]interface{}) {
prefixes = append(prefixes, pref.(string)) // prefixes = append(prefixes, pref.(string))
} // }
//
resp, err := lnetClient.CreateOrUpdate(resGroup, name, network.LocalNetworkGateway{ // resp, err := lnetClient.CreateOrUpdate(resGroup, name, network.LocalNetworkGateway{
Name: &name, // Name: &name,
Location: &location, // Location: &location,
Properties: &network.LocalNetworkGatewayPropertiesFormat{ // Properties: &network.LocalNetworkGatewayPropertiesFormat{
LocalNetworkAddressSpace: &network.AddressSpace{ // LocalNetworkAddressSpace: &network.AddressSpace{
AddressPrefixes: &prefixes, // AddressPrefixes: &prefixes,
}, // },
GatewayIPAddress: &ipAddress, // GatewayIPAddress: &ipAddress,
}, // },
}) // })
if err != nil { // if err != nil {
return fmt.Errorf("Error creating Azure ARM Local Network Gateway '%s': %s", name, err) // return fmt.Errorf("Error creating Azure ARM Local Network Gateway '%s': %s", name, err)
} // }
//
d.SetId(*resp.ID) // d.SetId(*resp.ID)
//
return resourceArmLocalNetworkGatewayRead(d, meta) // return resourceArmLocalNetworkGatewayRead(d, meta)
} //}
//
// resourceArmLocalNetworkGatewayRead goes ahead and reads the state of the corresponding ARM local network gateway. //// resourceArmLocalNetworkGatewayRead goes ahead and reads the state of the corresponding ARM local network gateway.
func resourceArmLocalNetworkGatewayRead(d *schema.ResourceData, meta interface{}) error { //func resourceArmLocalNetworkGatewayRead(d *schema.ResourceData, meta interface{}) error {
lnetClient := meta.(*ArmClient).localNetConnClient // lnetClient := meta.(*ArmClient).localNetConnClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
name := id.Path["localNetworkGateways"] // name := id.Path["localNetworkGateways"]
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
//
resp, err := lnetClient.Get(resGroup, name) // resp, err := lnetClient.Get(resGroup, name)
if err != nil { // if err != nil {
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
d.SetId("") // d.SetId("")
return nil // return nil
} // }
//
return fmt.Errorf("Error reading the state of Azure ARM local network gateway '%s': %s", name, err) // return fmt.Errorf("Error reading the state of Azure ARM local network gateway '%s': %s", name, err)
} // }
//
d.Set("gateway_address", resp.Properties.GatewayIPAddress) // d.Set("gateway_address", resp.Properties.GatewayIPAddress)
//
prefs := []string{} // prefs := []string{}
if ps := *resp.Properties.LocalNetworkAddressSpace.AddressPrefixes; ps != nil { // if ps := *resp.Properties.LocalNetworkAddressSpace.AddressPrefixes; ps != nil {
prefs = ps // prefs = ps
} // }
d.Set("address_space", prefs) // d.Set("address_space", prefs)
//
return nil // return nil
} //}
//
// resourceArmLocalNetworkGatewayDelete deletes the specified ARM local network gateway. //// resourceArmLocalNetworkGatewayDelete deletes the specified ARM local network gateway.
func resourceArmLocalNetworkGatewayDelete(d *schema.ResourceData, meta interface{}) error { //func resourceArmLocalNetworkGatewayDelete(d *schema.ResourceData, meta interface{}) error {
lnetClient := meta.(*ArmClient).localNetConnClient // lnetClient := meta.(*ArmClient).localNetConnClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
name := id.Path["localNetworkGateways"] // name := id.Path["localNetworkGateways"]
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
//
_, err = lnetClient.Delete(resGroup, name) // _, err = lnetClient.Delete(resGroup, name)
if err != nil { // if err != nil {
return fmt.Errorf("Error issuing Azure ARM delete request of local network gateway '%s': %s", name, err) // return fmt.Errorf("Error issuing Azure ARM delete request of local network gateway '%s': %s", name, err)
} // }
//
return nil // return nil
} //}

View File

@ -1,108 +1,108 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"testing" // "testing"
//
"github.com/Azure/azure-sdk-for-go/core/http" // "github.com/Azure/azure-sdk-for-go/core/http"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" // "github.com/hashicorp/terraform/terraform"
) //)
//
func TestAccAzureRMLocalNetworkGateway_basic(t *testing.T) { //func TestAccAzureRMLocalNetworkGateway_basic(t *testing.T) {
name := "azurerm_local_network_gateway.test" // name := "azurerm_local_network_gateway.test"
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMLocalNetworkGatewayDestroy, // CheckDestroy: testCheckAzureRMLocalNetworkGatewayDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: testAccAzureRMLocalNetworkGatewayConfig_basic, // Config: testAccAzureRMLocalNetworkGatewayConfig_basic,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMLocalNetworkGatewayExists(name), // testCheckAzureRMLocalNetworkGatewayExists(name),
resource.TestCheckResourceAttr(name, "gateway_address", "127.0.0.1"), // resource.TestCheckResourceAttr(name, "gateway_address", "127.0.0.1"),
resource.TestCheckResourceAttr(name, "address_space.0", "127.0.0.0/8"), // resource.TestCheckResourceAttr(name, "address_space.0", "127.0.0.0/8"),
), // ),
}, // },
}, // },
}) // })
} //}
//
// testCheckAzureRMLocalNetworkGatewayExists returns the resurce.TestCheckFunc //// testCheckAzureRMLocalNetworkGatewayExists returns the resurce.TestCheckFunc
// which checks whether or not the expected local network gateway exists both //// which checks whether or not the expected local network gateway exists both
// in the schema, and on Azure. //// in the schema, and on Azure.
func testCheckAzureRMLocalNetworkGatewayExists(name string) resource.TestCheckFunc { //func testCheckAzureRMLocalNetworkGatewayExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error { // return func(s *terraform.State) error {
// first check within the schema for the local network gateway: // // first check within the schema for the local network gateway:
res, ok := s.RootModule().Resources[name] // res, ok := s.RootModule().Resources[name]
if !ok { // if !ok {
return fmt.Errorf("Local network gateway '%s' not found.", name) // return fmt.Errorf("Local network gateway '%s' not found.", name)
} // }
//
// then, extract the name and the resource group: // // then, extract the name and the resource group:
id, err := parseAzureResourceID(res.Primary.ID) // id, err := parseAzureResourceID(res.Primary.ID)
if err != nil { // if err != nil {
return err // return err
} // }
localNetName := id.Path["localNetworkGateways"] // localNetName := id.Path["localNetworkGateways"]
resGrp := id.ResourceGroup // resGrp := id.ResourceGroup
//
// and finally, check that it exists on Azure: // // and finally, check that it exists on Azure:
lnetClient := testAccProvider.Meta().(*ArmClient).localNetConnClient // lnetClient := testAccProvider.Meta().(*ArmClient).localNetConnClient
//
resp, err := lnetClient.Get(resGrp, localNetName) // resp, err := lnetClient.Get(resGrp, localNetName)
if err != nil { // if err != nil {
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("Local network gateway '%s' (resource group '%s') does not exist on Azure.", localNetName, resGrp) // return fmt.Errorf("Local network gateway '%s' (resource group '%s') does not exist on Azure.", localNetName, resGrp)
} // }
//
return fmt.Errorf("Error reading the state of local network gateway '%s'.", localNetName) // return fmt.Errorf("Error reading the state of local network gateway '%s'.", localNetName)
} // }
//
return nil // return nil
} // }
} //}
//
func testCheckAzureRMLocalNetworkGatewayDestroy(s *terraform.State) error { //func testCheckAzureRMLocalNetworkGatewayDestroy(s *terraform.State) error {
for _, res := range s.RootModule().Resources { // for _, res := range s.RootModule().Resources {
if res.Type != "azurerm_local_network_gateway" { // if res.Type != "azurerm_local_network_gateway" {
continue // continue
} // }
//
id, err := parseAzureResourceID(res.Primary.ID) // id, err := parseAzureResourceID(res.Primary.ID)
if err != nil { // if err != nil {
return err // return err
} // }
localNetName := id.Path["localNetworkGateways"] // localNetName := id.Path["localNetworkGateways"]
resGrp := id.ResourceGroup // resGrp := id.ResourceGroup
//
lnetClient := testAccProvider.Meta().(*ArmClient).localNetConnClient // lnetClient := testAccProvider.Meta().(*ArmClient).localNetConnClient
resp, err := lnetClient.Get(resGrp, localNetName) // resp, err := lnetClient.Get(resGrp, localNetName)
//
if err != nil { // if err != nil {
return nil // return nil
} // }
//
if resp.StatusCode != http.StatusNotFound { // if resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("Local network gateway still exists:\n%#v", resp.Properties) // return fmt.Errorf("Local network gateway still exists:\n%#v", resp.Properties)
} // }
} // }
//
return nil // return nil
} //}
//
var testAccAzureRMLocalNetworkGatewayConfig_basic = ` //var testAccAzureRMLocalNetworkGatewayConfig_basic = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "tftestingResourceGroup" // name = "tftestingResourceGroup"
location = "West US" // location = "West US"
} //}
//
resource "azurerm_local_network_gateway" "test" { //resource "azurerm_local_network_gateway" "test" {
name = "tftestingLocalNetworkGateway" // name = "tftestingLocalNetworkGateway"
location = "${azurerm_resource_group.test.location}" // location = "${azurerm_resource_group.test.location}"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
gateway_address = "127.0.0.1" // gateway_address = "127.0.0.1"
address_space = ["127.0.0.0/8"] // address_space = ["127.0.0.0/8"]
} //}
` //`

View File

@ -1,431 +1,431 @@
package azurerm package azurerm
import ( //import (
"bytes" // "bytes"
"fmt" // "fmt"
"log" // "log"
"net/http" // "net/http"
"strings" // "strings"
"time" // "time"
//
"github.com/Azure/azure-sdk-for-go/arm/network" // "github.com/Azure/azure-sdk-for-go/arm/network"
"github.com/hashicorp/terraform/helper/hashcode" // "github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema" // "github.com/hashicorp/terraform/helper/schema"
) //)
//
func resourceArmNetworkInterface() *schema.Resource { //func resourceArmNetworkInterface() *schema.Resource {
return &schema.Resource{ // return &schema.Resource{
Create: resourceArmNetworkInterfaceCreate, // Create: resourceArmNetworkInterfaceCreate,
Read: resourceArmNetworkInterfaceRead, // Read: resourceArmNetworkInterfaceRead,
Update: resourceArmNetworkInterfaceCreate, // Update: resourceArmNetworkInterfaceCreate,
Delete: resourceArmNetworkInterfaceDelete, // Delete: resourceArmNetworkInterfaceDelete,
//
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"location": &schema.Schema{ // "location": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
StateFunc: azureRMNormalizeLocation, // StateFunc: azureRMNormalizeLocation,
}, // },
//
"resource_group_name": &schema.Schema{ // "resource_group_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"network_security_group_id": &schema.Schema{ // "network_security_group_id": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
}, // },
//
"mac_address": &schema.Schema{ // "mac_address": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
}, // },
//
"private_ip_address": &schema.Schema{ // "private_ip_address": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Computed: true, // Computed: true,
}, // },
//
"virtual_machine_id": &schema.Schema{ // "virtual_machine_id": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
}, // },
//
"ip_configuration": &schema.Schema{ // "ip_configuration": &schema.Schema{
Type: schema.TypeSet, // Type: schema.TypeSet,
Required: true, // Required: true,
Elem: &schema.Resource{ // Elem: &schema.Resource{
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"subnet_id": &schema.Schema{ // "subnet_id": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"private_ip_address": &schema.Schema{ // "private_ip_address": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
}, // },
//
"private_ip_address_allocation": &schema.Schema{ // "private_ip_address_allocation": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ValidateFunc: validateNetworkInterfacePrivateIpAddressAllocation, // ValidateFunc: validateNetworkInterfacePrivateIpAddressAllocation,
}, // },
//
"public_ip_address_id": &schema.Schema{ // "public_ip_address_id": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
}, // },
//
"load_balancer_backend_address_pools_ids": &schema.Schema{ // "load_balancer_backend_address_pools_ids": &schema.Schema{
Type: schema.TypeSet, // Type: schema.TypeSet,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
Elem: &schema.Schema{Type: schema.TypeString}, // Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString, // Set: schema.HashString,
}, // },
//
"load_balancer_inbound_nat_rules_ids": &schema.Schema{ // "load_balancer_inbound_nat_rules_ids": &schema.Schema{
Type: schema.TypeSet, // Type: schema.TypeSet,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
Elem: &schema.Schema{Type: schema.TypeString}, // Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString, // Set: schema.HashString,
}, // },
}, // },
}, // },
Set: resourceArmNetworkInterfaceIpConfigurationHash, // Set: resourceArmNetworkInterfaceIpConfigurationHash,
}, // },
//
"dns_servers": &schema.Schema{ // "dns_servers": &schema.Schema{
Type: schema.TypeSet, // Type: schema.TypeSet,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
Elem: &schema.Schema{Type: schema.TypeString}, // Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString, // Set: schema.HashString,
}, // },
//
"internal_dns_name_label": &schema.Schema{ // "internal_dns_name_label": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
}, // },
//
"applied_dns_servers": &schema.Schema{ // "applied_dns_servers": &schema.Schema{
Type: schema.TypeSet, // Type: schema.TypeSet,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
Elem: &schema.Schema{Type: schema.TypeString}, // Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString, // Set: schema.HashString,
}, // },
//
"internal_fqdn": &schema.Schema{ // "internal_fqdn": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
}, // },
//
"enable_ip_forwarding": &schema.Schema{ // "enable_ip_forwarding": &schema.Schema{
Type: schema.TypeBool, // Type: schema.TypeBool,
Optional: true, // Optional: true,
Default: false, // Default: false,
}, // },
//
"tags": tagsSchema(), // "tags": tagsSchema(),
}, // },
} // }
} //}
//
func resourceArmNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) error { //func resourceArmNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient) // client := meta.(*ArmClient)
ifaceClient := client.ifaceClient // ifaceClient := client.ifaceClient
//
log.Printf("[INFO] preparing arguments for Azure ARM Network Interface creation.") // log.Printf("[INFO] preparing arguments for Azure ARM Network Interface creation.")
//
name := d.Get("name").(string) // name := d.Get("name").(string)
location := d.Get("location").(string) // location := d.Get("location").(string)
resGroup := d.Get("resource_group_name").(string) // resGroup := d.Get("resource_group_name").(string)
enableIpForwarding := d.Get("enable_ip_forwarding").(bool) // enableIpForwarding := d.Get("enable_ip_forwarding").(bool)
tags := d.Get("tags").(map[string]interface{}) // tags := d.Get("tags").(map[string]interface{})
//
properties := network.InterfacePropertiesFormat{ // properties := network.InterfacePropertiesFormat{
EnableIPForwarding: &enableIpForwarding, // EnableIPForwarding: &enableIpForwarding,
} // }
//
if v, ok := d.GetOk("network_security_group_id"); ok { // if v, ok := d.GetOk("network_security_group_id"); ok {
nsgId := v.(string) // nsgId := v.(string)
properties.NetworkSecurityGroup = &network.SecurityGroup{ // properties.NetworkSecurityGroup = &network.SecurityGroup{
ID: &nsgId, // ID: &nsgId,
} // }
} // }
//
dns, hasDns := d.GetOk("dns_servers") // dns, hasDns := d.GetOk("dns_servers")
nameLabel, hasNameLabel := d.GetOk("internal_dns_name_label") // nameLabel, hasNameLabel := d.GetOk("internal_dns_name_label")
if hasDns || hasNameLabel { // if hasDns || hasNameLabel {
ifaceDnsSettings := network.InterfaceDNSSettings{} // ifaceDnsSettings := network.InterfaceDNSSettings{}
//
if hasDns { // if hasDns {
var dnsServers []string // var dnsServers []string
dns := dns.(*schema.Set).List() // dns := dns.(*schema.Set).List()
for _, v := range dns { // for _, v := range dns {
str := v.(string) // str := v.(string)
dnsServers = append(dnsServers, str) // dnsServers = append(dnsServers, str)
} // }
ifaceDnsSettings.DNSServers = &dnsServers // ifaceDnsSettings.DNSServers = &dnsServers
} // }
//
if hasNameLabel { // if hasNameLabel {
name_label := nameLabel.(string) // name_label := nameLabel.(string)
ifaceDnsSettings.InternalDNSNameLabel = &name_label // ifaceDnsSettings.InternalDNSNameLabel = &name_label
//
} // }
//
properties.DNSSettings = &ifaceDnsSettings // properties.DNSSettings = &ifaceDnsSettings
} // }
//
ipConfigs, sgErr := expandAzureRmNetworkInterfaceIpConfigurations(d) // ipConfigs, sgErr := expandAzureRmNetworkInterfaceIpConfigurations(d)
if sgErr != nil { // if sgErr != nil {
return fmt.Errorf("Error Building list of Network Interface IP Configurations: %s", sgErr) // return fmt.Errorf("Error Building list of Network Interface IP Configurations: %s", sgErr)
} // }
if len(ipConfigs) > 0 { // if len(ipConfigs) > 0 {
properties.IPConfigurations = &ipConfigs // properties.IPConfigurations = &ipConfigs
} // }
//
iface := network.Interface{ // iface := network.Interface{
Name: &name, // Name: &name,
Location: &location, // Location: &location,
Properties: &properties, // Properties: &properties,
Tags: expandTags(tags), // Tags: expandTags(tags),
} // }
//
resp, err := ifaceClient.CreateOrUpdate(resGroup, name, iface) // resp, err := ifaceClient.CreateOrUpdate(resGroup, name, iface)
if err != nil { // if err != nil {
return err // return err
} // }
//
d.SetId(*resp.ID) // d.SetId(*resp.ID)
//
log.Printf("[DEBUG] Waiting for Network Interface (%s) to become available", name) // log.Printf("[DEBUG] Waiting for Network Interface (%s) to become available", name)
stateConf := &resource.StateChangeConf{ // stateConf := &resource.StateChangeConf{
Pending: []string{"Accepted", "Updating"}, // Pending: []string{"Accepted", "Updating"},
Target: []string{"Succeeded"}, // Target: []string{"Succeeded"},
Refresh: networkInterfaceStateRefreshFunc(client, resGroup, name), // Refresh: networkInterfaceStateRefreshFunc(client, resGroup, name),
Timeout: 10 * time.Minute, // Timeout: 10 * time.Minute,
} // }
if _, err := stateConf.WaitForState(); err != nil { // if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Network Interface (%s) to become available: %s", name, err) // return fmt.Errorf("Error waiting for Network Interface (%s) to become available: %s", name, err)
} // }
//
return resourceArmNetworkInterfaceRead(d, meta) // return resourceArmNetworkInterfaceRead(d, meta)
} //}
//
func resourceArmNetworkInterfaceRead(d *schema.ResourceData, meta interface{}) error { //func resourceArmNetworkInterfaceRead(d *schema.ResourceData, meta interface{}) error {
ifaceClient := meta.(*ArmClient).ifaceClient // ifaceClient := meta.(*ArmClient).ifaceClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["networkInterfaces"] // name := id.Path["networkInterfaces"]
//
resp, err := ifaceClient.Get(resGroup, name, "") // resp, err := ifaceClient.Get(resGroup, name, "")
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
d.SetId("") // d.SetId("")
return nil // return nil
} // }
if err != nil { // if err != nil {
return fmt.Errorf("Error making Read request on Azure Network Interface %s: %s", name, err) // return fmt.Errorf("Error making Read request on Azure Network Interface %s: %s", name, err)
} // }
//
iface := *resp.Properties // iface := *resp.Properties
//
if iface.MacAddress != nil { // if iface.MacAddress != nil {
if *iface.MacAddress != "" { // if *iface.MacAddress != "" {
d.Set("mac_address", iface.MacAddress) // d.Set("mac_address", iface.MacAddress)
} // }
} // }
//
if iface.IPConfigurations != nil && len(*iface.IPConfigurations) > 0 { // if iface.IPConfigurations != nil && len(*iface.IPConfigurations) > 0 {
var privateIPAddress *string // var privateIPAddress *string
///TODO: Change this to a loop when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed // ///TODO: Change this to a loop when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed
if (*iface.IPConfigurations)[0].Properties != nil { // if (*iface.IPConfigurations)[0].Properties != nil {
privateIPAddress = (*iface.IPConfigurations)[0].Properties.PrivateIPAddress // privateIPAddress = (*iface.IPConfigurations)[0].Properties.PrivateIPAddress
} // }
//
if *privateIPAddress != "" { // if *privateIPAddress != "" {
d.Set("private_ip_address", *privateIPAddress) // d.Set("private_ip_address", *privateIPAddress)
} // }
} // }
//
if iface.VirtualMachine != nil { // if iface.VirtualMachine != nil {
if *iface.VirtualMachine.ID != "" { // if *iface.VirtualMachine.ID != "" {
d.Set("virtual_machine_id", *iface.VirtualMachine.ID) // d.Set("virtual_machine_id", *iface.VirtualMachine.ID)
} // }
} // }
//
if iface.DNSSettings != nil { // if iface.DNSSettings != nil {
if iface.DNSSettings.AppliedDNSServers != nil && len(*iface.DNSSettings.AppliedDNSServers) > 0 { // if iface.DNSSettings.AppliedDNSServers != nil && len(*iface.DNSSettings.AppliedDNSServers) > 0 {
dnsServers := make([]string, 0, len(*iface.DNSSettings.AppliedDNSServers)) // dnsServers := make([]string, 0, len(*iface.DNSSettings.AppliedDNSServers))
for _, dns := range *iface.DNSSettings.AppliedDNSServers { // for _, dns := range *iface.DNSSettings.AppliedDNSServers {
dnsServers = append(dnsServers, dns) // dnsServers = append(dnsServers, dns)
} // }
//
if err := d.Set("applied_dns_servers", dnsServers); err != nil { // if err := d.Set("applied_dns_servers", dnsServers); err != nil {
return err // return err
} // }
} // }
//
if iface.DNSSettings.InternalFqdn != nil && *iface.DNSSettings.InternalFqdn != "" { // if iface.DNSSettings.InternalFqdn != nil && *iface.DNSSettings.InternalFqdn != "" {
d.Set("internal_fqdn", iface.DNSSettings.InternalFqdn) // d.Set("internal_fqdn", iface.DNSSettings.InternalFqdn)
} // }
} // }
//
flattenAndSetTags(d, resp.Tags) // flattenAndSetTags(d, resp.Tags)
//
return nil // return nil
} //}
//
func resourceArmNetworkInterfaceDelete(d *schema.ResourceData, meta interface{}) error { //func resourceArmNetworkInterfaceDelete(d *schema.ResourceData, meta interface{}) error {
ifaceClient := meta.(*ArmClient).ifaceClient // ifaceClient := meta.(*ArmClient).ifaceClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["networkInterfaces"] // name := id.Path["networkInterfaces"]
//
_, err = ifaceClient.Delete(resGroup, name) // _, err = ifaceClient.Delete(resGroup, name)
//
return err // return err
} //}
//
func networkInterfaceStateRefreshFunc(client *ArmClient, resourceGroupName string, ifaceName string) resource.StateRefreshFunc { //func networkInterfaceStateRefreshFunc(client *ArmClient, resourceGroupName string, ifaceName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) { // return func() (interface{}, string, error) {
res, err := client.ifaceClient.Get(resourceGroupName, ifaceName, "") // res, err := client.ifaceClient.Get(resourceGroupName, ifaceName, "")
if err != nil { // if err != nil {
return nil, "", fmt.Errorf("Error issuing read request in networkInterfaceStateRefreshFunc to Azure ARM for network interace '%s' (RG: '%s'): %s", ifaceName, resourceGroupName, err) // return nil, "", fmt.Errorf("Error issuing read request in networkInterfaceStateRefreshFunc to Azure ARM for network interace '%s' (RG: '%s'): %s", ifaceName, resourceGroupName, err)
} // }
//
return res, *res.Properties.ProvisioningState, nil // return res, *res.Properties.ProvisioningState, nil
} // }
} //}
//
func resourceArmNetworkInterfaceIpConfigurationHash(v interface{}) int { //func resourceArmNetworkInterfaceIpConfigurationHash(v interface{}) int {
var buf bytes.Buffer // var buf bytes.Buffer
m := v.(map[string]interface{}) // m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["name"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["subnet_id"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["subnet_id"].(string)))
if m["private_ip_address"] != nil { // if m["private_ip_address"] != nil {
buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address"].(string)))
} // }
buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address_allocation"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address_allocation"].(string)))
if m["public_ip_address_id"] != nil { // if m["public_ip_address_id"] != nil {
buf.WriteString(fmt.Sprintf("%s-", m["public_ip_address_id"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["public_ip_address_id"].(string)))
} // }
//
return hashcode.String(buf.String()) // return hashcode.String(buf.String())
} //}
//
func validateNetworkInterfacePrivateIpAddressAllocation(v interface{}, k string) (ws []string, errors []error) { //func validateNetworkInterfacePrivateIpAddressAllocation(v interface{}, k string) (ws []string, errors []error) {
value := strings.ToLower(v.(string)) // value := strings.ToLower(v.(string))
allocations := map[string]bool{ // allocations := map[string]bool{
"static": true, // "static": true,
"dynamic": true, // "dynamic": true,
} // }
//
if !allocations[value] { // if !allocations[value] {
errors = append(errors, fmt.Errorf("Network Interface Allocations can only be Static or Dynamic")) // errors = append(errors, fmt.Errorf("Network Interface Allocations can only be Static or Dynamic"))
} // }
return // return
} //}
//
func expandAzureRmNetworkInterfaceIpConfigurations(d *schema.ResourceData) ([]network.InterfaceIPConfiguration, error) { //func expandAzureRmNetworkInterfaceIpConfigurations(d *schema.ResourceData) ([]network.InterfaceIPConfiguration, error) {
configs := d.Get("ip_configuration").(*schema.Set).List() // configs := d.Get("ip_configuration").(*schema.Set).List()
ipConfigs := make([]network.InterfaceIPConfiguration, 0, len(configs)) // ipConfigs := make([]network.InterfaceIPConfiguration, 0, len(configs))
//
for _, configRaw := range configs { // for _, configRaw := range configs {
data := configRaw.(map[string]interface{}) // data := configRaw.(map[string]interface{})
//
subnet_id := data["subnet_id"].(string) // subnet_id := data["subnet_id"].(string)
private_ip_allocation_method := data["private_ip_address_allocation"].(string) // private_ip_allocation_method := data["private_ip_address_allocation"].(string)
//
properties := network.InterfaceIPConfigurationPropertiesFormat{ // properties := network.InterfaceIPConfigurationPropertiesFormat{
Subnet: &network.Subnet{ // Subnet: &network.Subnet{
ID: &subnet_id, // ID: &subnet_id,
}, // },
PrivateIPAllocationMethod: &private_ip_allocation_method, // PrivateIPAllocationMethod: &private_ip_allocation_method,
} // }
//
if v := data["private_ip_address"].(string); v != "" { // if v := data["private_ip_address"].(string); v != "" {
properties.PrivateIPAddress = &v // properties.PrivateIPAddress = &v
} // }
//
if v := data["public_ip_address_id"].(string); v != "" { // if v := data["public_ip_address_id"].(string); v != "" {
properties.PublicIPAddress = &network.PublicIPAddress{ // properties.PublicIPAddress = &network.PublicIPAddress{
ID: &v, // ID: &v,
} // }
} // }
//
if v, ok := data["load_balancer_backend_address_pools_ids"]; ok { // if v, ok := data["load_balancer_backend_address_pools_ids"]; ok {
var ids []network.BackendAddressPool // var ids []network.BackendAddressPool
pools := v.(*schema.Set).List() // pools := v.(*schema.Set).List()
for _, p := range pools { // for _, p := range pools {
pool_id := p.(string) // pool_id := p.(string)
id := network.BackendAddressPool{ // id := network.BackendAddressPool{
ID: &pool_id, // ID: &pool_id,
} // }
//
ids = append(ids, id) // ids = append(ids, id)
} // }
//
properties.LoadBalancerBackendAddressPools = &ids // properties.LoadBalancerBackendAddressPools = &ids
} // }
//
if v, ok := data["load_balancer_inbound_nat_rules_ids"]; ok { // if v, ok := data["load_balancer_inbound_nat_rules_ids"]; ok {
var natRules []network.InboundNatRule // var natRules []network.InboundNatRule
rules := v.(*schema.Set).List() // rules := v.(*schema.Set).List()
for _, r := range rules { // for _, r := range rules {
rule_id := r.(string) // rule_id := r.(string)
rule := network.InboundNatRule{ // rule := network.InboundNatRule{
ID: &rule_id, // ID: &rule_id,
} // }
//
natRules = append(natRules, rule) // natRules = append(natRules, rule)
} // }
//
properties.LoadBalancerInboundNatRules = &natRules // properties.LoadBalancerInboundNatRules = &natRules
} // }
//
name := data["name"].(string) // name := data["name"].(string)
ipConfig := network.InterfaceIPConfiguration{ // ipConfig := network.InterfaceIPConfiguration{
Name: &name, // Name: &name,
Properties: &properties, // Properties: &properties,
} // }
//
ipConfigs = append(ipConfigs, ipConfig) // ipConfigs = append(ipConfigs, ipConfig)
} // }
//
return ipConfigs, nil // return ipConfigs, nil
} //}

View File

@ -1,86 +1,16 @@
package azurerm package azurerm
import ( //
"fmt" //import (
"net/http" // "fmt"
"testing" // "net/http"
// "testing"
"github.com/hashicorp/terraform/helper/resource" //
"github.com/hashicorp/terraform/terraform" // "github.com/hashicorp/terraform/helper/resource"
) // "github.com/hashicorp/terraform/terraform"
//)
func TestAccAzureRMNetworkInterface_basic(t *testing.T) { //
//func TestAccAzureRMNetworkInterface_basic(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAzureRMNetworkInterface_basic,
Check: resource.ComposeTestCheckFunc(
testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"),
),
},
},
})
}
func TestAccAzureRMNetworkInterfaceenableIPForwarding(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAzureRMNetworkInterface_ipForwarding,
Check: resource.ComposeTestCheckFunc(
testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"),
resource.TestCheckResourceAttr(
"azurerm_network_interface.test", "enable_ip_forwarding", "true"),
),
},
},
})
}
func TestAccAzureRMNetworkInterface_withTags(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAzureRMNetworkInterface_withTags,
Check: resource.ComposeTestCheckFunc(
testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"),
resource.TestCheckResourceAttr(
"azurerm_network_interface.test", "tags.#", "2"),
resource.TestCheckResourceAttr(
"azurerm_network_interface.test", "tags.environment", "Production"),
resource.TestCheckResourceAttr(
"azurerm_network_interface.test", "tags.cost_center", "MSFT"),
),
},
resource.TestStep{
Config: testAccAzureRMNetworkInterface_withTagsUpdate,
Check: resource.ComposeTestCheckFunc(
testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"),
resource.TestCheckResourceAttr(
"azurerm_network_interface.test", "tags.#", "1"),
resource.TestCheckResourceAttr(
"azurerm_network_interface.test", "tags.environment", "staging"),
),
},
},
})
}
///TODO: Re-enable this test when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed
//func TestAccAzureRMNetworkInterface_addingIpConfigurations(t *testing.T) {
// //
// resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
// PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
@ -91,221 +21,149 @@ func TestAccAzureRMNetworkInterface_withTags(t *testing.T) {
// Config: testAccAzureRMNetworkInterface_basic, // Config: testAccAzureRMNetworkInterface_basic,
// Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
// testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), // testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"),
// resource.TestCheckResourceAttr(
// "azurerm_network_interface.test", "ip_configuration.#", "1"),
// ),
// },
//
// resource.TestStep{
// Config: testAccAzureRMNetworkInterface_extraIpConfiguration,
// Check: resource.ComposeTestCheckFunc(
// testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"),
// resource.TestCheckResourceAttr(
// "azurerm_network_interface.test", "ip_configuration.#", "2"),
// ), // ),
// }, // },
// }, // },
// }) // })
//} //}
//
func testCheckAzureRMNetworkInterfaceExists(name string) resource.TestCheckFunc { //func TestAccAzureRMNetworkInterfaceenableIPForwarding(t *testing.T) {
return func(s *terraform.State) error { //
// Ensure we have enough information in state to look up in API // resource.Test(t, resource.TestCase{
rs, ok := s.RootModule().Resources[name] // PreCheck: func() { testAccPreCheck(t) },
if !ok { // Providers: testAccProviders,
return fmt.Errorf("Not found: %s", name) // CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy,
} // Steps: []resource.TestStep{
// resource.TestStep{
name := rs.Primary.Attributes["name"] // Config: testAccAzureRMNetworkInterface_ipForwarding,
resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] // Check: resource.ComposeTestCheckFunc(
if !hasResourceGroup { // testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"),
return fmt.Errorf("Bad: no resource group found in state for availability set: %s", name) // resource.TestCheckResourceAttr(
} // "azurerm_network_interface.test", "enable_ip_forwarding", "true"),
// ),
conn := testAccProvider.Meta().(*ArmClient).ifaceClient // },
// },
resp, err := conn.Get(resourceGroup, name, "") // })
if err != nil { //}
return fmt.Errorf("Bad: Get on ifaceClient: %s", err) //
} //func TestAccAzureRMNetworkInterface_withTags(t *testing.T) {
//
if resp.StatusCode == http.StatusNotFound { // resource.Test(t, resource.TestCase{
return fmt.Errorf("Bad: Network Interface %q (resource group: %q) does not exist", name, resourceGroup) // PreCheck: func() { testAccPreCheck(t) },
} // Providers: testAccProviders,
// CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy,
return nil // Steps: []resource.TestStep{
} // resource.TestStep{
} // Config: testAccAzureRMNetworkInterface_withTags,
// Check: resource.ComposeTestCheckFunc(
func testCheckAzureRMNetworkInterfaceDestroy(s *terraform.State) error { // testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"),
conn := testAccProvider.Meta().(*ArmClient).ifaceClient // resource.TestCheckResourceAttr(
// "azurerm_network_interface.test", "tags.#", "2"),
for _, rs := range s.RootModule().Resources { // resource.TestCheckResourceAttr(
if rs.Type != "azurerm_network_interface" { // "azurerm_network_interface.test", "tags.environment", "Production"),
continue // resource.TestCheckResourceAttr(
} // "azurerm_network_interface.test", "tags.cost_center", "MSFT"),
// ),
name := rs.Primary.Attributes["name"] // },
resourceGroup := rs.Primary.Attributes["resource_group_name"] //
// resource.TestStep{
resp, err := conn.Get(resourceGroup, name, "") // Config: testAccAzureRMNetworkInterface_withTagsUpdate,
// Check: resource.ComposeTestCheckFunc(
if err != nil { // testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"),
return nil // resource.TestCheckResourceAttr(
} // "azurerm_network_interface.test", "tags.#", "1"),
// resource.TestCheckResourceAttr(
if resp.StatusCode != http.StatusNotFound { // "azurerm_network_interface.test", "tags.environment", "staging"),
return fmt.Errorf("Network Interface still exists:\n%#v", resp.Properties) // ),
} // },
} // },
// })
return nil //}
} //
/////TODO: Re-enable this test when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed
var testAccAzureRMNetworkInterface_basic = ` ////func TestAccAzureRMNetworkInterface_addingIpConfigurations(t *testing.T) {
resource "azurerm_resource_group" "test" { ////
name = "acceptanceTestResourceGroup1" //// resource.Test(t, resource.TestCase{
location = "West US" //// PreCheck: func() { testAccPreCheck(t) },
} //// Providers: testAccProviders,
//// CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy,
resource "azurerm_virtual_network" "test" { //// Steps: []resource.TestStep{
name = "acceptanceTestVirtualNetwork1" //// resource.TestStep{
address_space = ["10.0.0.0/16"] //// Config: testAccAzureRMNetworkInterface_basic,
location = "West US" //// Check: resource.ComposeTestCheckFunc(
resource_group_name = "${azurerm_resource_group.test.name}" //// testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"),
} //// resource.TestCheckResourceAttr(
//// "azurerm_network_interface.test", "ip_configuration.#", "1"),
resource "azurerm_subnet" "test" { //// ),
name = "testsubnet" //// },
resource_group_name = "${azurerm_resource_group.test.name}" ////
virtual_network_name = "${azurerm_virtual_network.test.name}" //// resource.TestStep{
address_prefix = "10.0.2.0/24" //// Config: testAccAzureRMNetworkInterface_extraIpConfiguration,
} //// Check: resource.ComposeTestCheckFunc(
//// testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"),
resource "azurerm_network_interface" "test" { //// resource.TestCheckResourceAttr(
name = "acceptanceTestNetworkInterface1" //// "azurerm_network_interface.test", "ip_configuration.#", "2"),
location = "West US" //// ),
resource_group_name = "${azurerm_resource_group.test.name}" //// },
//// },
ip_configuration { //// })
name = "testconfiguration1" ////}
subnet_id = "${azurerm_subnet.test.id}" //
private_ip_address_allocation = "dynamic" //func testCheckAzureRMNetworkInterfaceExists(name string) resource.TestCheckFunc {
} // return func(s *terraform.State) error {
} // // Ensure we have enough information in state to look up in API
` // rs, ok := s.RootModule().Resources[name]
// if !ok {
var testAccAzureRMNetworkInterface_ipForwarding = ` // return fmt.Errorf("Not found: %s", name)
resource "azurerm_resource_group" "test" { // }
name = "acceptanceTestResourceGroup1" //
location = "West US" // name := rs.Primary.Attributes["name"]
} // resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
// if !hasResourceGroup {
resource "azurerm_virtual_network" "test" { // return fmt.Errorf("Bad: no resource group found in state for availability set: %s", name)
name = "acceptanceTestVirtualNetwork1" // }
address_space = ["10.0.0.0/16"] //
location = "West US" // conn := testAccProvider.Meta().(*ArmClient).ifaceClient
resource_group_name = "${azurerm_resource_group.test.name}" //
} // resp, err := conn.Get(resourceGroup, name, "")
// if err != nil {
resource "azurerm_subnet" "test" { // return fmt.Errorf("Bad: Get on ifaceClient: %s", err)
name = "testsubnet" // }
resource_group_name = "${azurerm_resource_group.test.name}" //
virtual_network_name = "${azurerm_virtual_network.test.name}" // if resp.StatusCode == http.StatusNotFound {
address_prefix = "10.0.2.0/24" // return fmt.Errorf("Bad: Network Interface %q (resource group: %q) does not exist", name, resourceGroup)
} // }
//
resource "azurerm_network_interface" "test" { // return nil
name = "acceptanceTestNetworkInterface1" // }
location = "West US" //}
resource_group_name = "${azurerm_resource_group.test.name}" //
enable_ip_forwarding = true //func testCheckAzureRMNetworkInterfaceDestroy(s *terraform.State) error {
// conn := testAccProvider.Meta().(*ArmClient).ifaceClient
ip_configuration { //
name = "testconfiguration1" // for _, rs := range s.RootModule().Resources {
subnet_id = "${azurerm_subnet.test.id}" // if rs.Type != "azurerm_network_interface" {
private_ip_address_allocation = "dynamic" // continue
} // }
} //
` // name := rs.Primary.Attributes["name"]
// resourceGroup := rs.Primary.Attributes["resource_group_name"]
var testAccAzureRMNetworkInterface_withTags = ` //
resource "azurerm_resource_group" "test" { // resp, err := conn.Get(resourceGroup, name, "")
name = "acceptanceTestResourceGroup1" //
location = "West US" // if err != nil {
} // return nil
// }
resource "azurerm_virtual_network" "test" { //
name = "acceptanceTestVirtualNetwork1" // if resp.StatusCode != http.StatusNotFound {
address_space = ["10.0.0.0/16"] // return fmt.Errorf("Network Interface still exists:\n%#v", resp.Properties)
location = "West US" // }
resource_group_name = "${azurerm_resource_group.test.name}" // }
} //
// return nil
resource "azurerm_subnet" "test" { //}
name = "testsubnet" //
resource_group_name = "${azurerm_resource_group.test.name}" //var testAccAzureRMNetworkInterface_basic = `
virtual_network_name = "${azurerm_virtual_network.test.name}"
address_prefix = "10.0.2.0/24"
}
resource "azurerm_network_interface" "test" {
name = "acceptanceTestNetworkInterface1"
location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}"
ip_configuration {
name = "testconfiguration1"
subnet_id = "${azurerm_subnet.test.id}"
private_ip_address_allocation = "dynamic"
}
tags {
environment = "Production"
cost_center = "MSFT"
}
}
`
var testAccAzureRMNetworkInterface_withTagsUpdate = `
resource "azurerm_resource_group" "test" {
name = "acceptanceTestResourceGroup1"
location = "West US"
}
resource "azurerm_virtual_network" "test" {
name = "acceptanceTestVirtualNetwork1"
address_space = ["10.0.0.0/16"]
location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}"
}
resource "azurerm_subnet" "test" {
name = "testsubnet"
resource_group_name = "${azurerm_resource_group.test.name}"
virtual_network_name = "${azurerm_virtual_network.test.name}"
address_prefix = "10.0.2.0/24"
}
resource "azurerm_network_interface" "test" {
name = "acceptanceTestNetworkInterface1"
location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}"
ip_configuration {
name = "testconfiguration1"
subnet_id = "${azurerm_subnet.test.id}"
private_ip_address_allocation = "dynamic"
}
tags {
environment = "staging"
}
}
`
//TODO: Re-enable this test when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed
//var testAccAzureRMNetworkInterface_extraIpConfiguration = `
//resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
// name = "acceptanceTestResourceGroup1" // name = "acceptanceTestResourceGroup1"
// location = "West US" // location = "West US"
@ -325,11 +183,71 @@ resource "azurerm_network_interface" "test" {
// address_prefix = "10.0.2.0/24" // address_prefix = "10.0.2.0/24"
//} //}
// //
//resource "azurerm_subnet" "test1" { //resource "azurerm_network_interface" "test" {
// name = "testsubnet1" // name = "acceptanceTestNetworkInterface1"
// location = "West US"
// resource_group_name = "${azurerm_resource_group.test.name}"
//
// ip_configuration {
// name = "testconfiguration1"
// subnet_id = "${azurerm_subnet.test.id}"
// private_ip_address_allocation = "dynamic"
// }
//}
//`
//
//var testAccAzureRMNetworkInterface_ipForwarding = `
//resource "azurerm_resource_group" "test" {
// name = "acceptanceTestResourceGroup1"
// location = "West US"
//}
//
//resource "azurerm_virtual_network" "test" {
// name = "acceptanceTestVirtualNetwork1"
// address_space = ["10.0.0.0/16"]
// location = "West US"
// resource_group_name = "${azurerm_resource_group.test.name}"
//}
//
//resource "azurerm_subnet" "test" {
// name = "testsubnet"
// resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
// virtual_network_name = "${azurerm_virtual_network.test.name}" // virtual_network_name = "${azurerm_virtual_network.test.name}"
// address_prefix = "10.0.1.0/24" // address_prefix = "10.0.2.0/24"
//}
//
//resource "azurerm_network_interface" "test" {
// name = "acceptanceTestNetworkInterface1"
// location = "West US"
// resource_group_name = "${azurerm_resource_group.test.name}"
// enable_ip_forwarding = true
//
// ip_configuration {
// name = "testconfiguration1"
// subnet_id = "${azurerm_subnet.test.id}"
// private_ip_address_allocation = "dynamic"
// }
//}
//`
//
//var testAccAzureRMNetworkInterface_withTags = `
//resource "azurerm_resource_group" "test" {
// name = "acceptanceTestResourceGroup1"
// location = "West US"
//}
//
//resource "azurerm_virtual_network" "test" {
// name = "acceptanceTestVirtualNetwork1"
// address_space = ["10.0.0.0/16"]
// location = "West US"
// resource_group_name = "${azurerm_resource_group.test.name}"
//}
//
//resource "azurerm_subnet" "test" {
// name = "testsubnet"
// resource_group_name = "${azurerm_resource_group.test.name}"
// virtual_network_name = "${azurerm_virtual_network.test.name}"
// address_prefix = "10.0.2.0/24"
//} //}
// //
//resource "azurerm_network_interface" "test" { //resource "azurerm_network_interface" "test" {
@ -343,11 +261,94 @@ resource "azurerm_network_interface" "test" {
// private_ip_address_allocation = "dynamic" // private_ip_address_allocation = "dynamic"
// } // }
// //
// ip_configuration { // tags {
// name = "testconfiguration2" // environment = "Production"
// subnet_id = "${azurerm_subnet.test1.id}" // cost_center = "MSFT"
// private_ip_address_allocation = "dynamic"
// primary = true
// } // }
//} //}
//` //`
//
//var testAccAzureRMNetworkInterface_withTagsUpdate = `
//resource "azurerm_resource_group" "test" {
// name = "acceptanceTestResourceGroup1"
// location = "West US"
//}
//
//resource "azurerm_virtual_network" "test" {
// name = "acceptanceTestVirtualNetwork1"
// address_space = ["10.0.0.0/16"]
// location = "West US"
// resource_group_name = "${azurerm_resource_group.test.name}"
//}
//
//resource "azurerm_subnet" "test" {
// name = "testsubnet"
// resource_group_name = "${azurerm_resource_group.test.name}"
// virtual_network_name = "${azurerm_virtual_network.test.name}"
// address_prefix = "10.0.2.0/24"
//}
//
//resource "azurerm_network_interface" "test" {
// name = "acceptanceTestNetworkInterface1"
// location = "West US"
// resource_group_name = "${azurerm_resource_group.test.name}"
//
// ip_configuration {
// name = "testconfiguration1"
// subnet_id = "${azurerm_subnet.test.id}"
// private_ip_address_allocation = "dynamic"
// }
//
// tags {
// environment = "staging"
// }
//}
//`
//
////TODO: Re-enable this test when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed
////var testAccAzureRMNetworkInterface_extraIpConfiguration = `
////resource "azurerm_resource_group" "test" {
//// name = "acceptanceTestResourceGroup1"
//// location = "West US"
////}
////
////resource "azurerm_virtual_network" "test" {
//// name = "acceptanceTestVirtualNetwork1"
//// address_space = ["10.0.0.0/16"]
//// location = "West US"
//// resource_group_name = "${azurerm_resource_group.test.name}"
////}
////
////resource "azurerm_subnet" "test" {
//// name = "testsubnet"
//// resource_group_name = "${azurerm_resource_group.test.name}"
//// virtual_network_name = "${azurerm_virtual_network.test.name}"
//// address_prefix = "10.0.2.0/24"
////}
////
////resource "azurerm_subnet" "test1" {
//// name = "testsubnet1"
//// resource_group_name = "${azurerm_resource_group.test.name}"
//// virtual_network_name = "${azurerm_virtual_network.test.name}"
//// address_prefix = "10.0.1.0/24"
////}
////
////resource "azurerm_network_interface" "test" {
//// name = "acceptanceTestNetworkInterface1"
//// location = "West US"
//// resource_group_name = "${azurerm_resource_group.test.name}"
////
//// ip_configuration {
//// name = "testconfiguration1"
//// subnet_id = "${azurerm_subnet.test.id}"
//// private_ip_address_allocation = "dynamic"
//// }
////
//// ip_configuration {
//// name = "testconfiguration2"
//// subnet_id = "${azurerm_subnet.test1.id}"
//// private_ip_address_allocation = "dynamic"
//// primary = true
//// }
////}
////`

View File

@ -1,301 +1,301 @@
package azurerm package azurerm
import ( //import (
"bytes" // "bytes"
"fmt" // "fmt"
"log" // "log"
"net/http" // "net/http"
"time" // "time"
//
"github.com/Azure/azure-sdk-for-go/arm/network" // "github.com/Azure/azure-sdk-for-go/arm/network"
"github.com/hashicorp/terraform/helper/hashcode" // "github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema" // "github.com/hashicorp/terraform/helper/schema"
) //)
//
func resourceArmNetworkSecurityGroup() *schema.Resource { //func resourceArmNetworkSecurityGroup() *schema.Resource {
return &schema.Resource{ // return &schema.Resource{
Create: resourceArmNetworkSecurityGroupCreate, // Create: resourceArmNetworkSecurityGroupCreate,
Read: resourceArmNetworkSecurityGroupRead, // Read: resourceArmNetworkSecurityGroupRead,
Update: resourceArmNetworkSecurityGroupCreate, // Update: resourceArmNetworkSecurityGroupCreate,
Delete: resourceArmNetworkSecurityGroupDelete, // Delete: resourceArmNetworkSecurityGroupDelete,
//
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"location": &schema.Schema{ // "location": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
StateFunc: azureRMNormalizeLocation, // StateFunc: azureRMNormalizeLocation,
}, // },
//
"resource_group_name": &schema.Schema{ // "resource_group_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"security_rule": &schema.Schema{ // "security_rule": &schema.Schema{
Type: schema.TypeSet, // Type: schema.TypeSet,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
Elem: &schema.Resource{ // Elem: &schema.Resource{
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"description": &schema.Schema{ // "description": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { // ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := v.(string) // value := v.(string)
if len(value) > 140 { // if len(value) > 140 {
errors = append(errors, fmt.Errorf( // errors = append(errors, fmt.Errorf(
"The network security rule description can be no longer than 140 chars")) // "The network security rule description can be no longer than 140 chars"))
} // }
return // return
}, // },
}, // },
//
"protocol": &schema.Schema{ // "protocol": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ValidateFunc: validateNetworkSecurityRuleProtocol, // ValidateFunc: validateNetworkSecurityRuleProtocol,
}, // },
//
"source_port_range": &schema.Schema{ // "source_port_range": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"destination_port_range": &schema.Schema{ // "destination_port_range": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"source_address_prefix": &schema.Schema{ // "source_address_prefix": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"destination_address_prefix": &schema.Schema{ // "destination_address_prefix": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"access": &schema.Schema{ // "access": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ValidateFunc: validateNetworkSecurityRuleAccess, // ValidateFunc: validateNetworkSecurityRuleAccess,
}, // },
//
"priority": &schema.Schema{ // "priority": &schema.Schema{
Type: schema.TypeInt, // Type: schema.TypeInt,
Required: true, // Required: true,
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { // ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := v.(int) // value := v.(int)
if value < 100 || value > 4096 { // if value < 100 || value > 4096 {
errors = append(errors, fmt.Errorf( // errors = append(errors, fmt.Errorf(
"The `priority` can only be between 100 and 4096")) // "The `priority` can only be between 100 and 4096"))
} // }
return // return
}, // },
}, // },
//
"direction": &schema.Schema{ // "direction": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ValidateFunc: validateNetworkSecurityRuleDirection, // ValidateFunc: validateNetworkSecurityRuleDirection,
}, // },
}, // },
}, // },
Set: resourceArmNetworkSecurityGroupRuleHash, // Set: resourceArmNetworkSecurityGroupRuleHash,
}, // },
//
"tags": tagsSchema(), // "tags": tagsSchema(),
}, // },
} // }
} //}
//
func resourceArmNetworkSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error { //func resourceArmNetworkSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient) // client := meta.(*ArmClient)
secClient := client.secGroupClient // secClient := client.secGroupClient
//
name := d.Get("name").(string) // name := d.Get("name").(string)
location := d.Get("location").(string) // location := d.Get("location").(string)
resGroup := d.Get("resource_group_name").(string) // resGroup := d.Get("resource_group_name").(string)
tags := d.Get("tags").(map[string]interface{}) // tags := d.Get("tags").(map[string]interface{})
//
sgRules, sgErr := expandAzureRmSecurityRules(d) // sgRules, sgErr := expandAzureRmSecurityRules(d)
if sgErr != nil { // if sgErr != nil {
return fmt.Errorf("Error Building list of Network Security Group Rules: %s", sgErr) // return fmt.Errorf("Error Building list of Network Security Group Rules: %s", sgErr)
} // }
//
sg := network.SecurityGroup{ // sg := network.SecurityGroup{
Name: &name, // Name: &name,
Location: &location, // Location: &location,
Properties: &network.SecurityGroupPropertiesFormat{ // Properties: &network.SecurityGroupPropertiesFormat{
SecurityRules: &sgRules, // SecurityRules: &sgRules,
}, // },
Tags: expandTags(tags), // Tags: expandTags(tags),
} // }
//
resp, err := secClient.CreateOrUpdate(resGroup, name, sg) // resp, err := secClient.CreateOrUpdate(resGroup, name, sg)
if err != nil { // if err != nil {
return err // return err
} // }
//
d.SetId(*resp.ID) // d.SetId(*resp.ID)
//
log.Printf("[DEBUG] Waiting for Network Security Group (%s) to become available", name) // log.Printf("[DEBUG] Waiting for Network Security Group (%s) to become available", name)
stateConf := &resource.StateChangeConf{ // stateConf := &resource.StateChangeConf{
Pending: []string{"Accepted", "Updating"}, // Pending: []string{"Accepted", "Updating"},
Target: []string{"Succeeded"}, // Target: []string{"Succeeded"},
Refresh: securityGroupStateRefreshFunc(client, resGroup, name), // Refresh: securityGroupStateRefreshFunc(client, resGroup, name),
Timeout: 10 * time.Minute, // Timeout: 10 * time.Minute,
} // }
if _, err := stateConf.WaitForState(); err != nil { // if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Network Securty Group (%s) to become available: %s", name, err) // return fmt.Errorf("Error waiting for Network Securty Group (%s) to become available: %s", name, err)
} // }
//
return resourceArmNetworkSecurityGroupRead(d, meta) // return resourceArmNetworkSecurityGroupRead(d, meta)
} //}
//
func resourceArmNetworkSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { //func resourceArmNetworkSecurityGroupRead(d *schema.ResourceData, meta interface{}) error {
secGroupClient := meta.(*ArmClient).secGroupClient // secGroupClient := meta.(*ArmClient).secGroupClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["networkSecurityGroups"] // name := id.Path["networkSecurityGroups"]
//
resp, err := secGroupClient.Get(resGroup, name, "") // resp, err := secGroupClient.Get(resGroup, name, "")
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
d.SetId("") // d.SetId("")
return nil // return nil
} // }
if err != nil { // if err != nil {
return fmt.Errorf("Error making Read request on Azure Network Security Group %s: %s", name, err) // return fmt.Errorf("Error making Read request on Azure Network Security Group %s: %s", name, err)
} // }
//
if resp.Properties.SecurityRules != nil { // if resp.Properties.SecurityRules != nil {
d.Set("security_rule", flattenNetworkSecurityRules(resp.Properties.SecurityRules)) // d.Set("security_rule", flattenNetworkSecurityRules(resp.Properties.SecurityRules))
} // }
//
flattenAndSetTags(d, resp.Tags) // flattenAndSetTags(d, resp.Tags)
//
return nil // return nil
} //}
//
func resourceArmNetworkSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error { //func resourceArmNetworkSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error {
secGroupClient := meta.(*ArmClient).secGroupClient // secGroupClient := meta.(*ArmClient).secGroupClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["networkSecurityGroups"] // name := id.Path["networkSecurityGroups"]
//
_, err = secGroupClient.Delete(resGroup, name) // _, err = secGroupClient.Delete(resGroup, name)
//
return err // return err
} //}
//
func resourceArmNetworkSecurityGroupRuleHash(v interface{}) int { //func resourceArmNetworkSecurityGroupRuleHash(v interface{}) int {
var buf bytes.Buffer // var buf bytes.Buffer
m := v.(map[string]interface{}) // m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["protocol"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["protocol"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["source_port_range"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["source_port_range"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["destination_port_range"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["destination_port_range"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["source_address_prefix"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["source_address_prefix"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["destination_address_prefix"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["destination_address_prefix"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["access"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["access"].(string)))
buf.WriteString(fmt.Sprintf("%d-", m["priority"].(int))) // buf.WriteString(fmt.Sprintf("%d-", m["priority"].(int)))
buf.WriteString(fmt.Sprintf("%s-", m["direction"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["direction"].(string)))
//
return hashcode.String(buf.String()) // return hashcode.String(buf.String())
} //}
//
func securityGroupStateRefreshFunc(client *ArmClient, resourceGroupName string, securityGroupName string) resource.StateRefreshFunc { //func securityGroupStateRefreshFunc(client *ArmClient, resourceGroupName string, securityGroupName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) { // return func() (interface{}, string, error) {
res, err := client.secGroupClient.Get(resourceGroupName, securityGroupName, "") // res, err := client.secGroupClient.Get(resourceGroupName, securityGroupName, "")
if err != nil { // if err != nil {
return nil, "", fmt.Errorf("Error issuing read request in securityGroupStateRefreshFunc to Azure ARM for network security group '%s' (RG: '%s'): %s", securityGroupName, resourceGroupName, err) // return nil, "", fmt.Errorf("Error issuing read request in securityGroupStateRefreshFunc to Azure ARM for network security group '%s' (RG: '%s'): %s", securityGroupName, resourceGroupName, err)
} // }
//
return res, *res.Properties.ProvisioningState, nil // return res, *res.Properties.ProvisioningState, nil
} // }
} //}
//
func flattenNetworkSecurityRules(rules *[]network.SecurityRule) []map[string]interface{} { //func flattenNetworkSecurityRules(rules *[]network.SecurityRule) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(*rules)) // result := make([]map[string]interface{}, 0, len(*rules))
for _, rule := range *rules { // for _, rule := range *rules {
sgRule := make(map[string]interface{}) // sgRule := make(map[string]interface{})
sgRule["name"] = *rule.Name // sgRule["name"] = *rule.Name
sgRule["destination_address_prefix"] = *rule.Properties.DestinationAddressPrefix // sgRule["destination_address_prefix"] = *rule.Properties.DestinationAddressPrefix
sgRule["destination_port_range"] = *rule.Properties.DestinationPortRange // sgRule["destination_port_range"] = *rule.Properties.DestinationPortRange
sgRule["source_address_prefix"] = *rule.Properties.SourceAddressPrefix // sgRule["source_address_prefix"] = *rule.Properties.SourceAddressPrefix
sgRule["source_port_range"] = *rule.Properties.SourcePortRange // sgRule["source_port_range"] = *rule.Properties.SourcePortRange
sgRule["priority"] = int(*rule.Properties.Priority) // sgRule["priority"] = int(*rule.Properties.Priority)
sgRule["access"] = rule.Properties.Access // sgRule["access"] = rule.Properties.Access
sgRule["direction"] = rule.Properties.Direction // sgRule["direction"] = rule.Properties.Direction
sgRule["protocol"] = rule.Properties.Protocol // sgRule["protocol"] = rule.Properties.Protocol
//
if rule.Properties.Description != nil { // if rule.Properties.Description != nil {
sgRule["description"] = *rule.Properties.Description // sgRule["description"] = *rule.Properties.Description
} // }
//
result = append(result, sgRule) // result = append(result, sgRule)
} // }
return result // return result
} //}
//
func expandAzureRmSecurityRules(d *schema.ResourceData) ([]network.SecurityRule, error) { //func expandAzureRmSecurityRules(d *schema.ResourceData) ([]network.SecurityRule, error) {
sgRules := d.Get("security_rule").(*schema.Set).List() // sgRules := d.Get("security_rule").(*schema.Set).List()
rules := make([]network.SecurityRule, 0, len(sgRules)) // rules := make([]network.SecurityRule, 0, len(sgRules))
//
for _, sgRaw := range sgRules { // for _, sgRaw := range sgRules {
data := sgRaw.(map[string]interface{}) // data := sgRaw.(map[string]interface{})
//
source_port_range := data["source_port_range"].(string) // source_port_range := data["source_port_range"].(string)
destination_port_range := data["destination_port_range"].(string) // destination_port_range := data["destination_port_range"].(string)
source_address_prefix := data["source_address_prefix"].(string) // source_address_prefix := data["source_address_prefix"].(string)
destination_address_prefix := data["destination_address_prefix"].(string) // destination_address_prefix := data["destination_address_prefix"].(string)
priority := data["priority"].(int) // priority := data["priority"].(int)
//
properties := network.SecurityRulePropertiesFormat{ // properties := network.SecurityRulePropertiesFormat{
SourcePortRange: &source_port_range, // SourcePortRange: &source_port_range,
DestinationPortRange: &destination_port_range, // DestinationPortRange: &destination_port_range,
SourceAddressPrefix: &source_address_prefix, // SourceAddressPrefix: &source_address_prefix,
DestinationAddressPrefix: &destination_address_prefix, // DestinationAddressPrefix: &destination_address_prefix,
Priority: &priority, // Priority: &priority,
Access: network.SecurityRuleAccess(data["access"].(string)), // Access: network.SecurityRuleAccess(data["access"].(string)),
Direction: network.SecurityRuleDirection(data["direction"].(string)), // Direction: network.SecurityRuleDirection(data["direction"].(string)),
Protocol: network.SecurityRuleProtocol(data["protocol"].(string)), // Protocol: network.SecurityRuleProtocol(data["protocol"].(string)),
} // }
//
if v := data["description"].(string); v != "" { // if v := data["description"].(string); v != "" {
properties.Description = &v // properties.Description = &v
} // }
//
name := data["name"].(string) // name := data["name"].(string)
rule := network.SecurityRule{ // rule := network.SecurityRule{
Name: &name, // Name: &name,
Properties: &properties, // Properties: &properties,
} // }
//
rules = append(rules, rule) // rules = append(rules, rule)
} // }
//
return rules, nil // return rules, nil
} //}

View File

@ -1,265 +1,265 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"net/http" // "net/http"
"testing" // "testing"
//
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" // "github.com/hashicorp/terraform/terraform"
) //)
//
func TestAccAzureRMNetworkSecurityGroup_basic(t *testing.T) { //func TestAccAzureRMNetworkSecurityGroup_basic(t *testing.T) {
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy, // CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: testAccAzureRMNetworkSecurityGroup_basic, // Config: testAccAzureRMNetworkSecurityGroup_basic,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), // testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func TestAccAzureRMNetworkSecurityGroup_withTags(t *testing.T) { //func TestAccAzureRMNetworkSecurityGroup_withTags(t *testing.T) {
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy, // CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: testAccAzureRMNetworkSecurityGroup_withTags, // Config: testAccAzureRMNetworkSecurityGroup_withTags,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), // testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_network_security_group.test", "tags.#", "2"), // "azurerm_network_security_group.test", "tags.#", "2"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_network_security_group.test", "tags.environment", "Production"), // "azurerm_network_security_group.test", "tags.environment", "Production"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_network_security_group.test", "tags.cost_center", "MSFT"), // "azurerm_network_security_group.test", "tags.cost_center", "MSFT"),
), // ),
}, // },
//
resource.TestStep{ // resource.TestStep{
Config: testAccAzureRMNetworkSecurityGroup_withTagsUpdate, // Config: testAccAzureRMNetworkSecurityGroup_withTagsUpdate,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), // testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_network_security_group.test", "tags.#", "1"), // "azurerm_network_security_group.test", "tags.#", "1"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_network_security_group.test", "tags.environment", "staging"), // "azurerm_network_security_group.test", "tags.environment", "staging"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func TestAccAzureRMNetworkSecurityGroup_addingExtraRules(t *testing.T) { //func TestAccAzureRMNetworkSecurityGroup_addingExtraRules(t *testing.T) {
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy, // CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: testAccAzureRMNetworkSecurityGroup_basic, // Config: testAccAzureRMNetworkSecurityGroup_basic,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), // testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_network_security_group.test", "security_rule.#", "1"), // "azurerm_network_security_group.test", "security_rule.#", "1"),
), // ),
}, // },
//
resource.TestStep{ // resource.TestStep{
Config: testAccAzureRMNetworkSecurityGroup_anotherRule, // Config: testAccAzureRMNetworkSecurityGroup_anotherRule,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), // testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_network_security_group.test", "security_rule.#", "2"), // "azurerm_network_security_group.test", "security_rule.#", "2"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func testCheckAzureRMNetworkSecurityGroupExists(name string) resource.TestCheckFunc { //func testCheckAzureRMNetworkSecurityGroupExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error { // return func(s *terraform.State) error {
//
rs, ok := s.RootModule().Resources[name] // rs, ok := s.RootModule().Resources[name]
if !ok { // if !ok {
return fmt.Errorf("Not found: %s", name) // return fmt.Errorf("Not found: %s", name)
} // }
//
sgName := rs.Primary.Attributes["name"] // sgName := rs.Primary.Attributes["name"]
resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
if !hasResourceGroup { // if !hasResourceGroup {
return fmt.Errorf("Bad: no resource group found in state for network security group: %s", sgName) // return fmt.Errorf("Bad: no resource group found in state for network security group: %s", sgName)
} // }
//
conn := testAccProvider.Meta().(*ArmClient).secGroupClient // conn := testAccProvider.Meta().(*ArmClient).secGroupClient
//
resp, err := conn.Get(resourceGroup, sgName, "") // resp, err := conn.Get(resourceGroup, sgName, "")
if err != nil { // if err != nil {
return fmt.Errorf("Bad: Get on secGroupClient: %s", err) // return fmt.Errorf("Bad: Get on secGroupClient: %s", err)
} // }
//
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("Bad: Network Security Group %q (resource group: %q) does not exist", name, resourceGroup) // return fmt.Errorf("Bad: Network Security Group %q (resource group: %q) does not exist", name, resourceGroup)
} // }
//
return nil // return nil
} // }
} //}
//
func testCheckAzureRMNetworkSecurityGroupDestroy(s *terraform.State) error { //func testCheckAzureRMNetworkSecurityGroupDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*ArmClient).secGroupClient // conn := testAccProvider.Meta().(*ArmClient).secGroupClient
//
for _, rs := range s.RootModule().Resources { // for _, rs := range s.RootModule().Resources {
if rs.Type != "azurerm_network_security_group" { // if rs.Type != "azurerm_network_security_group" {
continue // continue
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup := rs.Primary.Attributes["resource_group_name"]
//
resp, err := conn.Get(resourceGroup, name, "") // resp, err := conn.Get(resourceGroup, name, "")
//
if err != nil { // if err != nil {
return nil // return nil
} // }
//
if resp.StatusCode != http.StatusNotFound { // if resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("Network Security Group still exists:\n%#v", resp.Properties) // return fmt.Errorf("Network Security Group still exists:\n%#v", resp.Properties)
} // }
} // }
//
return nil // return nil
} //}
//
var testAccAzureRMNetworkSecurityGroup_basic = ` //var testAccAzureRMNetworkSecurityGroup_basic = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acceptanceTestResourceGroup1" // name = "acceptanceTestResourceGroup1"
location = "West US" // location = "West US"
} //}
//
resource "azurerm_network_security_group" "test" { //resource "azurerm_network_security_group" "test" {
name = "acceptanceTestSecurityGroup1" // name = "acceptanceTestSecurityGroup1"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
//
security_rule { // security_rule {
name = "test123" // name = "test123"
priority = 100 // priority = 100
direction = "Inbound" // direction = "Inbound"
access = "Allow" // access = "Allow"
protocol = "Tcp" // protocol = "Tcp"
source_port_range = "*" // source_port_range = "*"
destination_port_range = "*" // destination_port_range = "*"
source_address_prefix = "*" // source_address_prefix = "*"
destination_address_prefix = "*" // destination_address_prefix = "*"
} // }
} //}
` //`
//
var testAccAzureRMNetworkSecurityGroup_anotherRule = ` //var testAccAzureRMNetworkSecurityGroup_anotherRule = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acceptanceTestResourceGroup1" // name = "acceptanceTestResourceGroup1"
location = "West US" // location = "West US"
} //}
//
resource "azurerm_network_security_group" "test" { //resource "azurerm_network_security_group" "test" {
name = "acceptanceTestSecurityGroup1" // name = "acceptanceTestSecurityGroup1"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
//
security_rule { // security_rule {
name = "test123" // name = "test123"
priority = 100 // priority = 100
direction = "Inbound" // direction = "Inbound"
access = "Allow" // access = "Allow"
protocol = "Tcp" // protocol = "Tcp"
source_port_range = "*" // source_port_range = "*"
destination_port_range = "*" // destination_port_range = "*"
source_address_prefix = "*" // source_address_prefix = "*"
destination_address_prefix = "*" // destination_address_prefix = "*"
} // }
//
security_rule { // security_rule {
name = "testDeny" // name = "testDeny"
priority = 101 // priority = 101
direction = "Inbound" // direction = "Inbound"
access = "Deny" // access = "Deny"
protocol = "Udp" // protocol = "Udp"
source_port_range = "*" // source_port_range = "*"
destination_port_range = "*" // destination_port_range = "*"
source_address_prefix = "*" // source_address_prefix = "*"
destination_address_prefix = "*" // destination_address_prefix = "*"
} // }
} //}
` //`
//
var testAccAzureRMNetworkSecurityGroup_withTags = ` //var testAccAzureRMNetworkSecurityGroup_withTags = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acceptanceTestResourceGroup1" // name = "acceptanceTestResourceGroup1"
location = "West US" // location = "West US"
} //}
//
resource "azurerm_network_security_group" "test" { //resource "azurerm_network_security_group" "test" {
name = "acceptanceTestSecurityGroup1" // name = "acceptanceTestSecurityGroup1"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
//
security_rule { // security_rule {
name = "test123" // name = "test123"
priority = 100 // priority = 100
direction = "Inbound" // direction = "Inbound"
access = "Allow" // access = "Allow"
protocol = "Tcp" // protocol = "Tcp"
source_port_range = "*" // source_port_range = "*"
destination_port_range = "*" // destination_port_range = "*"
source_address_prefix = "*" // source_address_prefix = "*"
destination_address_prefix = "*" // destination_address_prefix = "*"
} // }
//
//
tags { // tags {
environment = "Production" // environment = "Production"
cost_center = "MSFT" // cost_center = "MSFT"
} // }
} //}
` //`
//
var testAccAzureRMNetworkSecurityGroup_withTagsUpdate = ` //var testAccAzureRMNetworkSecurityGroup_withTagsUpdate = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acceptanceTestResourceGroup1" // name = "acceptanceTestResourceGroup1"
location = "West US" // location = "West US"
} //}
//
resource "azurerm_network_security_group" "test" { //resource "azurerm_network_security_group" "test" {
name = "acceptanceTestSecurityGroup1" // name = "acceptanceTestSecurityGroup1"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
//
security_rule { // security_rule {
name = "test123" // name = "test123"
priority = 100 // priority = 100
direction = "Inbound" // direction = "Inbound"
access = "Allow" // access = "Allow"
protocol = "Tcp" // protocol = "Tcp"
source_port_range = "*" // source_port_range = "*"
destination_port_range = "*" // destination_port_range = "*"
source_address_prefix = "*" // source_address_prefix = "*"
destination_address_prefix = "*" // destination_address_prefix = "*"
} // }
//
tags { // tags {
environment = "staging" // environment = "staging"
} // }
} //}
` //`

View File

@ -1,219 +1,219 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"log" // "log"
"net/http" // "net/http"
"time" // "time"
//
"github.com/Azure/azure-sdk-for-go/arm/network" // "github.com/Azure/azure-sdk-for-go/arm/network"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema" // "github.com/hashicorp/terraform/helper/schema"
) //)
//
func resourceArmNetworkSecurityRule() *schema.Resource { //func resourceArmNetworkSecurityRule() *schema.Resource {
return &schema.Resource{ // return &schema.Resource{
Create: resourceArmNetworkSecurityRuleCreate, // Create: resourceArmNetworkSecurityRuleCreate,
Read: resourceArmNetworkSecurityRuleRead, // Read: resourceArmNetworkSecurityRuleRead,
Update: resourceArmNetworkSecurityRuleCreate, // Update: resourceArmNetworkSecurityRuleCreate,
Delete: resourceArmNetworkSecurityRuleDelete, // Delete: resourceArmNetworkSecurityRuleDelete,
//
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"resource_group_name": &schema.Schema{ // "resource_group_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"network_security_group_name": &schema.Schema{ // "network_security_group_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"description": &schema.Schema{ // "description": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { // ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := v.(string) // value := v.(string)
if len(value) > 140 { // if len(value) > 140 {
errors = append(errors, fmt.Errorf( // errors = append(errors, fmt.Errorf(
"The network security rule description can be no longer than 140 chars")) // "The network security rule description can be no longer than 140 chars"))
} // }
return // return
}, // },
}, // },
//
"protocol": &schema.Schema{ // "protocol": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ValidateFunc: validateNetworkSecurityRuleProtocol, // ValidateFunc: validateNetworkSecurityRuleProtocol,
}, // },
//
"source_port_range": &schema.Schema{ // "source_port_range": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"destination_port_range": &schema.Schema{ // "destination_port_range": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"source_address_prefix": &schema.Schema{ // "source_address_prefix": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"destination_address_prefix": &schema.Schema{ // "destination_address_prefix": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"access": &schema.Schema{ // "access": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ValidateFunc: validateNetworkSecurityRuleAccess, // ValidateFunc: validateNetworkSecurityRuleAccess,
}, // },
//
"priority": &schema.Schema{ // "priority": &schema.Schema{
Type: schema.TypeInt, // Type: schema.TypeInt,
Required: true, // Required: true,
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { // ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := v.(int) // value := v.(int)
if value < 100 || value > 4096 { // if value < 100 || value > 4096 {
errors = append(errors, fmt.Errorf( // errors = append(errors, fmt.Errorf(
"The `priority` can only be between 100 and 4096")) // "The `priority` can only be between 100 and 4096"))
} // }
return // return
}, // },
}, // },
//
"direction": &schema.Schema{ // "direction": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ValidateFunc: validateNetworkSecurityRuleDirection, // ValidateFunc: validateNetworkSecurityRuleDirection,
}, // },
}, // },
} // }
} //}
//
func resourceArmNetworkSecurityRuleCreate(d *schema.ResourceData, meta interface{}) error { //func resourceArmNetworkSecurityRuleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient) // client := meta.(*ArmClient)
secClient := client.secRuleClient // secClient := client.secRuleClient
//
name := d.Get("name").(string) // name := d.Get("name").(string)
nsgName := d.Get("network_security_group_name").(string) // nsgName := d.Get("network_security_group_name").(string)
resGroup := d.Get("resource_group_name").(string) // resGroup := d.Get("resource_group_name").(string)
//
source_port_range := d.Get("source_port_range").(string) // source_port_range := d.Get("source_port_range").(string)
destination_port_range := d.Get("destination_port_range").(string) // destination_port_range := d.Get("destination_port_range").(string)
source_address_prefix := d.Get("source_address_prefix").(string) // source_address_prefix := d.Get("source_address_prefix").(string)
destination_address_prefix := d.Get("destination_address_prefix").(string) // destination_address_prefix := d.Get("destination_address_prefix").(string)
priority := d.Get("priority").(int) // priority := d.Get("priority").(int)
access := d.Get("access").(string) // access := d.Get("access").(string)
direction := d.Get("direction").(string) // direction := d.Get("direction").(string)
protocol := d.Get("protocol").(string) // protocol := d.Get("protocol").(string)
//
armMutexKV.Lock(nsgName) // armMutexKV.Lock(nsgName)
defer armMutexKV.Unlock(nsgName) // defer armMutexKV.Unlock(nsgName)
//
properties := network.SecurityRulePropertiesFormat{ // properties := network.SecurityRulePropertiesFormat{
SourcePortRange: &source_port_range, // SourcePortRange: &source_port_range,
DestinationPortRange: &destination_port_range, // DestinationPortRange: &destination_port_range,
SourceAddressPrefix: &source_address_prefix, // SourceAddressPrefix: &source_address_prefix,
DestinationAddressPrefix: &destination_address_prefix, // DestinationAddressPrefix: &destination_address_prefix,
Priority: &priority, // Priority: &priority,
Access: network.SecurityRuleAccess(access), // Access: network.SecurityRuleAccess(access),
Direction: network.SecurityRuleDirection(direction), // Direction: network.SecurityRuleDirection(direction),
Protocol: network.SecurityRuleProtocol(protocol), // Protocol: network.SecurityRuleProtocol(protocol),
} // }
//
if v, ok := d.GetOk("description"); ok { // if v, ok := d.GetOk("description"); ok {
description := v.(string) // description := v.(string)
properties.Description = &description // properties.Description = &description
} // }
//
sgr := network.SecurityRule{ // sgr := network.SecurityRule{
Name: &name, // Name: &name,
Properties: &properties, // Properties: &properties,
} // }
//
resp, err := secClient.CreateOrUpdate(resGroup, nsgName, name, sgr) // resp, err := secClient.CreateOrUpdate(resGroup, nsgName, name, sgr)
if err != nil { // if err != nil {
return err // return err
} // }
d.SetId(*resp.ID) // d.SetId(*resp.ID)
//
log.Printf("[DEBUG] Waiting for Network Security Rule (%s) to become available", name) // log.Printf("[DEBUG] Waiting for Network Security Rule (%s) to become available", name)
stateConf := &resource.StateChangeConf{ // stateConf := &resource.StateChangeConf{
Pending: []string{"Accepted", "Updating"}, // Pending: []string{"Accepted", "Updating"},
Target: []string{"Succeeded"}, // Target: []string{"Succeeded"},
Refresh: securityRuleStateRefreshFunc(client, resGroup, nsgName, name), // Refresh: securityRuleStateRefreshFunc(client, resGroup, nsgName, name),
Timeout: 10 * time.Minute, // Timeout: 10 * time.Minute,
} // }
if _, err := stateConf.WaitForState(); err != nil { // if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Network Securty Rule (%s) to become available: %s", name, err) // return fmt.Errorf("Error waiting for Network Securty Rule (%s) to become available: %s", name, err)
} // }
//
return resourceArmNetworkSecurityRuleRead(d, meta) // return resourceArmNetworkSecurityRuleRead(d, meta)
} //}
//
func resourceArmNetworkSecurityRuleRead(d *schema.ResourceData, meta interface{}) error { //func resourceArmNetworkSecurityRuleRead(d *schema.ResourceData, meta interface{}) error {
secRuleClient := meta.(*ArmClient).secRuleClient // secRuleClient := meta.(*ArmClient).secRuleClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
networkSGName := id.Path["networkSecurityGroups"] // networkSGName := id.Path["networkSecurityGroups"]
sgRuleName := id.Path["securityRules"] // sgRuleName := id.Path["securityRules"]
//
resp, err := secRuleClient.Get(resGroup, networkSGName, sgRuleName) // resp, err := secRuleClient.Get(resGroup, networkSGName, sgRuleName)
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
d.SetId("") // d.SetId("")
return nil // return nil
} // }
if err != nil { // if err != nil {
return fmt.Errorf("Error making Read request on Azure Network Security Rule %s: %s", sgRuleName, err) // return fmt.Errorf("Error making Read request on Azure Network Security Rule %s: %s", sgRuleName, err)
} // }
//
return nil // return nil
} //}
//
func resourceArmNetworkSecurityRuleDelete(d *schema.ResourceData, meta interface{}) error { //func resourceArmNetworkSecurityRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient) // client := meta.(*ArmClient)
secRuleClient := client.secRuleClient // secRuleClient := client.secRuleClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
nsgName := id.Path["networkSecurityGroups"] // nsgName := id.Path["networkSecurityGroups"]
sgRuleName := id.Path["securityRules"] // sgRuleName := id.Path["securityRules"]
//
armMutexKV.Lock(nsgName) // armMutexKV.Lock(nsgName)
defer armMutexKV.Unlock(nsgName) // defer armMutexKV.Unlock(nsgName)
//
_, err = secRuleClient.Delete(resGroup, nsgName, sgRuleName) // _, err = secRuleClient.Delete(resGroup, nsgName, sgRuleName)
//
return err // return err
} //}
//
func securityRuleStateRefreshFunc(client *ArmClient, resourceGroupName string, networkSecurityGroupName string, securityRuleName string) resource.StateRefreshFunc { //func securityRuleStateRefreshFunc(client *ArmClient, resourceGroupName string, networkSecurityGroupName string, securityRuleName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) { // return func() (interface{}, string, error) {
res, err := client.secRuleClient.Get(resourceGroupName, networkSecurityGroupName, securityRuleName) // res, err := client.secRuleClient.Get(resourceGroupName, networkSecurityGroupName, securityRuleName)
if err != nil { // if err != nil {
return nil, "", fmt.Errorf("Error issuing read request in securityGroupStateRefreshFunc to Azure ARM for network security rule '%s' (RG: '%s') (NSG: '%s'): %s", securityRuleName, resourceGroupName, networkSecurityGroupName, err) // return nil, "", fmt.Errorf("Error issuing read request in securityGroupStateRefreshFunc to Azure ARM for network security rule '%s' (RG: '%s') (NSG: '%s'): %s", securityRuleName, resourceGroupName, networkSecurityGroupName, err)
} // }
//
return res, *res.Properties.ProvisioningState, nil // return res, *res.Properties.ProvisioningState, nil
} // }
} //}

View File

@ -1,203 +1,203 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"net/http" // "net/http"
"testing" // "testing"
//
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" // "github.com/hashicorp/terraform/terraform"
) //)
//
func TestAccAzureRMNetworkSecurityRule_basic(t *testing.T) { //func TestAccAzureRMNetworkSecurityRule_basic(t *testing.T) {
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMNetworkSecurityRuleDestroy, // CheckDestroy: testCheckAzureRMNetworkSecurityRuleDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: testAccAzureRMNetworkSecurityRule_basic, // Config: testAccAzureRMNetworkSecurityRule_basic,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test"), // testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func TestAccAzureRMNetworkSecurityRule_addingRules(t *testing.T) { //func TestAccAzureRMNetworkSecurityRule_addingRules(t *testing.T) {
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMNetworkSecurityRuleDestroy, // CheckDestroy: testCheckAzureRMNetworkSecurityRuleDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: testAccAzureRMNetworkSecurityRule_updateBasic, // Config: testAccAzureRMNetworkSecurityRule_updateBasic,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test1"), // testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test1"),
), // ),
}, // },
//
resource.TestStep{ // resource.TestStep{
Config: testAccAzureRMNetworkSecurityRule_updateExtraRule, // Config: testAccAzureRMNetworkSecurityRule_updateExtraRule,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test2"), // testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test2"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func testCheckAzureRMNetworkSecurityRuleExists(name string) resource.TestCheckFunc { //func testCheckAzureRMNetworkSecurityRuleExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error { // return func(s *terraform.State) error {
//
rs, ok := s.RootModule().Resources[name] // rs, ok := s.RootModule().Resources[name]
if !ok { // if !ok {
return fmt.Errorf("Not found: %s", name) // return fmt.Errorf("Not found: %s", name)
} // }
//
sgName := rs.Primary.Attributes["network_security_group_name"] // sgName := rs.Primary.Attributes["network_security_group_name"]
sgrName := rs.Primary.Attributes["name"] // sgrName := rs.Primary.Attributes["name"]
resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
if !hasResourceGroup { // if !hasResourceGroup {
return fmt.Errorf("Bad: no resource group found in state for network security rule: %s", sgName) // return fmt.Errorf("Bad: no resource group found in state for network security rule: %s", sgName)
} // }
//
conn := testAccProvider.Meta().(*ArmClient).secRuleClient // conn := testAccProvider.Meta().(*ArmClient).secRuleClient
//
resp, err := conn.Get(resourceGroup, sgName, sgrName) // resp, err := conn.Get(resourceGroup, sgName, sgrName)
if err != nil { // if err != nil {
return fmt.Errorf("Bad: Get on secRuleClient: %s", err) // return fmt.Errorf("Bad: Get on secRuleClient: %s", err)
} // }
//
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("Bad: Network Security Rule %q (resource group: %q) (network security group: %q) does not exist", sgrName, sgName, resourceGroup) // return fmt.Errorf("Bad: Network Security Rule %q (resource group: %q) (network security group: %q) does not exist", sgrName, sgName, resourceGroup)
} // }
//
return nil // return nil
} // }
} //}
//
func testCheckAzureRMNetworkSecurityRuleDestroy(s *terraform.State) error { //func testCheckAzureRMNetworkSecurityRuleDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*ArmClient).secRuleClient // conn := testAccProvider.Meta().(*ArmClient).secRuleClient
//
for _, rs := range s.RootModule().Resources { // for _, rs := range s.RootModule().Resources {
//
if rs.Type != "azurerm_network_security_rule" { // if rs.Type != "azurerm_network_security_rule" {
continue // continue
} // }
//
sgName := rs.Primary.Attributes["network_security_group_name"] // sgName := rs.Primary.Attributes["network_security_group_name"]
sgrName := rs.Primary.Attributes["name"] // sgrName := rs.Primary.Attributes["name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup := rs.Primary.Attributes["resource_group_name"]
//
resp, err := conn.Get(resourceGroup, sgName, sgrName) // resp, err := conn.Get(resourceGroup, sgName, sgrName)
//
if err != nil { // if err != nil {
return nil // return nil
} // }
//
if resp.StatusCode != http.StatusNotFound { // if resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("Network Security Rule still exists:\n%#v", resp.Properties) // return fmt.Errorf("Network Security Rule still exists:\n%#v", resp.Properties)
} // }
} // }
//
return nil // return nil
} //}
//
var testAccAzureRMNetworkSecurityRule_basic = ` //var testAccAzureRMNetworkSecurityRule_basic = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acceptanceTestResourceGroup1" // name = "acceptanceTestResourceGroup1"
location = "West US" // location = "West US"
} //}
//
resource "azurerm_network_security_group" "test" { //resource "azurerm_network_security_group" "test" {
name = "acceptanceTestSecurityGroup1" // name = "acceptanceTestSecurityGroup1"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
} //}
//
resource "azurerm_network_security_rule" "test" { //resource "azurerm_network_security_rule" "test" {
name = "test123" // name = "test123"
priority = 100 // priority = 100
direction = "Outbound" // direction = "Outbound"
access = "Allow" // access = "Allow"
protocol = "Tcp" // protocol = "Tcp"
source_port_range = "*" // source_port_range = "*"
destination_port_range = "*" // destination_port_range = "*"
source_address_prefix = "*" // source_address_prefix = "*"
destination_address_prefix = "*" // destination_address_prefix = "*"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
network_security_group_name = "${azurerm_network_security_group.test.name}" // network_security_group_name = "${azurerm_network_security_group.test.name}"
} //}
` //`
//
var testAccAzureRMNetworkSecurityRule_updateBasic = ` //var testAccAzureRMNetworkSecurityRule_updateBasic = `
resource "azurerm_resource_group" "test1" { //resource "azurerm_resource_group" "test1" {
name = "acceptanceTestResourceGroup2" // name = "acceptanceTestResourceGroup2"
location = "West US" // location = "West US"
} //}
//
resource "azurerm_network_security_group" "test1" { //resource "azurerm_network_security_group" "test1" {
name = "acceptanceTestSecurityGroup2" // name = "acceptanceTestSecurityGroup2"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test1.name}" // resource_group_name = "${azurerm_resource_group.test1.name}"
} //}
//
resource "azurerm_network_security_rule" "test1" { //resource "azurerm_network_security_rule" "test1" {
name = "test123" // name = "test123"
priority = 100 // priority = 100
direction = "Outbound" // direction = "Outbound"
access = "Allow" // access = "Allow"
protocol = "Tcp" // protocol = "Tcp"
source_port_range = "*" // source_port_range = "*"
destination_port_range = "*" // destination_port_range = "*"
source_address_prefix = "*" // source_address_prefix = "*"
destination_address_prefix = "*" // destination_address_prefix = "*"
resource_group_name = "${azurerm_resource_group.test1.name}" // resource_group_name = "${azurerm_resource_group.test1.name}"
network_security_group_name = "${azurerm_network_security_group.test1.name}" // network_security_group_name = "${azurerm_network_security_group.test1.name}"
} //}
` //`
//
var testAccAzureRMNetworkSecurityRule_updateExtraRule = ` //var testAccAzureRMNetworkSecurityRule_updateExtraRule = `
resource "azurerm_resource_group" "test1" { //resource "azurerm_resource_group" "test1" {
name = "acceptanceTestResourceGroup2" // name = "acceptanceTestResourceGroup2"
location = "West US" // location = "West US"
} //}
//
resource "azurerm_network_security_group" "test1" { //resource "azurerm_network_security_group" "test1" {
name = "acceptanceTestSecurityGroup2" // name = "acceptanceTestSecurityGroup2"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test1.name}" // resource_group_name = "${azurerm_resource_group.test1.name}"
} //}
//
resource "azurerm_network_security_rule" "test1" { //resource "azurerm_network_security_rule" "test1" {
name = "test123" // name = "test123"
priority = 100 // priority = 100
direction = "Outbound" // direction = "Outbound"
access = "Allow" // access = "Allow"
protocol = "Tcp" // protocol = "Tcp"
source_port_range = "*" // source_port_range = "*"
destination_port_range = "*" // destination_port_range = "*"
source_address_prefix = "*" // source_address_prefix = "*"
destination_address_prefix = "*" // destination_address_prefix = "*"
resource_group_name = "${azurerm_resource_group.test1.name}" // resource_group_name = "${azurerm_resource_group.test1.name}"
network_security_group_name = "${azurerm_network_security_group.test1.name}" // network_security_group_name = "${azurerm_network_security_group.test1.name}"
} //}
//
resource "azurerm_network_security_rule" "test2" { //resource "azurerm_network_security_rule" "test2" {
name = "testing456" // name = "testing456"
priority = 101 // priority = 101
direction = "Inbound" // direction = "Inbound"
access = "Deny" // access = "Deny"
protocol = "Tcp" // protocol = "Tcp"
source_port_range = "*" // source_port_range = "*"
destination_port_range = "*" // destination_port_range = "*"
source_address_prefix = "*" // source_address_prefix = "*"
destination_address_prefix = "*" // destination_address_prefix = "*"
resource_group_name = "${azurerm_resource_group.test1.name}" // resource_group_name = "${azurerm_resource_group.test1.name}"
network_security_group_name = "${azurerm_network_security_group.test1.name}" // network_security_group_name = "${azurerm_network_security_group.test1.name}"
} //}
` //`

View File

@ -1,251 +1,251 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"log" // "log"
"net/http" // "net/http"
"regexp" // "regexp"
"strings" // "strings"
"time" // "time"
//
"github.com/Azure/azure-sdk-for-go/arm/network" // "github.com/Azure/azure-sdk-for-go/arm/network"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema" // "github.com/hashicorp/terraform/helper/schema"
) //)
//
func resourceArmPublicIp() *schema.Resource { //func resourceArmPublicIp() *schema.Resource {
return &schema.Resource{ // return &schema.Resource{
Create: resourceArmPublicIpCreate, // Create: resourceArmPublicIpCreate,
Read: resourceArmPublicIpRead, // Read: resourceArmPublicIpRead,
Update: resourceArmPublicIpCreate, // Update: resourceArmPublicIpCreate,
Delete: resourceArmPublicIpDelete, // Delete: resourceArmPublicIpDelete,
//
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"location": &schema.Schema{ // "location": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
StateFunc: azureRMNormalizeLocation, // StateFunc: azureRMNormalizeLocation,
}, // },
//
"resource_group_name": &schema.Schema{ // "resource_group_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"public_ip_address_allocation": &schema.Schema{ // "public_ip_address_allocation": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ValidateFunc: validatePublicIpAllocation, // ValidateFunc: validatePublicIpAllocation,
}, // },
//
"idle_timeout_in_minutes": &schema.Schema{ // "idle_timeout_in_minutes": &schema.Schema{
Type: schema.TypeInt, // Type: schema.TypeInt,
Optional: true, // Optional: true,
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { // ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := v.(int) // value := v.(int)
if value < 4 || value > 30 { // if value < 4 || value > 30 {
errors = append(errors, fmt.Errorf( // errors = append(errors, fmt.Errorf(
"The idle timeout must be between 4 and 30 minutes")) // "The idle timeout must be between 4 and 30 minutes"))
} // }
return // return
}, // },
}, // },
//
"domain_name_label": &schema.Schema{ // "domain_name_label": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
ValidateFunc: validatePublicIpDomainNameLabel, // ValidateFunc: validatePublicIpDomainNameLabel,
}, // },
//
"reverse_fqdn": &schema.Schema{ // "reverse_fqdn": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
}, // },
//
"fqdn": &schema.Schema{ // "fqdn": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Computed: true, // Computed: true,
}, // },
//
"ip_address": &schema.Schema{ // "ip_address": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Computed: true, // Computed: true,
}, // },
//
"tags": tagsSchema(), // "tags": tagsSchema(),
}, // },
} // }
} //}
//
func resourceArmPublicIpCreate(d *schema.ResourceData, meta interface{}) error { //func resourceArmPublicIpCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient) // client := meta.(*ArmClient)
publicIPClient := client.publicIPClient // publicIPClient := client.publicIPClient
//
log.Printf("[INFO] preparing arguments for Azure ARM Public IP creation.") // log.Printf("[INFO] preparing arguments for Azure ARM Public IP creation.")
//
name := d.Get("name").(string) // name := d.Get("name").(string)
location := d.Get("location").(string) // location := d.Get("location").(string)
resGroup := d.Get("resource_group_name").(string) // resGroup := d.Get("resource_group_name").(string)
tags := d.Get("tags").(map[string]interface{}) // tags := d.Get("tags").(map[string]interface{})
//
properties := network.PublicIPAddressPropertiesFormat{ // properties := network.PublicIPAddressPropertiesFormat{
PublicIPAllocationMethod: network.IPAllocationMethod(d.Get("public_ip_address_allocation").(string)), // PublicIPAllocationMethod: network.IPAllocationMethod(d.Get("public_ip_address_allocation").(string)),
} // }
//
dnl, hasDnl := d.GetOk("domain_name_label") // dnl, hasDnl := d.GetOk("domain_name_label")
rfqdn, hasRfqdn := d.GetOk("reverse_fqdn") // rfqdn, hasRfqdn := d.GetOk("reverse_fqdn")
//
if hasDnl || hasRfqdn { // if hasDnl || hasRfqdn {
dnsSettings := network.PublicIPAddressDNSSettings{} // dnsSettings := network.PublicIPAddressDNSSettings{}
//
if hasRfqdn { // if hasRfqdn {
reverse_fqdn := rfqdn.(string) // reverse_fqdn := rfqdn.(string)
dnsSettings.ReverseFqdn = &reverse_fqdn // dnsSettings.ReverseFqdn = &reverse_fqdn
} // }
//
if hasDnl { // if hasDnl {
domain_name_label := dnl.(string) // domain_name_label := dnl.(string)
dnsSettings.DomainNameLabel = &domain_name_label // dnsSettings.DomainNameLabel = &domain_name_label
//
} // }
//
properties.DNSSettings = &dnsSettings // properties.DNSSettings = &dnsSettings
} // }
//
if v, ok := d.GetOk("idle_timeout_in_minutes"); ok { // if v, ok := d.GetOk("idle_timeout_in_minutes"); ok {
idle_timeout := v.(int) // idle_timeout := v.(int)
properties.IdleTimeoutInMinutes = &idle_timeout // properties.IdleTimeoutInMinutes = &idle_timeout
} // }
//
publicIp := network.PublicIPAddress{ // publicIp := network.PublicIPAddress{
Name: &name, // Name: &name,
Location: &location, // Location: &location,
Properties: &properties, // Properties: &properties,
Tags: expandTags(tags), // Tags: expandTags(tags),
} // }
//
resp, err := publicIPClient.CreateOrUpdate(resGroup, name, publicIp) // resp, err := publicIPClient.CreateOrUpdate(resGroup, name, publicIp)
if err != nil { // if err != nil {
return err // return err
} // }
//
d.SetId(*resp.ID) // d.SetId(*resp.ID)
//
log.Printf("[DEBUG] Waiting for Public IP (%s) to become available", name) // log.Printf("[DEBUG] Waiting for Public IP (%s) to become available", name)
stateConf := &resource.StateChangeConf{ // stateConf := &resource.StateChangeConf{
Pending: []string{"Accepted", "Updating"}, // Pending: []string{"Accepted", "Updating"},
Target: []string{"Succeeded"}, // Target: []string{"Succeeded"},
Refresh: publicIPStateRefreshFunc(client, resGroup, name), // Refresh: publicIPStateRefreshFunc(client, resGroup, name),
Timeout: 10 * time.Minute, // Timeout: 10 * time.Minute,
} // }
if _, err := stateConf.WaitForState(); err != nil { // if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Public IP (%s) to become available: %s", name, err) // return fmt.Errorf("Error waiting for Public IP (%s) to become available: %s", name, err)
} // }
//
return resourceArmPublicIpRead(d, meta) // return resourceArmPublicIpRead(d, meta)
} //}
//
func resourceArmPublicIpRead(d *schema.ResourceData, meta interface{}) error { //func resourceArmPublicIpRead(d *schema.ResourceData, meta interface{}) error {
publicIPClient := meta.(*ArmClient).publicIPClient // publicIPClient := meta.(*ArmClient).publicIPClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["publicIPAddresses"] // name := id.Path["publicIPAddresses"]
//
resp, err := publicIPClient.Get(resGroup, name, "") // resp, err := publicIPClient.Get(resGroup, name, "")
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
d.SetId("") // d.SetId("")
return nil // return nil
} // }
if err != nil { // if err != nil {
return fmt.Errorf("Error making Read request on Azure public ip %s: %s", name, err) // return fmt.Errorf("Error making Read request on Azure public ip %s: %s", name, err)
} // }
//
if resp.Properties.DNSSettings != nil && resp.Properties.DNSSettings.Fqdn != nil && *resp.Properties.DNSSettings.Fqdn != "" { // if resp.Properties.DNSSettings != nil && resp.Properties.DNSSettings.Fqdn != nil && *resp.Properties.DNSSettings.Fqdn != "" {
d.Set("fqdn", resp.Properties.DNSSettings.Fqdn) // d.Set("fqdn", resp.Properties.DNSSettings.Fqdn)
} // }
//
if resp.Properties.IPAddress != nil && *resp.Properties.IPAddress != "" { // if resp.Properties.IPAddress != nil && *resp.Properties.IPAddress != "" {
d.Set("ip_address", resp.Properties.IPAddress) // d.Set("ip_address", resp.Properties.IPAddress)
} // }
//
flattenAndSetTags(d, resp.Tags) // flattenAndSetTags(d, resp.Tags)
//
return nil // return nil
} //}
//
func resourceArmPublicIpDelete(d *schema.ResourceData, meta interface{}) error { //func resourceArmPublicIpDelete(d *schema.ResourceData, meta interface{}) error {
publicIPClient := meta.(*ArmClient).publicIPClient // publicIPClient := meta.(*ArmClient).publicIPClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["publicIPAddresses"] // name := id.Path["publicIPAddresses"]
//
_, err = publicIPClient.Delete(resGroup, name) // _, err = publicIPClient.Delete(resGroup, name)
//
return err // return err
} //}
//
func publicIPStateRefreshFunc(client *ArmClient, resourceGroupName string, publicIpName string) resource.StateRefreshFunc { //func publicIPStateRefreshFunc(client *ArmClient, resourceGroupName string, publicIpName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) { // return func() (interface{}, string, error) {
res, err := client.publicIPClient.Get(resourceGroupName, publicIpName, "") // res, err := client.publicIPClient.Get(resourceGroupName, publicIpName, "")
if err != nil { // if err != nil {
return nil, "", fmt.Errorf("Error issuing read request in publicIPStateRefreshFunc to Azure ARM for public ip '%s' (RG: '%s'): %s", publicIpName, resourceGroupName, err) // return nil, "", fmt.Errorf("Error issuing read request in publicIPStateRefreshFunc to Azure ARM for public ip '%s' (RG: '%s'): %s", publicIpName, resourceGroupName, err)
} // }
//
return res, *res.Properties.ProvisioningState, nil // return res, *res.Properties.ProvisioningState, nil
} // }
} //}
//
func validatePublicIpAllocation(v interface{}, k string) (ws []string, errors []error) { //func validatePublicIpAllocation(v interface{}, k string) (ws []string, errors []error) {
value := strings.ToLower(v.(string)) // value := strings.ToLower(v.(string))
allocations := map[string]bool{ // allocations := map[string]bool{
"static": true, // "static": true,
"dynamic": true, // "dynamic": true,
} // }
//
if !allocations[value] { // if !allocations[value] {
errors = append(errors, fmt.Errorf("Public IP Allocation can only be Static of Dynamic")) // errors = append(errors, fmt.Errorf("Public IP Allocation can only be Static of Dynamic"))
} // }
return // return
} //}
//
func validatePublicIpDomainNameLabel(v interface{}, k string) (ws []string, errors []error) { //func validatePublicIpDomainNameLabel(v interface{}, k string) (ws []string, errors []error) {
value := v.(string) // value := v.(string)
if !regexp.MustCompile(`^[a-z0-9-]+$`).MatchString(value) { // if !regexp.MustCompile(`^[a-z0-9-]+$`).MatchString(value) {
errors = append(errors, fmt.Errorf( // errors = append(errors, fmt.Errorf(
"only alphanumeric characters and hyphens allowed in %q: %q", // "only alphanumeric characters and hyphens allowed in %q: %q",
k, value)) // k, value))
} // }
//
if len(value) > 61 { // if len(value) > 61 {
errors = append(errors, fmt.Errorf( // errors = append(errors, fmt.Errorf(
"%q cannot be longer than 61 characters: %q", k, value)) // "%q cannot be longer than 61 characters: %q", k, value))
} // }
//
if len(value) == 0 { // if len(value) == 0 {
errors = append(errors, fmt.Errorf( // errors = append(errors, fmt.Errorf(
"%q cannot be an empty string: %q", k, value)) // "%q cannot be an empty string: %q", k, value))
} // }
if regexp.MustCompile(`-$`).MatchString(value) { // if regexp.MustCompile(`-$`).MatchString(value) {
errors = append(errors, fmt.Errorf( // errors = append(errors, fmt.Errorf(
"%q cannot end with a hyphen: %q", k, value)) // "%q cannot end with a hyphen: %q", k, value))
} // }
//
return // return
//
} //}

View File

@ -1,316 +1,316 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"net/http" // "net/http"
"testing" // "testing"
//
"github.com/hashicorp/terraform/helper/acctest" // "github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" // "github.com/hashicorp/terraform/terraform"
) //)
//
func TestResourceAzureRMPublicIpAllocation_validation(t *testing.T) { //func TestResourceAzureRMPublicIpAllocation_validation(t *testing.T) {
cases := []struct { // cases := []struct {
Value string // Value string
ErrCount int // ErrCount int
}{ // }{
{ // {
Value: "Random", // Value: "Random",
ErrCount: 1, // ErrCount: 1,
}, // },
{ // {
Value: "Static", // Value: "Static",
ErrCount: 0, // ErrCount: 0,
}, // },
{ // {
Value: "Dynamic", // Value: "Dynamic",
ErrCount: 0, // ErrCount: 0,
}, // },
{ // {
Value: "STATIC", // Value: "STATIC",
ErrCount: 0, // ErrCount: 0,
}, // },
{ // {
Value: "static", // Value: "static",
ErrCount: 0, // ErrCount: 0,
}, // },
} // }
//
for _, tc := range cases { // for _, tc := range cases {
_, errors := validatePublicIpAllocation(tc.Value, "azurerm_public_ip") // _, errors := validatePublicIpAllocation(tc.Value, "azurerm_public_ip")
//
if len(errors) != tc.ErrCount { // if len(errors) != tc.ErrCount {
t.Fatalf("Expected the Azure RM Public IP allocation to trigger a validation error") // t.Fatalf("Expected the Azure RM Public IP allocation to trigger a validation error")
} // }
} // }
} //}
//
func TestResourceAzureRMPublicIpDomainNameLabel_validation(t *testing.T) { //func TestResourceAzureRMPublicIpDomainNameLabel_validation(t *testing.T) {
cases := []struct { // cases := []struct {
Value string // Value string
ErrCount int // ErrCount int
}{ // }{
{ // {
Value: "tEsting123", // Value: "tEsting123",
ErrCount: 1, // ErrCount: 1,
}, // },
{ // {
Value: "testing123!", // Value: "testing123!",
ErrCount: 1, // ErrCount: 1,
}, // },
{ // {
Value: "testing123-", // Value: "testing123-",
ErrCount: 1, // ErrCount: 1,
}, // },
{ // {
Value: acctest.RandString(80), // Value: acctest.RandString(80),
ErrCount: 1, // ErrCount: 1,
}, // },
} // }
//
for _, tc := range cases { // for _, tc := range cases {
_, errors := validatePublicIpDomainNameLabel(tc.Value, "azurerm_public_ip") // _, errors := validatePublicIpDomainNameLabel(tc.Value, "azurerm_public_ip")
//
if len(errors) != tc.ErrCount { // if len(errors) != tc.ErrCount {
t.Fatalf("Expected the Azure RM Public IP Domain Name Label to trigger a validation error") // t.Fatalf("Expected the Azure RM Public IP Domain Name Label to trigger a validation error")
} // }
} // }
} //}
//
func TestAccAzureRMPublicIpStatic_basic(t *testing.T) { //func TestAccAzureRMPublicIpStatic_basic(t *testing.T) {
//
ri := acctest.RandInt() // ri := acctest.RandInt()
config := fmt.Sprintf(testAccAzureRMVPublicIpStatic_basic, ri, ri) // config := fmt.Sprintf(testAccAzureRMVPublicIpStatic_basic, ri, ri)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMPublicIpDestroy, // CheckDestroy: testCheckAzureRMPublicIpDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: config, // Config: config,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), // testCheckAzureRMPublicIpExists("azurerm_public_ip.test"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func TestAccAzureRMPublicIpStatic_withTags(t *testing.T) { //func TestAccAzureRMPublicIpStatic_withTags(t *testing.T) {
//
ri := acctest.RandInt() // ri := acctest.RandInt()
preConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_withTags, ri, ri) // preConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_withTags, ri, ri)
postConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_withTagsUpdate, ri, ri) // postConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_withTagsUpdate, ri, ri)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMPublicIpDestroy, // CheckDestroy: testCheckAzureRMPublicIpDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: preConfig, // Config: preConfig,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), // testCheckAzureRMPublicIpExists("azurerm_public_ip.test"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_public_ip.test", "tags.#", "2"), // "azurerm_public_ip.test", "tags.#", "2"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_public_ip.test", "tags.environment", "Production"), // "azurerm_public_ip.test", "tags.environment", "Production"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_public_ip.test", "tags.cost_center", "MSFT"), // "azurerm_public_ip.test", "tags.cost_center", "MSFT"),
), // ),
}, // },
//
resource.TestStep{ // resource.TestStep{
Config: postConfig, // Config: postConfig,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), // testCheckAzureRMPublicIpExists("azurerm_public_ip.test"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_public_ip.test", "tags.#", "1"), // "azurerm_public_ip.test", "tags.#", "1"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_public_ip.test", "tags.environment", "staging"), // "azurerm_public_ip.test", "tags.environment", "staging"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func TestAccAzureRMPublicIpStatic_update(t *testing.T) { //func TestAccAzureRMPublicIpStatic_update(t *testing.T) {
//
ri := acctest.RandInt() // ri := acctest.RandInt()
preConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_basic, ri, ri) // preConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_basic, ri, ri)
postConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_update, ri, ri) // postConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_update, ri, ri)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMPublicIpDestroy, // CheckDestroy: testCheckAzureRMPublicIpDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: preConfig, // Config: preConfig,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), // testCheckAzureRMPublicIpExists("azurerm_public_ip.test"),
), // ),
}, // },
//
resource.TestStep{ // resource.TestStep{
Config: postConfig, // Config: postConfig,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), // testCheckAzureRMPublicIpExists("azurerm_public_ip.test"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_public_ip.test", "domain_name_label", "mylabel01"), // "azurerm_public_ip.test", "domain_name_label", "mylabel01"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func TestAccAzureRMPublicIpDynamic_basic(t *testing.T) { //func TestAccAzureRMPublicIpDynamic_basic(t *testing.T) {
//
ri := acctest.RandInt() // ri := acctest.RandInt()
config := fmt.Sprintf(testAccAzureRMVPublicIpDynamic_basic, ri, ri) // config := fmt.Sprintf(testAccAzureRMVPublicIpDynamic_basic, ri, ri)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMPublicIpDestroy, // CheckDestroy: testCheckAzureRMPublicIpDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: config, // Config: config,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), // testCheckAzureRMPublicIpExists("azurerm_public_ip.test"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func testCheckAzureRMPublicIpExists(name string) resource.TestCheckFunc { //func testCheckAzureRMPublicIpExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error { // return func(s *terraform.State) error {
// Ensure we have enough information in state to look up in API // // Ensure we have enough information in state to look up in API
rs, ok := s.RootModule().Resources[name] // rs, ok := s.RootModule().Resources[name]
if !ok { // if !ok {
return fmt.Errorf("Not found: %s", name) // return fmt.Errorf("Not found: %s", name)
} // }
//
availSetName := rs.Primary.Attributes["name"] // availSetName := rs.Primary.Attributes["name"]
resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
if !hasResourceGroup { // if !hasResourceGroup {
return fmt.Errorf("Bad: no resource group found in state for public ip: %s", availSetName) // return fmt.Errorf("Bad: no resource group found in state for public ip: %s", availSetName)
} // }
//
conn := testAccProvider.Meta().(*ArmClient).publicIPClient // conn := testAccProvider.Meta().(*ArmClient).publicIPClient
//
resp, err := conn.Get(resourceGroup, availSetName, "") // resp, err := conn.Get(resourceGroup, availSetName, "")
if err != nil { // if err != nil {
return fmt.Errorf("Bad: Get on publicIPClient: %s", err) // return fmt.Errorf("Bad: Get on publicIPClient: %s", err)
} // }
//
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("Bad: Public IP %q (resource group: %q) does not exist", name, resourceGroup) // return fmt.Errorf("Bad: Public IP %q (resource group: %q) does not exist", name, resourceGroup)
} // }
//
return nil // return nil
} // }
} //}
//
func testCheckAzureRMPublicIpDestroy(s *terraform.State) error { //func testCheckAzureRMPublicIpDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*ArmClient).publicIPClient // conn := testAccProvider.Meta().(*ArmClient).publicIPClient
//
for _, rs := range s.RootModule().Resources { // for _, rs := range s.RootModule().Resources {
if rs.Type != "azurerm_public_ip" { // if rs.Type != "azurerm_public_ip" {
continue // continue
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup := rs.Primary.Attributes["resource_group_name"]
//
resp, err := conn.Get(resourceGroup, name, "") // resp, err := conn.Get(resourceGroup, name, "")
//
if err != nil { // if err != nil {
return nil // return nil
} // }
//
if resp.StatusCode != http.StatusNotFound { // if resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("Public IP still exists:\n%#v", resp.Properties) // return fmt.Errorf("Public IP still exists:\n%#v", resp.Properties)
} // }
} // }
//
return nil // return nil
} //}
//
var testAccAzureRMVPublicIpStatic_basic = ` //var testAccAzureRMVPublicIpStatic_basic = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
resource "azurerm_public_ip" "test" { //resource "azurerm_public_ip" "test" {
name = "acctestpublicip-%d" // name = "acctestpublicip-%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
public_ip_address_allocation = "static" // public_ip_address_allocation = "static"
} //}
` //`
//
var testAccAzureRMVPublicIpStatic_update = ` //var testAccAzureRMVPublicIpStatic_update = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
resource "azurerm_public_ip" "test" { //resource "azurerm_public_ip" "test" {
name = "acctestpublicip-%d" // name = "acctestpublicip-%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
public_ip_address_allocation = "static" // public_ip_address_allocation = "static"
domain_name_label = "mylabel01" // domain_name_label = "mylabel01"
} //}
` //`
//
var testAccAzureRMVPublicIpDynamic_basic = ` //var testAccAzureRMVPublicIpDynamic_basic = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
resource "azurerm_public_ip" "test" { //resource "azurerm_public_ip" "test" {
name = "acctestpublicip-%d" // name = "acctestpublicip-%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
public_ip_address_allocation = "dynamic" // public_ip_address_allocation = "dynamic"
} //}
` //`
//
var testAccAzureRMVPublicIpStatic_withTags = ` //var testAccAzureRMVPublicIpStatic_withTags = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
resource "azurerm_public_ip" "test" { //resource "azurerm_public_ip" "test" {
name = "acctestpublicip-%d" // name = "acctestpublicip-%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
public_ip_address_allocation = "static" // public_ip_address_allocation = "static"
//
tags { // tags {
environment = "Production" // environment = "Production"
cost_center = "MSFT" // cost_center = "MSFT"
} // }
} //}
` //`
//
var testAccAzureRMVPublicIpStatic_withTagsUpdate = ` //var testAccAzureRMVPublicIpStatic_withTagsUpdate = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
resource "azurerm_public_ip" "test" { //resource "azurerm_public_ip" "test" {
name = "acctestpublicip-%d" // name = "acctestpublicip-%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
public_ip_address_allocation = "static" // public_ip_address_allocation = "static"
//
tags { // tags {
environment = "staging" // environment = "staging"
} // }
} //}
` //`

View File

@ -1,161 +1,161 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"log" // "log"
"net/http" // "net/http"
"time" // "time"
//
"github.com/Azure/azure-sdk-for-go/arm/network" // "github.com/Azure/azure-sdk-for-go/arm/network"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema" // "github.com/hashicorp/terraform/helper/schema"
) //)
//
func resourceArmRoute() *schema.Resource { //func resourceArmRoute() *schema.Resource {
return &schema.Resource{ // return &schema.Resource{
Create: resourceArmRouteCreate, // Create: resourceArmRouteCreate,
Read: resourceArmRouteRead, // Read: resourceArmRouteRead,
Update: resourceArmRouteCreate, // Update: resourceArmRouteCreate,
Delete: resourceArmRouteDelete, // Delete: resourceArmRouteDelete,
//
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"resource_group_name": &schema.Schema{ // "resource_group_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"route_table_name": &schema.Schema{ // "route_table_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"address_prefix": &schema.Schema{ // "address_prefix": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"next_hop_type": &schema.Schema{ // "next_hop_type": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ValidateFunc: validateRouteTableNextHopType, // ValidateFunc: validateRouteTableNextHopType,
}, // },
//
"next_hop_in_ip_address": &schema.Schema{ // "next_hop_in_ip_address": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
}, // },
}, // },
} // }
} //}
//
func resourceArmRouteCreate(d *schema.ResourceData, meta interface{}) error { //func resourceArmRouteCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient) // client := meta.(*ArmClient)
routesClient := client.routesClient // routesClient := client.routesClient
//
name := d.Get("name").(string) // name := d.Get("name").(string)
rtName := d.Get("route_table_name").(string) // rtName := d.Get("route_table_name").(string)
resGroup := d.Get("resource_group_name").(string) // resGroup := d.Get("resource_group_name").(string)
//
addressPrefix := d.Get("address_prefix").(string) // addressPrefix := d.Get("address_prefix").(string)
nextHopType := d.Get("next_hop_type").(string) // nextHopType := d.Get("next_hop_type").(string)
//
armMutexKV.Lock(rtName) // armMutexKV.Lock(rtName)
defer armMutexKV.Unlock(rtName) // defer armMutexKV.Unlock(rtName)
//
properties := network.RoutePropertiesFormat{ // properties := network.RoutePropertiesFormat{
AddressPrefix: &addressPrefix, // AddressPrefix: &addressPrefix,
NextHopType: network.RouteNextHopType(nextHopType), // NextHopType: network.RouteNextHopType(nextHopType),
} // }
//
if v, ok := d.GetOk("next_hop_in_ip_address"); ok { // if v, ok := d.GetOk("next_hop_in_ip_address"); ok {
nextHopInIpAddress := v.(string) // nextHopInIpAddress := v.(string)
properties.NextHopIPAddress = &nextHopInIpAddress // properties.NextHopIPAddress = &nextHopInIpAddress
} // }
//
route := network.Route{ // route := network.Route{
Name: &name, // Name: &name,
Properties: &properties, // Properties: &properties,
} // }
//
resp, err := routesClient.CreateOrUpdate(resGroup, rtName, name, route) // resp, err := routesClient.CreateOrUpdate(resGroup, rtName, name, route)
if err != nil { // if err != nil {
return err // return err
} // }
d.SetId(*resp.ID) // d.SetId(*resp.ID)
//
log.Printf("[DEBUG] Waiting for Route (%s) to become available", name) // log.Printf("[DEBUG] Waiting for Route (%s) to become available", name)
stateConf := &resource.StateChangeConf{ // stateConf := &resource.StateChangeConf{
Pending: []string{"Accepted", "Updating"}, // Pending: []string{"Accepted", "Updating"},
Target: []string{"Succeeded"}, // Target: []string{"Succeeded"},
Refresh: routeStateRefreshFunc(client, resGroup, rtName, name), // Refresh: routeStateRefreshFunc(client, resGroup, rtName, name),
Timeout: 10 * time.Minute, // Timeout: 10 * time.Minute,
} // }
if _, err := stateConf.WaitForState(); err != nil { // if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Route (%s) to become available: %s", name, err) // return fmt.Errorf("Error waiting for Route (%s) to become available: %s", name, err)
} // }
//
return resourceArmRouteRead(d, meta) // return resourceArmRouteRead(d, meta)
} //}
//
func resourceArmRouteRead(d *schema.ResourceData, meta interface{}) error { //func resourceArmRouteRead(d *schema.ResourceData, meta interface{}) error {
routesClient := meta.(*ArmClient).routesClient // routesClient := meta.(*ArmClient).routesClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
rtName := id.Path["routeTables"] // rtName := id.Path["routeTables"]
routeName := id.Path["routes"] // routeName := id.Path["routes"]
//
resp, err := routesClient.Get(resGroup, rtName, routeName) // resp, err := routesClient.Get(resGroup, rtName, routeName)
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
d.SetId("") // d.SetId("")
return nil // return nil
} // }
if err != nil { // if err != nil {
return fmt.Errorf("Error making Read request on Azure Route %s: %s", routeName, err) // return fmt.Errorf("Error making Read request on Azure Route %s: %s", routeName, err)
} // }
//
return nil // return nil
} //}
//
func resourceArmRouteDelete(d *schema.ResourceData, meta interface{}) error { //func resourceArmRouteDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient) // client := meta.(*ArmClient)
routesClient := client.routesClient // routesClient := client.routesClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
rtName := id.Path["routeTables"] // rtName := id.Path["routeTables"]
routeName := id.Path["routes"] // routeName := id.Path["routes"]
//
armMutexKV.Lock(rtName) // armMutexKV.Lock(rtName)
defer armMutexKV.Unlock(rtName) // defer armMutexKV.Unlock(rtName)
//
_, err = routesClient.Delete(resGroup, rtName, routeName) // _, err = routesClient.Delete(resGroup, rtName, routeName)
//
return err // return err
} //}
//
func routeStateRefreshFunc(client *ArmClient, resourceGroupName string, routeTableName string, routeName string) resource.StateRefreshFunc { //func routeStateRefreshFunc(client *ArmClient, resourceGroupName string, routeTableName string, routeName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) { // return func() (interface{}, string, error) {
res, err := client.routesClient.Get(resourceGroupName, routeTableName, routeName) // res, err := client.routesClient.Get(resourceGroupName, routeTableName, routeName)
if err != nil { // if err != nil {
return nil, "", fmt.Errorf("Error issuing read request in routeStateRefreshFunc to Azure ARM for route '%s' (RG: '%s') (NSG: '%s'): %s", routeName, resourceGroupName, routeTableName, err) // return nil, "", fmt.Errorf("Error issuing read request in routeStateRefreshFunc to Azure ARM for route '%s' (RG: '%s') (NSG: '%s'): %s", routeName, resourceGroupName, routeTableName, err)
} // }
//
return res, *res.Properties.ProvisioningState, nil // return res, *res.Properties.ProvisioningState, nil
} // }
} //}

View File

@ -1,258 +1,258 @@
package azurerm package azurerm
import ( //import (
"bytes" // "bytes"
"fmt" // "fmt"
"log" // "log"
"net/http" // "net/http"
"strings" // "strings"
"time" // "time"
//
"github.com/Azure/azure-sdk-for-go/arm/network" // "github.com/Azure/azure-sdk-for-go/arm/network"
"github.com/hashicorp/terraform/helper/hashcode" // "github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema" // "github.com/hashicorp/terraform/helper/schema"
) //)
//
func resourceArmRouteTable() *schema.Resource { //func resourceArmRouteTable() *schema.Resource {
return &schema.Resource{ // return &schema.Resource{
Create: resourceArmRouteTableCreate, // Create: resourceArmRouteTableCreate,
Read: resourceArmRouteTableRead, // Read: resourceArmRouteTableRead,
Update: resourceArmRouteTableCreate, // Update: resourceArmRouteTableCreate,
Delete: resourceArmRouteTableDelete, // Delete: resourceArmRouteTableDelete,
//
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"location": &schema.Schema{ // "location": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
StateFunc: azureRMNormalizeLocation, // StateFunc: azureRMNormalizeLocation,
}, // },
//
"resource_group_name": &schema.Schema{ // "resource_group_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"route": &schema.Schema{ // "route": &schema.Schema{
Type: schema.TypeSet, // Type: schema.TypeSet,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
Elem: &schema.Resource{ // Elem: &schema.Resource{
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"address_prefix": &schema.Schema{ // "address_prefix": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"next_hop_type": &schema.Schema{ // "next_hop_type": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ValidateFunc: validateRouteTableNextHopType, // ValidateFunc: validateRouteTableNextHopType,
}, // },
//
"next_hop_in_ip_address": &schema.Schema{ // "next_hop_in_ip_address": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
}, // },
}, // },
}, // },
Set: resourceArmRouteTableRouteHash, // Set: resourceArmRouteTableRouteHash,
}, // },
//
"subnets": &schema.Schema{ // "subnets": &schema.Schema{
Type: schema.TypeSet, // Type: schema.TypeSet,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
Elem: &schema.Schema{Type: schema.TypeString}, // Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString, // Set: schema.HashString,
}, // },
//
"tags": tagsSchema(), // "tags": tagsSchema(),
}, // },
} // }
} //}
//
func resourceArmRouteTableCreate(d *schema.ResourceData, meta interface{}) error { //func resourceArmRouteTableCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient) // client := meta.(*ArmClient)
routeTablesClient := client.routeTablesClient // routeTablesClient := client.routeTablesClient
//
log.Printf("[INFO] preparing arguments for Azure ARM Route Table creation.") // log.Printf("[INFO] preparing arguments for Azure ARM Route Table creation.")
//
name := d.Get("name").(string) // name := d.Get("name").(string)
location := d.Get("location").(string) // location := d.Get("location").(string)
resGroup := d.Get("resource_group_name").(string) // resGroup := d.Get("resource_group_name").(string)
tags := d.Get("tags").(map[string]interface{}) // tags := d.Get("tags").(map[string]interface{})
//
routeSet := network.RouteTable{ // routeSet := network.RouteTable{
Name: &name, // Name: &name,
Location: &location, // Location: &location,
Tags: expandTags(tags), // Tags: expandTags(tags),
} // }
//
if _, ok := d.GetOk("route"); ok { // if _, ok := d.GetOk("route"); ok {
properties := network.RouteTablePropertiesFormat{} // properties := network.RouteTablePropertiesFormat{}
routes, routeErr := expandAzureRmRouteTableRoutes(d) // routes, routeErr := expandAzureRmRouteTableRoutes(d)
if routeErr != nil { // if routeErr != nil {
return fmt.Errorf("Error Building list of Route Table Routes: %s", routeErr) // return fmt.Errorf("Error Building list of Route Table Routes: %s", routeErr)
} // }
if len(routes) > 0 { // if len(routes) > 0 {
routeSet.Properties = &properties // routeSet.Properties = &properties
} // }
//
} // }
//
resp, err := routeTablesClient.CreateOrUpdate(resGroup, name, routeSet) // resp, err := routeTablesClient.CreateOrUpdate(resGroup, name, routeSet)
if err != nil { // if err != nil {
return err // return err
} // }
//
d.SetId(*resp.ID) // d.SetId(*resp.ID)
//
log.Printf("[DEBUG] Waiting for Route Table (%s) to become available", name) // log.Printf("[DEBUG] Waiting for Route Table (%s) to become available", name)
stateConf := &resource.StateChangeConf{ // stateConf := &resource.StateChangeConf{
Pending: []string{"Accepted", "Updating"}, // Pending: []string{"Accepted", "Updating"},
Target: []string{"Succeeded"}, // Target: []string{"Succeeded"},
Refresh: routeTableStateRefreshFunc(client, resGroup, name), // Refresh: routeTableStateRefreshFunc(client, resGroup, name),
Timeout: 10 * time.Minute, // Timeout: 10 * time.Minute,
} // }
if _, err := stateConf.WaitForState(); err != nil { // if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting forRoute Table (%s) to become available: %s", name, err) // return fmt.Errorf("Error waiting forRoute Table (%s) to become available: %s", name, err)
} // }
//
return resourceArmRouteTableRead(d, meta) // return resourceArmRouteTableRead(d, meta)
} //}
//
func resourceArmRouteTableRead(d *schema.ResourceData, meta interface{}) error { //func resourceArmRouteTableRead(d *schema.ResourceData, meta interface{}) error {
routeTablesClient := meta.(*ArmClient).routeTablesClient // routeTablesClient := meta.(*ArmClient).routeTablesClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["routeTables"] // name := id.Path["routeTables"]
//
resp, err := routeTablesClient.Get(resGroup, name, "") // resp, err := routeTablesClient.Get(resGroup, name, "")
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
d.SetId("") // d.SetId("")
return nil // return nil
} // }
if err != nil { // if err != nil {
return fmt.Errorf("Error making Read request on Azure Route Table %s: %s", name, err) // return fmt.Errorf("Error making Read request on Azure Route Table %s: %s", name, err)
} // }
//
if resp.Properties.Subnets != nil { // if resp.Properties.Subnets != nil {
if len(*resp.Properties.Subnets) > 0 { // if len(*resp.Properties.Subnets) > 0 {
subnets := make([]string, 0, len(*resp.Properties.Subnets)) // subnets := make([]string, 0, len(*resp.Properties.Subnets))
for _, subnet := range *resp.Properties.Subnets { // for _, subnet := range *resp.Properties.Subnets {
id := subnet.ID // id := subnet.ID
subnets = append(subnets, *id) // subnets = append(subnets, *id)
} // }
//
if err := d.Set("subnets", subnets); err != nil { // if err := d.Set("subnets", subnets); err != nil {
return err // return err
} // }
} // }
} // }
//
flattenAndSetTags(d, resp.Tags) // flattenAndSetTags(d, resp.Tags)
//
return nil // return nil
} //}
//
func resourceArmRouteTableDelete(d *schema.ResourceData, meta interface{}) error { //func resourceArmRouteTableDelete(d *schema.ResourceData, meta interface{}) error {
routeTablesClient := meta.(*ArmClient).routeTablesClient // routeTablesClient := meta.(*ArmClient).routeTablesClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["routeTables"] // name := id.Path["routeTables"]
//
_, err = routeTablesClient.Delete(resGroup, name) // _, err = routeTablesClient.Delete(resGroup, name)
//
return err // return err
} //}
//
func expandAzureRmRouteTableRoutes(d *schema.ResourceData) ([]network.Route, error) { //func expandAzureRmRouteTableRoutes(d *schema.ResourceData) ([]network.Route, error) {
configs := d.Get("route").(*schema.Set).List() // configs := d.Get("route").(*schema.Set).List()
routes := make([]network.Route, 0, len(configs)) // routes := make([]network.Route, 0, len(configs))
//
for _, configRaw := range configs { // for _, configRaw := range configs {
data := configRaw.(map[string]interface{}) // data := configRaw.(map[string]interface{})
//
address_prefix := data["address_prefix"].(string) // address_prefix := data["address_prefix"].(string)
next_hop_type := data["next_hop_type"].(string) // next_hop_type := data["next_hop_type"].(string)
//
properties := network.RoutePropertiesFormat{ // properties := network.RoutePropertiesFormat{
AddressPrefix: &address_prefix, // AddressPrefix: &address_prefix,
NextHopType: network.RouteNextHopType(next_hop_type), // NextHopType: network.RouteNextHopType(next_hop_type),
} // }
//
if v := data["next_hop_in_ip_address"].(string); v != "" { // if v := data["next_hop_in_ip_address"].(string); v != "" {
properties.NextHopIPAddress = &v // properties.NextHopIPAddress = &v
} // }
//
name := data["name"].(string) // name := data["name"].(string)
route := network.Route{ // route := network.Route{
Name: &name, // Name: &name,
Properties: &properties, // Properties: &properties,
} // }
//
routes = append(routes, route) // routes = append(routes, route)
} // }
//
return routes, nil // return routes, nil
} //}
//
func routeTableStateRefreshFunc(client *ArmClient, resourceGroupName string, routeTableName string) resource.StateRefreshFunc { //func routeTableStateRefreshFunc(client *ArmClient, resourceGroupName string, routeTableName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) { // return func() (interface{}, string, error) {
res, err := client.routeTablesClient.Get(resourceGroupName, routeTableName, "") // res, err := client.routeTablesClient.Get(resourceGroupName, routeTableName, "")
if err != nil { // if err != nil {
return nil, "", fmt.Errorf("Error issuing read request in routeTableStateRefreshFunc to Azure ARM for route table '%s' (RG: '%s'): %s", routeTableName, resourceGroupName, err) // return nil, "", fmt.Errorf("Error issuing read request in routeTableStateRefreshFunc to Azure ARM for route table '%s' (RG: '%s'): %s", routeTableName, resourceGroupName, err)
} // }
//
return res, *res.Properties.ProvisioningState, nil // return res, *res.Properties.ProvisioningState, nil
} // }
} //}
//
func resourceArmRouteTableRouteHash(v interface{}) int { //func resourceArmRouteTableRouteHash(v interface{}) int {
var buf bytes.Buffer // var buf bytes.Buffer
m := v.(map[string]interface{}) // m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["name"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["address_prefix"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["address_prefix"].(string)))
buf.WriteString(fmt.Sprintf("%s-", m["next_hop_type"].(string))) // buf.WriteString(fmt.Sprintf("%s-", m["next_hop_type"].(string)))
//
return hashcode.String(buf.String()) // return hashcode.String(buf.String())
} //}
//
func validateRouteTableNextHopType(v interface{}, k string) (ws []string, errors []error) { //func validateRouteTableNextHopType(v interface{}, k string) (ws []string, errors []error) {
value := strings.ToLower(v.(string)) // value := strings.ToLower(v.(string))
hopTypes := map[string]bool{ // hopTypes := map[string]bool{
"virtualnetworkgateway": true, // "virtualnetworkgateway": true,
"vnetlocal": true, // "vnetlocal": true,
"internet": true, // "internet": true,
"virtualappliance": true, // "virtualappliance": true,
"none": true, // "none": true,
} // }
//
if !hopTypes[value] { // if !hopTypes[value] {
errors = append(errors, fmt.Errorf("Route Table NextHopType Protocol can only be VirtualNetworkGateway, VnetLocal, Internet or VirtualAppliance")) // errors = append(errors, fmt.Errorf("Route Table NextHopType Protocol can only be VirtualNetworkGateway, VnetLocal, Internet or VirtualAppliance"))
} // }
return // return
} //}

View File

@ -1,294 +1,294 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"net/http" // "net/http"
"testing" // "testing"
//
"github.com/hashicorp/terraform/helper/acctest" // "github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" // "github.com/hashicorp/terraform/terraform"
) //)
//
func TestResourceAzureRMRouteTableNextHopType_validation(t *testing.T) { //func TestResourceAzureRMRouteTableNextHopType_validation(t *testing.T) {
cases := []struct { // cases := []struct {
Value string // Value string
ErrCount int // ErrCount int
}{ // }{
{ // {
Value: "Random", // Value: "Random",
ErrCount: 1, // ErrCount: 1,
}, // },
{ // {
Value: "VirtualNetworkGateway", // Value: "VirtualNetworkGateway",
ErrCount: 0, // ErrCount: 0,
}, // },
{ // {
Value: "VNETLocal", // Value: "VNETLocal",
ErrCount: 0, // ErrCount: 0,
}, // },
{ // {
Value: "Internet", // Value: "Internet",
ErrCount: 0, // ErrCount: 0,
}, // },
{ // {
Value: "VirtualAppliance", // Value: "VirtualAppliance",
ErrCount: 0, // ErrCount: 0,
}, // },
{ // {
Value: "None", // Value: "None",
ErrCount: 0, // ErrCount: 0,
}, // },
{ // {
Value: "VIRTUALNETWORKGATEWAY", // Value: "VIRTUALNETWORKGATEWAY",
ErrCount: 0, // ErrCount: 0,
}, // },
{ // {
Value: "virtualnetworkgateway", // Value: "virtualnetworkgateway",
ErrCount: 0, // ErrCount: 0,
}, // },
} // }
//
for _, tc := range cases { // for _, tc := range cases {
_, errors := validateRouteTableNextHopType(tc.Value, "azurerm_route_table") // _, errors := validateRouteTableNextHopType(tc.Value, "azurerm_route_table")
//
if len(errors) != tc.ErrCount { // if len(errors) != tc.ErrCount {
t.Fatalf("Expected the Azure RM Route Table nextHopType to trigger a validation error") // t.Fatalf("Expected the Azure RM Route Table nextHopType to trigger a validation error")
} // }
} // }
} //}
//
func TestAccAzureRMRouteTable_basic(t *testing.T) { //func TestAccAzureRMRouteTable_basic(t *testing.T) {
//
ri := acctest.RandInt() // ri := acctest.RandInt()
config := fmt.Sprintf(testAccAzureRMRouteTable_basic, ri, ri) // config := fmt.Sprintf(testAccAzureRMRouteTable_basic, ri, ri)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMRouteTableDestroy, // CheckDestroy: testCheckAzureRMRouteTableDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: config, // Config: config,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMRouteTableExists("azurerm_route_table.test"), // testCheckAzureRMRouteTableExists("azurerm_route_table.test"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func TestAccAzureRMRouteTable_withTags(t *testing.T) { //func TestAccAzureRMRouteTable_withTags(t *testing.T) {
//
ri := acctest.RandInt() // ri := acctest.RandInt()
preConfig := fmt.Sprintf(testAccAzureRMRouteTable_withTags, ri, ri) // preConfig := fmt.Sprintf(testAccAzureRMRouteTable_withTags, ri, ri)
postConfig := fmt.Sprintf(testAccAzureRMRouteTable_withTagsUpdate, ri, ri) // postConfig := fmt.Sprintf(testAccAzureRMRouteTable_withTagsUpdate, ri, ri)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMRouteTableDestroy, // CheckDestroy: testCheckAzureRMRouteTableDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: preConfig, // Config: preConfig,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMRouteTableExists("azurerm_route_table.test"), // testCheckAzureRMRouteTableExists("azurerm_route_table.test"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_route_table.test", "tags.#", "2"), // "azurerm_route_table.test", "tags.#", "2"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_route_table.test", "tags.environment", "Production"), // "azurerm_route_table.test", "tags.environment", "Production"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_route_table.test", "tags.cost_center", "MSFT"), // "azurerm_route_table.test", "tags.cost_center", "MSFT"),
), // ),
}, // },
//
resource.TestStep{ // resource.TestStep{
Config: postConfig, // Config: postConfig,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMRouteTableExists("azurerm_route_table.test"), // testCheckAzureRMRouteTableExists("azurerm_route_table.test"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_route_table.test", "tags.#", "1"), // "azurerm_route_table.test", "tags.#", "1"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_route_table.test", "tags.environment", "staging"), // "azurerm_route_table.test", "tags.environment", "staging"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func TestAccAzureRMRouteTable_multipleRoutes(t *testing.T) { //func TestAccAzureRMRouteTable_multipleRoutes(t *testing.T) {
//
ri := acctest.RandInt() // ri := acctest.RandInt()
preConfig := fmt.Sprintf(testAccAzureRMRouteTable_basic, ri, ri) // preConfig := fmt.Sprintf(testAccAzureRMRouteTable_basic, ri, ri)
postConfig := fmt.Sprintf(testAccAzureRMRouteTable_multipleRoutes, ri, ri) // postConfig := fmt.Sprintf(testAccAzureRMRouteTable_multipleRoutes, ri, ri)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMRouteTableDestroy, // CheckDestroy: testCheckAzureRMRouteTableDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: preConfig, // Config: preConfig,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMRouteTableExists("azurerm_route_table.test"), // testCheckAzureRMRouteTableExists("azurerm_route_table.test"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_route_table.test", "route.#", "1"), // "azurerm_route_table.test", "route.#", "1"),
), // ),
}, // },
//
resource.TestStep{ // resource.TestStep{
Config: postConfig, // Config: postConfig,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMRouteTableExists("azurerm_route_table.test"), // testCheckAzureRMRouteTableExists("azurerm_route_table.test"),
resource.TestCheckResourceAttr( // resource.TestCheckResourceAttr(
"azurerm_route_table.test", "route.#", "2"), // "azurerm_route_table.test", "route.#", "2"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func testCheckAzureRMRouteTableExists(name string) resource.TestCheckFunc { //func testCheckAzureRMRouteTableExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error { // return func(s *terraform.State) error {
//
rs, ok := s.RootModule().Resources[name] // rs, ok := s.RootModule().Resources[name]
if !ok { // if !ok {
return fmt.Errorf("Not found: %s", name) // return fmt.Errorf("Not found: %s", name)
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
if !hasResourceGroup { // if !hasResourceGroup {
return fmt.Errorf("Bad: no resource group found in state for route table: %s", name) // return fmt.Errorf("Bad: no resource group found in state for route table: %s", name)
} // }
//
conn := testAccProvider.Meta().(*ArmClient).routeTablesClient // conn := testAccProvider.Meta().(*ArmClient).routeTablesClient
//
resp, err := conn.Get(resourceGroup, name, "") // resp, err := conn.Get(resourceGroup, name, "")
if err != nil { // if err != nil {
return fmt.Errorf("Bad: Get on routeTablesClient: %s", err) // return fmt.Errorf("Bad: Get on routeTablesClient: %s", err)
} // }
//
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("Bad: Route Table %q (resource group: %q) does not exist", name, resourceGroup) // return fmt.Errorf("Bad: Route Table %q (resource group: %q) does not exist", name, resourceGroup)
} // }
//
return nil // return nil
} // }
} //}
//
func testCheckAzureRMRouteTableDestroy(s *terraform.State) error { //func testCheckAzureRMRouteTableDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*ArmClient).routeTablesClient // conn := testAccProvider.Meta().(*ArmClient).routeTablesClient
//
for _, rs := range s.RootModule().Resources { // for _, rs := range s.RootModule().Resources {
if rs.Type != "azurerm_route_table" { // if rs.Type != "azurerm_route_table" {
continue // continue
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup := rs.Primary.Attributes["resource_group_name"]
//
resp, err := conn.Get(resourceGroup, name, "") // resp, err := conn.Get(resourceGroup, name, "")
//
if err != nil { // if err != nil {
return nil // return nil
} // }
//
if resp.StatusCode != http.StatusNotFound { // if resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("Route Table still exists:\n%#v", resp.Properties) // return fmt.Errorf("Route Table still exists:\n%#v", resp.Properties)
} // }
} // }
//
return nil // return nil
} //}
//
var testAccAzureRMRouteTable_basic = ` //var testAccAzureRMRouteTable_basic = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
//
resource "azurerm_route_table" "test" { //resource "azurerm_route_table" "test" {
name = "acctestrt%d" // name = "acctestrt%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
//
route { // route {
name = "route1" // name = "route1"
address_prefix = "*" // address_prefix = "*"
next_hop_type = "internet" // next_hop_type = "internet"
} // }
} //}
` //`
//
var testAccAzureRMRouteTable_multipleRoutes = ` //var testAccAzureRMRouteTable_multipleRoutes = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
//
resource "azurerm_route_table" "test" { //resource "azurerm_route_table" "test" {
name = "acctestrt%d" // name = "acctestrt%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
//
route { // route {
name = "route1" // name = "route1"
address_prefix = "*" // address_prefix = "*"
next_hop_type = "internet" // next_hop_type = "internet"
} // }
//
route { // route {
name = "route2" // name = "route2"
address_prefix = "*" // address_prefix = "*"
next_hop_type = "virtualappliance" // next_hop_type = "virtualappliance"
} // }
} //}
` //`
//
var testAccAzureRMRouteTable_withTags = ` //var testAccAzureRMRouteTable_withTags = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
//
resource "azurerm_route_table" "test" { //resource "azurerm_route_table" "test" {
name = "acctestrt%d" // name = "acctestrt%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
//
route { // route {
name = "route1" // name = "route1"
address_prefix = "*" // address_prefix = "*"
next_hop_type = "internet" // next_hop_type = "internet"
} // }
//
tags { // tags {
environment = "Production" // environment = "Production"
cost_center = "MSFT" // cost_center = "MSFT"
} // }
} //}
` //`
//
var testAccAzureRMRouteTable_withTagsUpdate = ` //var testAccAzureRMRouteTable_withTagsUpdate = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
//
resource "azurerm_route_table" "test" { //resource "azurerm_route_table" "test" {
name = "acctestrt%d" // name = "acctestrt%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
//
route { // route {
name = "route1" // name = "route1"
address_prefix = "*" // address_prefix = "*"
next_hop_type = "internet" // next_hop_type = "internet"
} // }
//
tags { // tags {
environment = "staging" // environment = "staging"
} // }
} //}
` //`

View File

@ -1,159 +1,159 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"net/http" // "net/http"
"testing" // "testing"
//
"github.com/hashicorp/terraform/helper/acctest" // "github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" // "github.com/hashicorp/terraform/terraform"
) //)
//
func TestAccAzureRMRoute_basic(t *testing.T) { //func TestAccAzureRMRoute_basic(t *testing.T) {
//
ri := acctest.RandInt() // ri := acctest.RandInt()
config := fmt.Sprintf(testAccAzureRMRoute_basic, ri, ri, ri) // config := fmt.Sprintf(testAccAzureRMRoute_basic, ri, ri, ri)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMRouteDestroy, // CheckDestroy: testCheckAzureRMRouteDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: config, // Config: config,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMRouteExists("azurerm_route.test"), // testCheckAzureRMRouteExists("azurerm_route.test"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func TestAccAzureRMRoute_multipleRoutes(t *testing.T) { //func TestAccAzureRMRoute_multipleRoutes(t *testing.T) {
//
ri := acctest.RandInt() // ri := acctest.RandInt()
preConfig := fmt.Sprintf(testAccAzureRMRoute_basic, ri, ri, ri) // preConfig := fmt.Sprintf(testAccAzureRMRoute_basic, ri, ri, ri)
postConfig := fmt.Sprintf(testAccAzureRMRoute_multipleRoutes, ri, ri, ri) // postConfig := fmt.Sprintf(testAccAzureRMRoute_multipleRoutes, ri, ri, ri)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMRouteDestroy, // CheckDestroy: testCheckAzureRMRouteDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: preConfig, // Config: preConfig,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMRouteExists("azurerm_route.test"), // testCheckAzureRMRouteExists("azurerm_route.test"),
), // ),
}, // },
//
resource.TestStep{ // resource.TestStep{
Config: postConfig, // Config: postConfig,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMRouteExists("azurerm_route.test1"), // testCheckAzureRMRouteExists("azurerm_route.test1"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func testCheckAzureRMRouteExists(name string) resource.TestCheckFunc { //func testCheckAzureRMRouteExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error { // return func(s *terraform.State) error {
//
rs, ok := s.RootModule().Resources[name] // rs, ok := s.RootModule().Resources[name]
if !ok { // if !ok {
return fmt.Errorf("Not found: %s", name) // return fmt.Errorf("Not found: %s", name)
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
rtName := rs.Primary.Attributes["route_table_name"] // rtName := rs.Primary.Attributes["route_table_name"]
resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
if !hasResourceGroup { // if !hasResourceGroup {
return fmt.Errorf("Bad: no resource group found in state for route: %s", name) // return fmt.Errorf("Bad: no resource group found in state for route: %s", name)
} // }
//
conn := testAccProvider.Meta().(*ArmClient).routesClient // conn := testAccProvider.Meta().(*ArmClient).routesClient
//
resp, err := conn.Get(resourceGroup, rtName, name) // resp, err := conn.Get(resourceGroup, rtName, name)
if err != nil { // if err != nil {
return fmt.Errorf("Bad: Get on routesClient: %s", err) // return fmt.Errorf("Bad: Get on routesClient: %s", err)
} // }
//
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("Bad: Route %q (resource group: %q) does not exist", name, resourceGroup) // return fmt.Errorf("Bad: Route %q (resource group: %q) does not exist", name, resourceGroup)
} // }
//
return nil // return nil
} // }
} //}
//
func testCheckAzureRMRouteDestroy(s *terraform.State) error { //func testCheckAzureRMRouteDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*ArmClient).routesClient // conn := testAccProvider.Meta().(*ArmClient).routesClient
//
for _, rs := range s.RootModule().Resources { // for _, rs := range s.RootModule().Resources {
if rs.Type != "azurerm_route" { // if rs.Type != "azurerm_route" {
continue // continue
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
rtName := rs.Primary.Attributes["route_table_name"] // rtName := rs.Primary.Attributes["route_table_name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup := rs.Primary.Attributes["resource_group_name"]
//
resp, err := conn.Get(resourceGroup, rtName, name) // resp, err := conn.Get(resourceGroup, rtName, name)
//
if err != nil { // if err != nil {
return nil // return nil
} // }
//
if resp.StatusCode != http.StatusNotFound { // if resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("Route still exists:\n%#v", resp.Properties) // return fmt.Errorf("Route still exists:\n%#v", resp.Properties)
} // }
} // }
//
return nil // return nil
} //}
//
var testAccAzureRMRoute_basic = ` //var testAccAzureRMRoute_basic = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
//
resource "azurerm_route_table" "test" { //resource "azurerm_route_table" "test" {
name = "acctestrt%d" // name = "acctestrt%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
} //}
//
resource "azurerm_route" "test" { //resource "azurerm_route" "test" {
name = "acctestroute%d" // name = "acctestroute%d"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
route_table_name = "${azurerm_route_table.test.name}" // route_table_name = "${azurerm_route_table.test.name}"
//
address_prefix = "10.1.0.0/16" // address_prefix = "10.1.0.0/16"
next_hop_type = "vnetlocal" // next_hop_type = "vnetlocal"
} //}
` //`
//
var testAccAzureRMRoute_multipleRoutes = ` //var testAccAzureRMRoute_multipleRoutes = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
//
resource "azurerm_route_table" "test" { //resource "azurerm_route_table" "test" {
name = "acctestrt%d" // name = "acctestrt%d"
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
} //}
//
resource "azurerm_route" "test1" { //resource "azurerm_route" "test1" {
name = "acctestroute%d" // name = "acctestroute%d"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
route_table_name = "${azurerm_route_table.test.name}" // route_table_name = "${azurerm_route_table.test.name}"
//
address_prefix = "10.2.0.0/16" // address_prefix = "10.2.0.0/16"
next_hop_type = "none" // next_hop_type = "none"
} //}
` //`

View File

@ -1,309 +1,309 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"net/http" // "net/http"
"regexp" // "regexp"
"strings" // "strings"
//
"github.com/Azure/azure-sdk-for-go/arm/storage" // "github.com/Azure/azure-sdk-for-go/arm/storage"
"github.com/hashicorp/terraform/helper/schema" // "github.com/hashicorp/terraform/helper/schema"
) //)
//
func resourceArmStorageAccount() *schema.Resource { //func resourceArmStorageAccount() *schema.Resource {
return &schema.Resource{ // return &schema.Resource{
Create: resourceArmStorageAccountCreate, // Create: resourceArmStorageAccountCreate,
Read: resourceArmStorageAccountRead, // Read: resourceArmStorageAccountRead,
Update: resourceArmStorageAccountUpdate, // Update: resourceArmStorageAccountUpdate,
Delete: resourceArmStorageAccountDelete, // Delete: resourceArmStorageAccountDelete,
//
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
ValidateFunc: validateArmStorageAccountName, // ValidateFunc: validateArmStorageAccountName,
}, // },
//
"resource_group_name": &schema.Schema{ // "resource_group_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"location": &schema.Schema{ // "location": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
StateFunc: azureRMNormalizeLocation, // StateFunc: azureRMNormalizeLocation,
}, // },
//
"account_type": &schema.Schema{ // "account_type": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ValidateFunc: validateArmStorageAccountType, // ValidateFunc: validateArmStorageAccountType,
}, // },
//
"primary_location": &schema.Schema{ // "primary_location": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Computed: true, // Computed: true,
}, // },
//
"secondary_location": &schema.Schema{ // "secondary_location": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Computed: true, // Computed: true,
}, // },
//
"primary_blob_endpoint": &schema.Schema{ // "primary_blob_endpoint": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Computed: true, // Computed: true,
}, // },
//
"secondary_blob_endpoint": &schema.Schema{ // "secondary_blob_endpoint": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Computed: true, // Computed: true,
}, // },
//
"primary_queue_endpoint": &schema.Schema{ // "primary_queue_endpoint": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Computed: true, // Computed: true,
}, // },
//
"secondary_queue_endpoint": &schema.Schema{ // "secondary_queue_endpoint": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Computed: true, // Computed: true,
}, // },
//
"primary_table_endpoint": &schema.Schema{ // "primary_table_endpoint": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Computed: true, // Computed: true,
}, // },
//
"secondary_table_endpoint": &schema.Schema{ // "secondary_table_endpoint": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Computed: true, // Computed: true,
}, // },
//
// NOTE: The API does not appear to expose a secondary file endpoint // // NOTE: The API does not appear to expose a secondary file endpoint
"primary_file_endpoint": &schema.Schema{ // "primary_file_endpoint": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Computed: true, // Computed: true,
}, // },
//
"primary_access_key": &schema.Schema{ // "primary_access_key": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Computed: true, // Computed: true,
}, // },
//
"secondary_access_key": &schema.Schema{ // "secondary_access_key": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Computed: true, // Computed: true,
}, // },
//
"tags": tagsSchema(), // "tags": tagsSchema(),
}, // },
} // }
} //}
//
func resourceArmStorageAccountCreate(d *schema.ResourceData, meta interface{}) error { //func resourceArmStorageAccountCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).storageServiceClient // client := meta.(*ArmClient).storageServiceClient
//
resourceGroupName := d.Get("resource_group_name").(string) // resourceGroupName := d.Get("resource_group_name").(string)
storageAccountName := d.Get("name").(string) // storageAccountName := d.Get("name").(string)
accountType := d.Get("account_type").(string) // accountType := d.Get("account_type").(string)
location := d.Get("location").(string) // location := d.Get("location").(string)
tags := d.Get("tags").(map[string]interface{}) // tags := d.Get("tags").(map[string]interface{})
//
opts := storage.AccountCreateParameters{ // opts := storage.AccountCreateParameters{
Location: &location, // Location: &location,
Properties: &storage.AccountPropertiesCreateParameters{ // Properties: &storage.AccountPropertiesCreateParameters{
AccountType: storage.AccountType(accountType), // AccountType: storage.AccountType(accountType),
}, // },
Tags: expandTags(tags), // Tags: expandTags(tags),
} // }
//
accResp, err := client.Create(resourceGroupName, storageAccountName, opts) // accResp, err := client.Create(resourceGroupName, storageAccountName, opts)
if err != nil { // if err != nil {
return fmt.Errorf("Error creating Azure Storage Account '%s': %s", storageAccountName, err) // return fmt.Errorf("Error creating Azure Storage Account '%s': %s", storageAccountName, err)
} // }
_, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK) // _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK)
if err != nil { // if err != nil {
return fmt.Errorf("Error creating Azure Storage Account %q: %s", storageAccountName, err) // return fmt.Errorf("Error creating Azure Storage Account %q: %s", storageAccountName, err)
} // }
//
// The only way to get the ID back apparently is to read the resource again // // The only way to get the ID back apparently is to read the resource again
account, err := client.GetProperties(resourceGroupName, storageAccountName) // account, err := client.GetProperties(resourceGroupName, storageAccountName)
if err != nil { // if err != nil {
return fmt.Errorf("Error retrieving Azure Storage Account %q: %s", storageAccountName, err) // return fmt.Errorf("Error retrieving Azure Storage Account %q: %s", storageAccountName, err)
} // }
//
d.SetId(*account.ID) // d.SetId(*account.ID)
//
return resourceArmStorageAccountRead(d, meta) // return resourceArmStorageAccountRead(d, meta)
} //}
//
// resourceArmStorageAccountUpdate is unusual in the ARM API where most resources have a combined //// resourceArmStorageAccountUpdate is unusual in the ARM API where most resources have a combined
// and idempotent operation for CreateOrUpdate. In particular updating all of the parameters //// and idempotent operation for CreateOrUpdate. In particular updating all of the parameters
// available requires a call to Update per parameter... //// available requires a call to Update per parameter...
func resourceArmStorageAccountUpdate(d *schema.ResourceData, meta interface{}) error { //func resourceArmStorageAccountUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).storageServiceClient // client := meta.(*ArmClient).storageServiceClient
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
storageAccountName := id.Path["storageAccounts"] // storageAccountName := id.Path["storageAccounts"]
resourceGroupName := id.ResourceGroup // resourceGroupName := id.ResourceGroup
//
d.Partial(true) // d.Partial(true)
//
if d.HasChange("account_type") { // if d.HasChange("account_type") {
accountType := d.Get("account_type").(string) // accountType := d.Get("account_type").(string)
//
opts := storage.AccountUpdateParameters{ // opts := storage.AccountUpdateParameters{
Properties: &storage.AccountPropertiesUpdateParameters{ // Properties: &storage.AccountPropertiesUpdateParameters{
AccountType: storage.AccountType(accountType), // AccountType: storage.AccountType(accountType),
}, // },
} // }
accResp, err := client.Update(resourceGroupName, storageAccountName, opts) // accResp, err := client.Update(resourceGroupName, storageAccountName, opts)
if err != nil { // if err != nil {
return fmt.Errorf("Error updating Azure Storage Account type %q: %s", storageAccountName, err) // return fmt.Errorf("Error updating Azure Storage Account type %q: %s", storageAccountName, err)
} // }
_, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK) // _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK)
if err != nil { // if err != nil {
return fmt.Errorf("Error updating Azure Storage Account type %q: %s", storageAccountName, err) // return fmt.Errorf("Error updating Azure Storage Account type %q: %s", storageAccountName, err)
} // }
//
d.SetPartial("account_type") // d.SetPartial("account_type")
} // }
//
if d.HasChange("tags") { // if d.HasChange("tags") {
tags := d.Get("tags").(map[string]interface{}) // tags := d.Get("tags").(map[string]interface{})
//
opts := storage.AccountUpdateParameters{ // opts := storage.AccountUpdateParameters{
Tags: expandTags(tags), // Tags: expandTags(tags),
} // }
accResp, err := client.Update(resourceGroupName, storageAccountName, opts) // accResp, err := client.Update(resourceGroupName, storageAccountName, opts)
if err != nil { // if err != nil {
return fmt.Errorf("Error updating Azure Storage Account tags %q: %s", storageAccountName, err) // return fmt.Errorf("Error updating Azure Storage Account tags %q: %s", storageAccountName, err)
} // }
_, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK) // _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK)
if err != nil { // if err != nil {
return fmt.Errorf("Error updating Azure Storage Account tags %q: %s", storageAccountName, err) // return fmt.Errorf("Error updating Azure Storage Account tags %q: %s", storageAccountName, err)
} // }
//
d.SetPartial("tags") // d.SetPartial("tags")
} // }
//
d.Partial(false) // d.Partial(false)
return nil // return nil
} //}
//
func resourceArmStorageAccountRead(d *schema.ResourceData, meta interface{}) error { //func resourceArmStorageAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).storageServiceClient // client := meta.(*ArmClient).storageServiceClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
name := id.Path["storageAccounts"] // name := id.Path["storageAccounts"]
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
//
resp, err := client.GetProperties(resGroup, name) // resp, err := client.GetProperties(resGroup, name)
if err != nil { // if err != nil {
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
d.SetId("") // d.SetId("")
return nil // return nil
} // }
//
return fmt.Errorf("Error reading the state of AzureRM Storage Account %q: %s", name, err) // return fmt.Errorf("Error reading the state of AzureRM Storage Account %q: %s", name, err)
} // }
//
keys, err := client.ListKeys(resGroup, name) // keys, err := client.ListKeys(resGroup, name)
if err != nil { // if err != nil {
return err // return err
} // }
//
d.Set("primary_access_key", keys.Key1) // d.Set("primary_access_key", keys.Key1)
d.Set("secondary_access_key", keys.Key2) // d.Set("secondary_access_key", keys.Key2)
d.Set("location", resp.Location) // d.Set("location", resp.Location)
d.Set("account_type", resp.Properties.AccountType) // d.Set("account_type", resp.Properties.AccountType)
d.Set("primary_location", resp.Properties.PrimaryLocation) // d.Set("primary_location", resp.Properties.PrimaryLocation)
d.Set("secondary_location", resp.Properties.SecondaryLocation) // d.Set("secondary_location", resp.Properties.SecondaryLocation)
//
if resp.Properties.PrimaryEndpoints != nil { // if resp.Properties.PrimaryEndpoints != nil {
d.Set("primary_blob_endpoint", resp.Properties.PrimaryEndpoints.Blob) // d.Set("primary_blob_endpoint", resp.Properties.PrimaryEndpoints.Blob)
d.Set("primary_queue_endpoint", resp.Properties.PrimaryEndpoints.Queue) // d.Set("primary_queue_endpoint", resp.Properties.PrimaryEndpoints.Queue)
d.Set("primary_table_endpoint", resp.Properties.PrimaryEndpoints.Table) // d.Set("primary_table_endpoint", resp.Properties.PrimaryEndpoints.Table)
d.Set("primary_file_endpoint", resp.Properties.PrimaryEndpoints.File) // d.Set("primary_file_endpoint", resp.Properties.PrimaryEndpoints.File)
} // }
//
if resp.Properties.SecondaryEndpoints != nil { // if resp.Properties.SecondaryEndpoints != nil {
if resp.Properties.SecondaryEndpoints.Blob != nil { // if resp.Properties.SecondaryEndpoints.Blob != nil {
d.Set("secondary_blob_endpoint", resp.Properties.SecondaryEndpoints.Blob) // d.Set("secondary_blob_endpoint", resp.Properties.SecondaryEndpoints.Blob)
} else { // } else {
d.Set("secondary_blob_endpoint", "") // d.Set("secondary_blob_endpoint", "")
} // }
if resp.Properties.SecondaryEndpoints.Queue != nil { // if resp.Properties.SecondaryEndpoints.Queue != nil {
d.Set("secondary_queue_endpoint", resp.Properties.SecondaryEndpoints.Queue) // d.Set("secondary_queue_endpoint", resp.Properties.SecondaryEndpoints.Queue)
} else { // } else {
d.Set("secondary_queue_endpoint", "") // d.Set("secondary_queue_endpoint", "")
} // }
if resp.Properties.SecondaryEndpoints.Table != nil { // if resp.Properties.SecondaryEndpoints.Table != nil {
d.Set("secondary_table_endpoint", resp.Properties.SecondaryEndpoints.Table) // d.Set("secondary_table_endpoint", resp.Properties.SecondaryEndpoints.Table)
} else { // } else {
d.Set("secondary_table_endpoint", "") // d.Set("secondary_table_endpoint", "")
} // }
} // }
//
flattenAndSetTags(d, resp.Tags) // flattenAndSetTags(d, resp.Tags)
//
return nil // return nil
} //}
//
func resourceArmStorageAccountDelete(d *schema.ResourceData, meta interface{}) error { //func resourceArmStorageAccountDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).storageServiceClient // client := meta.(*ArmClient).storageServiceClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
name := id.Path["storageAccounts"] // name := id.Path["storageAccounts"]
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
//
accResp, err := client.Delete(resGroup, name) // accResp, err := client.Delete(resGroup, name)
if err != nil { // if err != nil {
return fmt.Errorf("Error issuing AzureRM delete request for storage account %q: %s", name, err) // return fmt.Errorf("Error issuing AzureRM delete request for storage account %q: %s", name, err)
} // }
_, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response, http.StatusNotFound) // _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response, http.StatusNotFound)
if err != nil { // if err != nil {
return fmt.Errorf("Error polling for AzureRM delete request for storage account %q: %s", name, err) // return fmt.Errorf("Error polling for AzureRM delete request for storage account %q: %s", name, err)
} // }
//
return nil // return nil
} //}
//
func validateArmStorageAccountName(v interface{}, k string) (ws []string, es []error) { //func validateArmStorageAccountName(v interface{}, k string) (ws []string, es []error) {
input := v.(string) // input := v.(string)
//
if !regexp.MustCompile(`\A([a-z0-9]{3,24})\z`).MatchString(input) { // if !regexp.MustCompile(`\A([a-z0-9]{3,24})\z`).MatchString(input) {
es = append(es, fmt.Errorf("name can only consist of lowercase letters and numbers, and must be between 3 and 24 characters long")) // es = append(es, fmt.Errorf("name can only consist of lowercase letters and numbers, and must be between 3 and 24 characters long"))
} // }
//
return // return
} //}
//
func validateArmStorageAccountType(v interface{}, k string) (ws []string, es []error) { //func validateArmStorageAccountType(v interface{}, k string) (ws []string, es []error) {
validAccountTypes := []string{"standard_lrs", "standard_zrs", // validAccountTypes := []string{"standard_lrs", "standard_zrs",
"standard_grs", "standard_ragrs", "premium_lrs"} // "standard_grs", "standard_ragrs", "premium_lrs"}
//
input := strings.ToLower(v.(string)) // input := strings.ToLower(v.(string))
//
for _, valid := range validAccountTypes { // for _, valid := range validAccountTypes {
if valid == input { // if valid == input {
return // return
} // }
} // }
//
es = append(es, fmt.Errorf("Invalid storage account type %q", input)) // es = append(es, fmt.Errorf("Invalid storage account type %q", input))
return // return
} //}

View File

@ -1,166 +1,166 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"net/http" // "net/http"
"testing" // "testing"
//
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" // "github.com/hashicorp/terraform/terraform"
) //)
//
func TestValidateArmStorageAccountType(t *testing.T) { //func TestValidateArmStorageAccountType(t *testing.T) {
testCases := []struct { // testCases := []struct {
input string // input string
shouldError bool // shouldError bool
}{ // }{
{"standard_lrs", false}, // {"standard_lrs", false},
{"invalid", true}, // {"invalid", true},
} // }
//
for _, test := range testCases { // for _, test := range testCases {
_, es := validateArmStorageAccountType(test.input, "account_type") // _, es := validateArmStorageAccountType(test.input, "account_type")
//
if test.shouldError && len(es) == 0 { // if test.shouldError && len(es) == 0 {
t.Fatalf("Expected validating account_type %q to fail", test.input) // t.Fatalf("Expected validating account_type %q to fail", test.input)
} // }
} // }
} //}
//
func TestValidateArmStorageAccountName(t *testing.T) { //func TestValidateArmStorageAccountName(t *testing.T) {
testCases := []struct { // testCases := []struct {
input string // input string
shouldError bool // shouldError bool
}{ // }{
{"ab", true}, // {"ab", true},
{"ABC", true}, // {"ABC", true},
{"abc", false}, // {"abc", false},
{"123456789012345678901234", false}, // {"123456789012345678901234", false},
{"1234567890123456789012345", true}, // {"1234567890123456789012345", true},
{"abc12345", false}, // {"abc12345", false},
} // }
//
for _, test := range testCases { // for _, test := range testCases {
_, es := validateArmStorageAccountName(test.input, "name") // _, es := validateArmStorageAccountName(test.input, "name")
//
if test.shouldError && len(es) == 0 { // if test.shouldError && len(es) == 0 {
t.Fatalf("Expected validating name %q to fail", test.input) // t.Fatalf("Expected validating name %q to fail", test.input)
} // }
} // }
} //}
//
func TestAccAzureRMStorageAccount_basic(t *testing.T) { //func TestAccAzureRMStorageAccount_basic(t *testing.T) {
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMStorageAccountDestroy, // CheckDestroy: testCheckAzureRMStorageAccountDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: testAccAzureRMStorageAccount_basic, // Config: testAccAzureRMStorageAccount_basic,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMStorageAccountExists("azurerm_storage_account.testsa"), // testCheckAzureRMStorageAccountExists("azurerm_storage_account.testsa"),
resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "account_type", "Standard_LRS"), // resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "account_type", "Standard_LRS"),
resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.#", "1"), // resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.#", "1"),
resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.environment", "production"), // resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.environment", "production"),
), // ),
}, // },
//
resource.TestStep{ // resource.TestStep{
Config: testAccAzureRMStorageAccount_update, // Config: testAccAzureRMStorageAccount_update,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMStorageAccountExists("azurerm_storage_account.testsa"), // testCheckAzureRMStorageAccountExists("azurerm_storage_account.testsa"),
resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "account_type", "Standard_GRS"), // resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "account_type", "Standard_GRS"),
resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.#", "1"), // resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.#", "1"),
resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.environment", "staging"), // resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.environment", "staging"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func testCheckAzureRMStorageAccountExists(name string) resource.TestCheckFunc { //func testCheckAzureRMStorageAccountExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error { // return func(s *terraform.State) error {
// Ensure we have enough information in state to look up in API // // Ensure we have enough information in state to look up in API
rs, ok := s.RootModule().Resources[name] // rs, ok := s.RootModule().Resources[name]
if !ok { // if !ok {
return fmt.Errorf("Not found: %s", name) // return fmt.Errorf("Not found: %s", name)
} // }
//
storageAccount := rs.Primary.Attributes["name"] // storageAccount := rs.Primary.Attributes["name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup := rs.Primary.Attributes["resource_group_name"]
//
// Ensure resource group exists in API // // Ensure resource group exists in API
conn := testAccProvider.Meta().(*ArmClient).storageServiceClient // conn := testAccProvider.Meta().(*ArmClient).storageServiceClient
//
resp, err := conn.GetProperties(resourceGroup, storageAccount) // resp, err := conn.GetProperties(resourceGroup, storageAccount)
if err != nil { // if err != nil {
return fmt.Errorf("Bad: Get on storageServiceClient: %s", err) // return fmt.Errorf("Bad: Get on storageServiceClient: %s", err)
} // }
//
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("Bad: StorageAccount %q (resource group: %q) does not exist", name, resourceGroup) // return fmt.Errorf("Bad: StorageAccount %q (resource group: %q) does not exist", name, resourceGroup)
} // }
//
return nil // return nil
} // }
} //}
//
func testCheckAzureRMStorageAccountDestroy(s *terraform.State) error { //func testCheckAzureRMStorageAccountDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*ArmClient).storageServiceClient // conn := testAccProvider.Meta().(*ArmClient).storageServiceClient
//
for _, rs := range s.RootModule().Resources { // for _, rs := range s.RootModule().Resources {
if rs.Type != "azurerm_storage_account" { // if rs.Type != "azurerm_storage_account" {
continue // continue
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup := rs.Primary.Attributes["resource_group_name"]
//
resp, err := conn.GetProperties(resourceGroup, name) // resp, err := conn.GetProperties(resourceGroup, name)
if err != nil { // if err != nil {
return nil // return nil
} // }
//
if resp.StatusCode != http.StatusNotFound { // if resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("Storage Account still exists:\n%#v", resp.Properties) // return fmt.Errorf("Storage Account still exists:\n%#v", resp.Properties)
} // }
} // }
//
return nil // return nil
} //}
//
var testAccAzureRMStorageAccount_basic = ` //var testAccAzureRMStorageAccount_basic = `
resource "azurerm_resource_group" "testrg" { //resource "azurerm_resource_group" "testrg" {
name = "testAccAzureRMStorageAccountBasic" // name = "testAccAzureRMStorageAccountBasic"
location = "westus" // location = "westus"
} //}
//
resource "azurerm_storage_account" "testsa" { //resource "azurerm_storage_account" "testsa" {
name = "unlikely23exst2acct1435" // name = "unlikely23exst2acct1435"
resource_group_name = "${azurerm_resource_group.testrg.name}" // resource_group_name = "${azurerm_resource_group.testrg.name}"
//
location = "westus" // location = "westus"
account_type = "Standard_LRS" // account_type = "Standard_LRS"
//
tags { // tags {
environment = "production" // environment = "production"
} // }
}` //}`
//
var testAccAzureRMStorageAccount_update = ` //var testAccAzureRMStorageAccount_update = `
resource "azurerm_resource_group" "testrg" { //resource "azurerm_resource_group" "testrg" {
name = "testAccAzureRMStorageAccountBasic" // name = "testAccAzureRMStorageAccountBasic"
location = "westus" // location = "westus"
} //}
//
resource "azurerm_storage_account" "testsa" { //resource "azurerm_storage_account" "testsa" {
name = "unlikely23exst2acct1435" // name = "unlikely23exst2acct1435"
resource_group_name = "${azurerm_resource_group.testrg.name}" // resource_group_name = "${azurerm_resource_group.testrg.name}"
//
location = "westus" // location = "westus"
account_type = "Standard_GRS" // account_type = "Standard_GRS"
//
tags { // tags {
environment = "staging" // environment = "staging"
} // }
}` //}`

View File

@ -16,12 +16,12 @@ func resourceArmStorageBlob() *schema.Resource {
Delete: resourceArmStorageBlobDelete, Delete: resourceArmStorageBlobDelete,
Schema: map[string]*schema.Schema{ Schema: map[string]*schema.Schema{
"name": &schema.Schema{ "name": {
Type: schema.TypeString, Type: schema.TypeString,
Required: true, Required: true,
ForceNew: true, ForceNew: true,
}, },
"resource_group_name": &schema.Schema{ "resource_group_name": {
Type: schema.TypeString, Type: schema.TypeString,
Required: true, Required: true,
ForceNew: true, ForceNew: true,
@ -31,25 +31,25 @@ func resourceArmStorageBlob() *schema.Resource {
Required: true, Required: true,
ForceNew: true, ForceNew: true,
}, },
"storage_container_name": &schema.Schema{ "storage_container_name": {
Type: schema.TypeString, Type: schema.TypeString,
Required: true, Required: true,
ForceNew: true, ForceNew: true,
}, },
"type": &schema.Schema{ "type": {
Type: schema.TypeString, Type: schema.TypeString,
Required: true, Required: true,
ForceNew: true, ForceNew: true,
ValidateFunc: validateArmStorageBlobType, ValidateFunc: validateArmStorageBlobType,
}, },
"size": &schema.Schema{ "size": {
Type: schema.TypeInt, Type: schema.TypeInt,
Optional: true, Optional: true,
ForceNew: true, ForceNew: true,
Default: 0, Default: 0,
ValidateFunc: validateArmStorageBlobSize, ValidateFunc: validateArmStorageBlobSize,
}, },
"url": &schema.Schema{ "url": {
Type: schema.TypeString, Type: schema.TypeString,
Computed: true, Computed: true,
}, },
@ -204,7 +204,7 @@ func resourceArmStorageBlobDelete(d *schema.ResourceData, meta interface{}) erro
storageContainerName := d.Get("storage_container_name").(string) storageContainerName := d.Get("storage_container_name").(string)
log.Printf("[INFO] Deleting storage blob %q", name) log.Printf("[INFO] Deleting storage blob %q", name)
if _, err = blobClient.DeleteBlobIfExists(storageContainerName, name); err != nil { if _, err = blobClient.DeleteBlobIfExists(storageContainerName, name, map[string]string{}); err != nil {
return fmt.Errorf("Error deleting storage blob %q: %s", name, err) return fmt.Errorf("Error deleting storage blob %q: %s", name, err)
} }

View File

@ -1,227 +1,227 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"log" // "log"
"strings" // "strings"
//
"regexp" // "regexp"
//
"github.com/Azure/azure-sdk-for-go/storage" // "github.com/Azure/azure-sdk-for-go/storage"
"github.com/hashicorp/terraform/helper/schema" // "github.com/hashicorp/terraform/helper/schema"
) //)
//
func resourceArmStorageContainer() *schema.Resource { //func resourceArmStorageContainer() *schema.Resource {
return &schema.Resource{ // return &schema.Resource{
Create: resourceArmStorageContainerCreate, // Create: resourceArmStorageContainerCreate,
Read: resourceArmStorageContainerRead, // Read: resourceArmStorageContainerRead,
Exists: resourceArmStorageContainerExists, // Exists: resourceArmStorageContainerExists,
Delete: resourceArmStorageContainerDelete, // Delete: resourceArmStorageContainerDelete,
//
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
ValidateFunc: validateArmStorageContainerName, // ValidateFunc: validateArmStorageContainerName,
}, // },
"resource_group_name": &schema.Schema{ // "resource_group_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
"storage_account_name": &schema.Schema{ // "storage_account_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
"container_access_type": &schema.Schema{ // "container_access_type": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
ForceNew: true, // ForceNew: true,
Default: "private", // Default: "private",
ValidateFunc: validateArmStorageContainerAccessType, // ValidateFunc: validateArmStorageContainerAccessType,
}, // },
"properties": &schema.Schema{ // "properties": &schema.Schema{
Type: schema.TypeMap, // Type: schema.TypeMap,
Computed: true, // Computed: true,
}, // },
}, // },
} // }
} //}
//
//Following the naming convention as laid out in the docs ////Following the naming convention as laid out in the docs
func validateArmStorageContainerName(v interface{}, k string) (ws []string, errors []error) { //func validateArmStorageContainerName(v interface{}, k string) (ws []string, errors []error) {
value := v.(string) // value := v.(string)
if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) { // if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) {
errors = append(errors, fmt.Errorf( // errors = append(errors, fmt.Errorf(
"only lowercase alphanumeric characters and hyphens allowed in %q: %q", // "only lowercase alphanumeric characters and hyphens allowed in %q: %q",
k, value)) // k, value))
} // }
if len(value) < 3 || len(value) > 63 { // if len(value) < 3 || len(value) > 63 {
errors = append(errors, fmt.Errorf( // errors = append(errors, fmt.Errorf(
"%q must be between 3 and 63 characters: %q", k, value)) // "%q must be between 3 and 63 characters: %q", k, value))
} // }
if regexp.MustCompile(`^-`).MatchString(value) { // if regexp.MustCompile(`^-`).MatchString(value) {
errors = append(errors, fmt.Errorf( // errors = append(errors, fmt.Errorf(
"%q cannot begin with a hyphen: %q", k, value)) // "%q cannot begin with a hyphen: %q", k, value))
} // }
return // return
} //}
//
func validateArmStorageContainerAccessType(v interface{}, k string) (ws []string, errors []error) { //func validateArmStorageContainerAccessType(v interface{}, k string) (ws []string, errors []error) {
value := strings.ToLower(v.(string)) // value := strings.ToLower(v.(string))
validTypes := map[string]struct{}{ // validTypes := map[string]struct{}{
"private": struct{}{}, // "private": struct{}{},
"blob": struct{}{}, // "blob": struct{}{},
"container": struct{}{}, // "container": struct{}{},
} // }
//
if _, ok := validTypes[value]; !ok { // if _, ok := validTypes[value]; !ok {
errors = append(errors, fmt.Errorf("Storage container access type %q is invalid, must be %q, %q or %q", value, "private", "blob", "page")) // errors = append(errors, fmt.Errorf("Storage container access type %q is invalid, must be %q, %q or %q", value, "private", "blob", "page"))
} // }
return // return
} //}
//
func resourceArmStorageContainerCreate(d *schema.ResourceData, meta interface{}) error { //func resourceArmStorageContainerCreate(d *schema.ResourceData, meta interface{}) error {
armClient := meta.(*ArmClient) // armClient := meta.(*ArmClient)
//
resourceGroupName := d.Get("resource_group_name").(string) // resourceGroupName := d.Get("resource_group_name").(string)
storageAccountName := d.Get("storage_account_name").(string) // storageAccountName := d.Get("storage_account_name").(string)
//
blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) // blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName)
if err != nil { // if err != nil {
return err // return err
} // }
if !accountExists { // if !accountExists {
return fmt.Errorf("Storage Account %q Not Found", storageAccountName) // return fmt.Errorf("Storage Account %q Not Found", storageAccountName)
} // }
//
name := d.Get("name").(string) // name := d.Get("name").(string)
//
var accessType storage.ContainerAccessType // var accessType storage.ContainerAccessType
if d.Get("container_access_type").(string) == "private" { // if d.Get("container_access_type").(string) == "private" {
accessType = storage.ContainerAccessType("") // accessType = storage.ContainerAccessType("")
} else { // } else {
accessType = storage.ContainerAccessType(d.Get("container_access_type").(string)) // accessType = storage.ContainerAccessType(d.Get("container_access_type").(string))
} // }
//
log.Printf("[INFO] Creating container %q in storage account %q.", name, storageAccountName) // log.Printf("[INFO] Creating container %q in storage account %q.", name, storageAccountName)
_, err = blobClient.CreateContainerIfNotExists(name, accessType) // _, err = blobClient.CreateContainerIfNotExists(name, accessType)
if err != nil { // if err != nil {
return fmt.Errorf("Error creating container %q in storage account %q: %s", name, storageAccountName, err) // return fmt.Errorf("Error creating container %q in storage account %q: %s", name, storageAccountName, err)
} // }
//
d.SetId(name) // d.SetId(name)
return resourceArmStorageContainerRead(d, meta) // return resourceArmStorageContainerRead(d, meta)
} //}
//
// resourceAzureStorageContainerRead does all the necessary API calls to //// resourceAzureStorageContainerRead does all the necessary API calls to
// read the status of the storage container off Azure. //// read the status of the storage container off Azure.
func resourceArmStorageContainerRead(d *schema.ResourceData, meta interface{}) error { //func resourceArmStorageContainerRead(d *schema.ResourceData, meta interface{}) error {
armClient := meta.(*ArmClient) // armClient := meta.(*ArmClient)
//
resourceGroupName := d.Get("resource_group_name").(string) // resourceGroupName := d.Get("resource_group_name").(string)
storageAccountName := d.Get("storage_account_name").(string) // storageAccountName := d.Get("storage_account_name").(string)
//
blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) // blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName)
if err != nil { // if err != nil {
return err // return err
} // }
if !accountExists { // if !accountExists {
log.Printf("[DEBUG] Storage account %q not found, removing container %q from state", storageAccountName, d.Id()) // log.Printf("[DEBUG] Storage account %q not found, removing container %q from state", storageAccountName, d.Id())
d.SetId("") // d.SetId("")
return nil // return nil
} // }
//
name := d.Get("name").(string) // name := d.Get("name").(string)
containers, err := blobClient.ListContainers(storage.ListContainersParameters{ // containers, err := blobClient.ListContainers(storage.ListContainersParameters{
Prefix: name, // Prefix: name,
Timeout: 90, // Timeout: 90,
}) // })
if err != nil { // if err != nil {
return fmt.Errorf("Failed to retrieve storage containers in account %q: %s", name, err) // return fmt.Errorf("Failed to retrieve storage containers in account %q: %s", name, err)
} // }
//
var found bool // var found bool
for _, cont := range containers.Containers { // for _, cont := range containers.Containers {
if cont.Name == name { // if cont.Name == name {
found = true // found = true
//
props := make(map[string]interface{}) // props := make(map[string]interface{})
props["last_modified"] = cont.Properties.LastModified // props["last_modified"] = cont.Properties.LastModified
props["lease_status"] = cont.Properties.LeaseStatus // props["lease_status"] = cont.Properties.LeaseStatus
props["lease_state"] = cont.Properties.LeaseState // props["lease_state"] = cont.Properties.LeaseState
props["lease_duration"] = cont.Properties.LeaseDuration // props["lease_duration"] = cont.Properties.LeaseDuration
//
d.Set("properties", props) // d.Set("properties", props)
} // }
} // }
//
if !found { // if !found {
log.Printf("[INFO] Storage container %q does not exist in account %q, removing from state...", name, storageAccountName) // log.Printf("[INFO] Storage container %q does not exist in account %q, removing from state...", name, storageAccountName)
d.SetId("") // d.SetId("")
} // }
//
return nil // return nil
} //}
//
func resourceArmStorageContainerExists(d *schema.ResourceData, meta interface{}) (bool, error) { //func resourceArmStorageContainerExists(d *schema.ResourceData, meta interface{}) (bool, error) {
armClient := meta.(*ArmClient) // armClient := meta.(*ArmClient)
//
resourceGroupName := d.Get("resource_group_name").(string) // resourceGroupName := d.Get("resource_group_name").(string)
storageAccountName := d.Get("storage_account_name").(string) // storageAccountName := d.Get("storage_account_name").(string)
//
blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) // blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName)
if err != nil { // if err != nil {
return false, err // return false, err
} // }
if !accountExists { // if !accountExists {
log.Printf("[DEBUG] Storage account %q not found, removing container %q from state", storageAccountName, d.Id()) // log.Printf("[DEBUG] Storage account %q not found, removing container %q from state", storageAccountName, d.Id())
d.SetId("") // d.SetId("")
return false, nil // return false, nil
} // }
//
name := d.Get("name").(string) // name := d.Get("name").(string)
//
log.Printf("[INFO] Checking existence of storage container %q in storage account %q", name, storageAccountName) // log.Printf("[INFO] Checking existence of storage container %q in storage account %q", name, storageAccountName)
exists, err := blobClient.ContainerExists(name) // exists, err := blobClient.ContainerExists(name)
if err != nil { // if err != nil {
return false, fmt.Errorf("Error querying existence of storage container %q in storage account %q: %s", name, storageAccountName, err) // return false, fmt.Errorf("Error querying existence of storage container %q in storage account %q: %s", name, storageAccountName, err)
} // }
//
if !exists { // if !exists {
log.Printf("[INFO] Storage container %q does not exist in account %q, removing from state...", name, storageAccountName) // log.Printf("[INFO] Storage container %q does not exist in account %q, removing from state...", name, storageAccountName)
d.SetId("") // d.SetId("")
} // }
//
return exists, nil // return exists, nil
} //}
//
// resourceAzureStorageContainerDelete does all the necessary API calls to //// resourceAzureStorageContainerDelete does all the necessary API calls to
// delete a storage container off Azure. //// delete a storage container off Azure.
func resourceArmStorageContainerDelete(d *schema.ResourceData, meta interface{}) error { //func resourceArmStorageContainerDelete(d *schema.ResourceData, meta interface{}) error {
armClient := meta.(*ArmClient) // armClient := meta.(*ArmClient)
//
resourceGroupName := d.Get("resource_group_name").(string) // resourceGroupName := d.Get("resource_group_name").(string)
storageAccountName := d.Get("storage_account_name").(string) // storageAccountName := d.Get("storage_account_name").(string)
//
blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) // blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName)
if err != nil { // if err != nil {
return err // return err
} // }
if !accountExists { // if !accountExists {
log.Printf("[INFO]Storage Account %q doesn't exist so the container won't exist", storageAccountName) // log.Printf("[INFO]Storage Account %q doesn't exist so the container won't exist", storageAccountName)
return nil // return nil
} // }
//
name := d.Get("name").(string) // name := d.Get("name").(string)
//
log.Printf("[INFO] Deleting storage container %q in account %q", name, storageAccountName) // log.Printf("[INFO] Deleting storage container %q in account %q", name, storageAccountName)
if _, err := blobClient.DeleteContainerIfExists(name); err != nil { // if _, err := blobClient.DeleteContainerIfExists(name); err != nil {
return fmt.Errorf("Error deleting storage container %q from storage account %q: %s", name, storageAccountName, err) // return fmt.Errorf("Error deleting storage container %q from storage account %q: %s", name, storageAccountName, err)
} // }
//
d.SetId("") // d.SetId("")
return nil // return nil
} //}

View File

@ -1,241 +1,241 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"log" // "log"
"strings" // "strings"
"testing" // "testing"
//
"github.com/Azure/azure-sdk-for-go/storage" // "github.com/Azure/azure-sdk-for-go/storage"
"github.com/hashicorp/terraform/helper/acctest" // "github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" // "github.com/hashicorp/terraform/terraform"
) //)
//
func TestAccAzureRMStorageContainer_basic(t *testing.T) { //func TestAccAzureRMStorageContainer_basic(t *testing.T) {
var c storage.Container // var c storage.Container
//
ri := acctest.RandInt() // ri := acctest.RandInt()
rs := strings.ToLower(acctest.RandString(11)) // rs := strings.ToLower(acctest.RandString(11))
config := fmt.Sprintf(testAccAzureRMStorageContainer_basic, ri, rs) // config := fmt.Sprintf(testAccAzureRMStorageContainer_basic, ri, rs)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMStorageContainerDestroy, // CheckDestroy: testCheckAzureRMStorageContainerDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: config, // Config: config,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMStorageContainerExists("azurerm_storage_container.test", &c), // testCheckAzureRMStorageContainerExists("azurerm_storage_container.test", &c),
), // ),
}, // },
}, // },
}) // })
} //}
//
func TestAccAzureRMStorageContainer_disappears(t *testing.T) { //func TestAccAzureRMStorageContainer_disappears(t *testing.T) {
var c storage.Container // var c storage.Container
//
ri := acctest.RandInt() // ri := acctest.RandInt()
rs := strings.ToLower(acctest.RandString(11)) // rs := strings.ToLower(acctest.RandString(11))
config := fmt.Sprintf(testAccAzureRMStorageContainer_basic, ri, rs) // config := fmt.Sprintf(testAccAzureRMStorageContainer_basic, ri, rs)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMStorageContainerDestroy, // CheckDestroy: testCheckAzureRMStorageContainerDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: config, // Config: config,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMStorageContainerExists("azurerm_storage_container.test", &c), // testCheckAzureRMStorageContainerExists("azurerm_storage_container.test", &c),
testAccARMStorageContainerDisappears("azurerm_storage_container.test", &c), // testAccARMStorageContainerDisappears("azurerm_storage_container.test", &c),
), // ),
ExpectNonEmptyPlan: true, // ExpectNonEmptyPlan: true,
}, // },
}, // },
}) // })
} //}
//
func testCheckAzureRMStorageContainerExists(name string, c *storage.Container) resource.TestCheckFunc { //func testCheckAzureRMStorageContainerExists(name string, c *storage.Container) resource.TestCheckFunc {
return func(s *terraform.State) error { // return func(s *terraform.State) error {
//
rs, ok := s.RootModule().Resources[name] // rs, ok := s.RootModule().Resources[name]
if !ok { // if !ok {
return fmt.Errorf("Not found: %s", name) // return fmt.Errorf("Not found: %s", name)
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
storageAccountName := rs.Primary.Attributes["storage_account_name"] // storageAccountName := rs.Primary.Attributes["storage_account_name"]
resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
if !hasResourceGroup { // if !hasResourceGroup {
return fmt.Errorf("Bad: no resource group found in state for storage container: %s", name) // return fmt.Errorf("Bad: no resource group found in state for storage container: %s", name)
} // }
//
armClient := testAccProvider.Meta().(*ArmClient) // armClient := testAccProvider.Meta().(*ArmClient)
blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName) // blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName)
if err != nil { // if err != nil {
return err // return err
} // }
if !accountExists { // if !accountExists {
return fmt.Errorf("Bad: Storage Account %q does not exist", storageAccountName) // return fmt.Errorf("Bad: Storage Account %q does not exist", storageAccountName)
} // }
//
containers, err := blobClient.ListContainers(storage.ListContainersParameters{ // containers, err := blobClient.ListContainers(storage.ListContainersParameters{
Prefix: name, // Prefix: name,
Timeout: 90, // Timeout: 90,
}) // })
//
if len(containers.Containers) == 0 { // if len(containers.Containers) == 0 {
return fmt.Errorf("Bad: Storage Container %q (storage account: %q) does not exist", name, storageAccountName) // return fmt.Errorf("Bad: Storage Container %q (storage account: %q) does not exist", name, storageAccountName)
} // }
//
var found bool // var found bool
for _, container := range containers.Containers { // for _, container := range containers.Containers {
if container.Name == name { // if container.Name == name {
found = true // found = true
*c = container // *c = container
} // }
} // }
//
if !found { // if !found {
return fmt.Errorf("Bad: Storage Container %q (storage account: %q) does not exist", name, storageAccountName) // return fmt.Errorf("Bad: Storage Container %q (storage account: %q) does not exist", name, storageAccountName)
} // }
//
return nil // return nil
} // }
} //}
//
func testAccARMStorageContainerDisappears(name string, c *storage.Container) resource.TestCheckFunc { //func testAccARMStorageContainerDisappears(name string, c *storage.Container) resource.TestCheckFunc {
return func(s *terraform.State) error { // return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[name] // rs, ok := s.RootModule().Resources[name]
if !ok { // if !ok {
return fmt.Errorf("Not found: %s", name) // return fmt.Errorf("Not found: %s", name)
} // }
//
armClient := testAccProvider.Meta().(*ArmClient) // armClient := testAccProvider.Meta().(*ArmClient)
//
storageAccountName := rs.Primary.Attributes["storage_account_name"] // storageAccountName := rs.Primary.Attributes["storage_account_name"]
resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
if !hasResourceGroup { // if !hasResourceGroup {
return fmt.Errorf("Bad: no resource group found in state for storage container: %s", c.Name) // return fmt.Errorf("Bad: no resource group found in state for storage container: %s", c.Name)
} // }
//
blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName) // blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName)
if err != nil { // if err != nil {
return err // return err
} // }
if !accountExists { // if !accountExists {
log.Printf("[INFO]Storage Account %q doesn't exist so the container won't exist", storageAccountName) // log.Printf("[INFO]Storage Account %q doesn't exist so the container won't exist", storageAccountName)
return nil // return nil
} // }
//
_, err = blobClient.DeleteContainerIfExists(c.Name) // _, err = blobClient.DeleteContainerIfExists(c.Name)
if err != nil { // if err != nil {
return err // return err
} // }
//
return nil // return nil
} // }
} //}
//
func testCheckAzureRMStorageContainerDestroy(s *terraform.State) error { //func testCheckAzureRMStorageContainerDestroy(s *terraform.State) error {
for _, rs := range s.RootModule().Resources { // for _, rs := range s.RootModule().Resources {
if rs.Type != "azurerm_storage_container" { // if rs.Type != "azurerm_storage_container" {
continue // continue
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
storageAccountName := rs.Primary.Attributes["storage_account_name"] // storageAccountName := rs.Primary.Attributes["storage_account_name"]
resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
if !hasResourceGroup { // if !hasResourceGroup {
return fmt.Errorf("Bad: no resource group found in state for storage container: %s", name) // return fmt.Errorf("Bad: no resource group found in state for storage container: %s", name)
} // }
//
armClient := testAccProvider.Meta().(*ArmClient) // armClient := testAccProvider.Meta().(*ArmClient)
blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName) // blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName)
if err != nil { // if err != nil {
//If we can't get keys then the blob can't exist // //If we can't get keys then the blob can't exist
return nil // return nil
} // }
if !accountExists { // if !accountExists {
return nil // return nil
} // }
//
containers, err := blobClient.ListContainers(storage.ListContainersParameters{ // containers, err := blobClient.ListContainers(storage.ListContainersParameters{
Prefix: name, // Prefix: name,
Timeout: 90, // Timeout: 90,
}) // })
//
if err != nil { // if err != nil {
return nil // return nil
} // }
//
var found bool // var found bool
for _, container := range containers.Containers { // for _, container := range containers.Containers {
if container.Name == name { // if container.Name == name {
found = true // found = true
} // }
} // }
//
if found { // if found {
return fmt.Errorf("Bad: Storage Container %q (storage account: %q) still exist", name, storageAccountName) // return fmt.Errorf("Bad: Storage Container %q (storage account: %q) still exist", name, storageAccountName)
} // }
} // }
//
return nil // return nil
} //}
//
func TestValidateArmStorageContainerName(t *testing.T) { //func TestValidateArmStorageContainerName(t *testing.T) {
validNames := []string{ // validNames := []string{
"valid-name", // "valid-name",
"valid02-name", // "valid02-name",
} // }
for _, v := range validNames { // for _, v := range validNames {
_, errors := validateArmStorageContainerName(v, "name") // _, errors := validateArmStorageContainerName(v, "name")
if len(errors) != 0 { // if len(errors) != 0 {
t.Fatalf("%q should be a valid Storage Container Name: %q", v, errors) // t.Fatalf("%q should be a valid Storage Container Name: %q", v, errors)
} // }
} // }
//
invalidNames := []string{ // invalidNames := []string{
"InvalidName1", // "InvalidName1",
"-invalidname1", // "-invalidname1",
"invalid_name", // "invalid_name",
"invalid!", // "invalid!",
"ww", // "ww",
strings.Repeat("w", 65), // strings.Repeat("w", 65),
} // }
for _, v := range invalidNames { // for _, v := range invalidNames {
_, errors := validateArmStorageContainerName(v, "name") // _, errors := validateArmStorageContainerName(v, "name")
if len(errors) == 0 { // if len(errors) == 0 {
t.Fatalf("%q should be an invalid Storage Container Name", v) // t.Fatalf("%q should be an invalid Storage Container Name", v)
} // }
} // }
} //}
//
var testAccAzureRMStorageContainer_basic = ` //var testAccAzureRMStorageContainer_basic = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "westus" // location = "westus"
} //}
//
resource "azurerm_storage_account" "test" { //resource "azurerm_storage_account" "test" {
name = "acctestacc%s" // name = "acctestacc%s"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
location = "westus" // location = "westus"
account_type = "Standard_LRS" // account_type = "Standard_LRS"
//
tags { // tags {
environment = "staging" // environment = "staging"
} // }
} //}
//
resource "azurerm_storage_container" "test" { //resource "azurerm_storage_container" "test" {
name = "vhds" // name = "vhds"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
storage_account_name = "${azurerm_storage_account.test.name}" // storage_account_name = "${azurerm_storage_account.test.name}"
container_access_type = "private" // container_access_type = "private"
} //}
` //`

View File

@ -16,13 +16,13 @@ func resourceArmStorageQueue() *schema.Resource {
Delete: resourceArmStorageQueueDelete, Delete: resourceArmStorageQueueDelete,
Schema: map[string]*schema.Schema{ Schema: map[string]*schema.Schema{
"name": &schema.Schema{ "name": {
Type: schema.TypeString, Type: schema.TypeString,
Required: true, Required: true,
ForceNew: true, ForceNew: true,
ValidateFunc: validateArmStorageQueueName, ValidateFunc: validateArmStorageQueueName,
}, },
"resource_group_name": &schema.Schema{ "resource_group_name": {
Type: schema.TypeString, Type: schema.TypeString,
Required: true, Required: true,
ForceNew: true, ForceNew: true,

View File

@ -1,188 +1,188 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"log" // "log"
"net/http" // "net/http"
"time" // "time"
//
"github.com/Azure/azure-sdk-for-go/arm/network" // "github.com/Azure/azure-sdk-for-go/arm/network"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema" // "github.com/hashicorp/terraform/helper/schema"
) //)
//
func resourceArmSubnet() *schema.Resource { //func resourceArmSubnet() *schema.Resource {
return &schema.Resource{ // return &schema.Resource{
Create: resourceArmSubnetCreate, // Create: resourceArmSubnetCreate,
Read: resourceArmSubnetRead, // Read: resourceArmSubnetRead,
Update: resourceArmSubnetCreate, // Update: resourceArmSubnetCreate,
Delete: resourceArmSubnetDelete, // Delete: resourceArmSubnetDelete,
//
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"resource_group_name": &schema.Schema{ // "resource_group_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"virtual_network_name": &schema.Schema{ // "virtual_network_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"address_prefix": &schema.Schema{ // "address_prefix": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
//
"network_security_group_id": &schema.Schema{ // "network_security_group_id": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
}, // },
//
"route_table_id": &schema.Schema{ // "route_table_id": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
}, // },
//
"ip_configurations": &schema.Schema{ // "ip_configurations": &schema.Schema{
Type: schema.TypeSet, // Type: schema.TypeSet,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
Elem: &schema.Schema{Type: schema.TypeString}, // Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString, // Set: schema.HashString,
}, // },
}, // },
} // }
} //}
//
func resourceArmSubnetCreate(d *schema.ResourceData, meta interface{}) error { //func resourceArmSubnetCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient) // client := meta.(*ArmClient)
subnetClient := client.subnetClient // subnetClient := client.subnetClient
//
log.Printf("[INFO] preparing arguments for Azure ARM Subnet creation.") // log.Printf("[INFO] preparing arguments for Azure ARM Subnet creation.")
//
name := d.Get("name").(string) // name := d.Get("name").(string)
vnetName := d.Get("virtual_network_name").(string) // vnetName := d.Get("virtual_network_name").(string)
resGroup := d.Get("resource_group_name").(string) // resGroup := d.Get("resource_group_name").(string)
addressPrefix := d.Get("address_prefix").(string) // addressPrefix := d.Get("address_prefix").(string)
//
armMutexKV.Lock(vnetName) // armMutexKV.Lock(vnetName)
defer armMutexKV.Unlock(vnetName) // defer armMutexKV.Unlock(vnetName)
//
properties := network.SubnetPropertiesFormat{ // properties := network.SubnetPropertiesFormat{
AddressPrefix: &addressPrefix, // AddressPrefix: &addressPrefix,
} // }
//
if v, ok := d.GetOk("network_security_group_id"); ok { // if v, ok := d.GetOk("network_security_group_id"); ok {
nsgId := v.(string) // nsgId := v.(string)
properties.NetworkSecurityGroup = &network.SecurityGroup{ // properties.NetworkSecurityGroup = &network.SecurityGroup{
ID: &nsgId, // ID: &nsgId,
} // }
} // }
//
if v, ok := d.GetOk("route_table_id"); ok { // if v, ok := d.GetOk("route_table_id"); ok {
rtId := v.(string) // rtId := v.(string)
properties.RouteTable = &network.RouteTable{ // properties.RouteTable = &network.RouteTable{
ID: &rtId, // ID: &rtId,
} // }
} // }
//
subnet := network.Subnet{ // subnet := network.Subnet{
Name: &name, // Name: &name,
Properties: &properties, // Properties: &properties,
} // }
//
resp, err := subnetClient.CreateOrUpdate(resGroup, vnetName, name, subnet) // resp, err := subnetClient.CreateOrUpdate(resGroup, vnetName, name, subnet)
if err != nil { // if err != nil {
return err // return err
} // }
//
d.SetId(*resp.ID) // d.SetId(*resp.ID)
//
log.Printf("[DEBUG] Waiting for Subnet (%s) to become available", name) // log.Printf("[DEBUG] Waiting for Subnet (%s) to become available", name)
stateConf := &resource.StateChangeConf{ // stateConf := &resource.StateChangeConf{
Pending: []string{"Accepted", "Updating"}, // Pending: []string{"Accepted", "Updating"},
Target: []string{"Succeeded"}, // Target: []string{"Succeeded"},
Refresh: subnetRuleStateRefreshFunc(client, resGroup, vnetName, name), // Refresh: subnetRuleStateRefreshFunc(client, resGroup, vnetName, name),
Timeout: 10 * time.Minute, // Timeout: 10 * time.Minute,
} // }
if _, err := stateConf.WaitForState(); err != nil { // if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Subnet (%s) to become available: %s", name, err) // return fmt.Errorf("Error waiting for Subnet (%s) to become available: %s", name, err)
} // }
//
return resourceArmSubnetRead(d, meta) // return resourceArmSubnetRead(d, meta)
} //}
//
func resourceArmSubnetRead(d *schema.ResourceData, meta interface{}) error { //func resourceArmSubnetRead(d *schema.ResourceData, meta interface{}) error {
subnetClient := meta.(*ArmClient).subnetClient // subnetClient := meta.(*ArmClient).subnetClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
vnetName := id.Path["virtualNetworks"] // vnetName := id.Path["virtualNetworks"]
name := id.Path["subnets"] // name := id.Path["subnets"]
//
resp, err := subnetClient.Get(resGroup, vnetName, name, "") // resp, err := subnetClient.Get(resGroup, vnetName, name, "")
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
d.SetId("") // d.SetId("")
return nil // return nil
} // }
if err != nil { // if err != nil {
return fmt.Errorf("Error making Read request on Azure Subnet %s: %s", name, err) // return fmt.Errorf("Error making Read request on Azure Subnet %s: %s", name, err)
} // }
//
if resp.Properties.IPConfigurations != nil && len(*resp.Properties.IPConfigurations) > 0 { // if resp.Properties.IPConfigurations != nil && len(*resp.Properties.IPConfigurations) > 0 {
ips := make([]string, 0, len(*resp.Properties.IPConfigurations)) // ips := make([]string, 0, len(*resp.Properties.IPConfigurations))
for _, ip := range *resp.Properties.IPConfigurations { // for _, ip := range *resp.Properties.IPConfigurations {
ips = append(ips, *ip.ID) // ips = append(ips, *ip.ID)
} // }
//
if err := d.Set("ip_configurations", ips); err != nil { // if err := d.Set("ip_configurations", ips); err != nil {
return err // return err
} // }
} // }
//
return nil // return nil
} //}
//
func resourceArmSubnetDelete(d *schema.ResourceData, meta interface{}) error { //func resourceArmSubnetDelete(d *schema.ResourceData, meta interface{}) error {
subnetClient := meta.(*ArmClient).subnetClient // subnetClient := meta.(*ArmClient).subnetClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["subnets"] // name := id.Path["subnets"]
vnetName := id.Path["virtualNetworks"] // vnetName := id.Path["virtualNetworks"]
//
armMutexKV.Lock(vnetName) // armMutexKV.Lock(vnetName)
defer armMutexKV.Unlock(vnetName) // defer armMutexKV.Unlock(vnetName)
//
_, err = subnetClient.Delete(resGroup, vnetName, name) // _, err = subnetClient.Delete(resGroup, vnetName, name)
//
return err // return err
} //}
//
func subnetRuleStateRefreshFunc(client *ArmClient, resourceGroupName string, virtualNetworkName string, subnetName string) resource.StateRefreshFunc { //func subnetRuleStateRefreshFunc(client *ArmClient, resourceGroupName string, virtualNetworkName string, subnetName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) { // return func() (interface{}, string, error) {
res, err := client.subnetClient.Get(resourceGroupName, virtualNetworkName, subnetName, "") // res, err := client.subnetClient.Get(resourceGroupName, virtualNetworkName, subnetName, "")
if err != nil { // if err != nil {
return nil, "", fmt.Errorf("Error issuing read request in subnetRuleStateRefreshFunc to Azure ARM for subnet '%s' (RG: '%s') (VNN: '%s'): %s", subnetName, resourceGroupName, virtualNetworkName, err) // return nil, "", fmt.Errorf("Error issuing read request in subnetRuleStateRefreshFunc to Azure ARM for subnet '%s' (RG: '%s') (VNN: '%s'): %s", subnetName, resourceGroupName, virtualNetworkName, err)
} // }
//
return res, *res.Properties.ProvisioningState, nil // return res, *res.Properties.ProvisioningState, nil
} // }
} //}

View File

@ -1,108 +1,108 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"net/http" // "net/http"
"testing" // "testing"
//
"github.com/hashicorp/terraform/helper/acctest" // "github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" // "github.com/hashicorp/terraform/terraform"
) //)
//
func TestAccAzureRMSubnet_basic(t *testing.T) { //func TestAccAzureRMSubnet_basic(t *testing.T) {
//
ri := acctest.RandInt() // ri := acctest.RandInt()
config := fmt.Sprintf(testAccAzureRMSubnet_basic, ri, ri, ri) // config := fmt.Sprintf(testAccAzureRMSubnet_basic, ri, ri, ri)
//
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMSubnetDestroy, // CheckDestroy: testCheckAzureRMSubnetDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: config, // Config: config,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMSubnetExists("azurerm_subnet.test"), // testCheckAzureRMSubnetExists("azurerm_subnet.test"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func testCheckAzureRMSubnetExists(name string) resource.TestCheckFunc { //func testCheckAzureRMSubnetExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error { // return func(s *terraform.State) error {
// Ensure we have enough information in state to look up in API // // Ensure we have enough information in state to look up in API
rs, ok := s.RootModule().Resources[name] // rs, ok := s.RootModule().Resources[name]
if !ok { // if !ok {
return fmt.Errorf("Not found: %s", name) // return fmt.Errorf("Not found: %s", name)
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
vnetName := rs.Primary.Attributes["virtual_network_name"] // vnetName := rs.Primary.Attributes["virtual_network_name"]
resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
if !hasResourceGroup { // if !hasResourceGroup {
return fmt.Errorf("Bad: no resource group found in state for subnet: %s", name) // return fmt.Errorf("Bad: no resource group found in state for subnet: %s", name)
} // }
//
conn := testAccProvider.Meta().(*ArmClient).subnetClient // conn := testAccProvider.Meta().(*ArmClient).subnetClient
//
resp, err := conn.Get(resourceGroup, vnetName, name, "") // resp, err := conn.Get(resourceGroup, vnetName, name, "")
if err != nil { // if err != nil {
return fmt.Errorf("Bad: Get on subnetClient: %s", err) // return fmt.Errorf("Bad: Get on subnetClient: %s", err)
} // }
//
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("Bad: Subnet %q (resource group: %q) does not exist", name, resourceGroup) // return fmt.Errorf("Bad: Subnet %q (resource group: %q) does not exist", name, resourceGroup)
} // }
//
return nil // return nil
} // }
} //}
//
func testCheckAzureRMSubnetDestroy(s *terraform.State) error { //func testCheckAzureRMSubnetDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*ArmClient).subnetClient // conn := testAccProvider.Meta().(*ArmClient).subnetClient
//
for _, rs := range s.RootModule().Resources { // for _, rs := range s.RootModule().Resources {
if rs.Type != "azurerm_subnet" { // if rs.Type != "azurerm_subnet" {
continue // continue
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
vnetName := rs.Primary.Attributes["virtual_network_name"] // vnetName := rs.Primary.Attributes["virtual_network_name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup := rs.Primary.Attributes["resource_group_name"]
//
resp, err := conn.Get(resourceGroup, vnetName, name, "") // resp, err := conn.Get(resourceGroup, vnetName, name, "")
//
if err != nil { // if err != nil {
return nil // return nil
} // }
//
if resp.StatusCode != http.StatusNotFound { // if resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("Subnet still exists:\n%#v", resp.Properties) // return fmt.Errorf("Subnet still exists:\n%#v", resp.Properties)
} // }
} // }
//
return nil // return nil
} //}
//
var testAccAzureRMSubnet_basic = ` //var testAccAzureRMSubnet_basic = `
resource "azurerm_resource_group" "test" { //resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} //}
//
resource "azurerm_virtual_network" "test" { //resource "azurerm_virtual_network" "test" {
name = "acctestvirtnet%d" // name = "acctestvirtnet%d"
address_space = ["10.0.0.0/16"] // address_space = ["10.0.0.0/16"]
location = "West US" // location = "West US"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
} //}
//
resource "azurerm_subnet" "test" { //resource "azurerm_subnet" "test" {
name = "acctestsubnet%d" // name = "acctestsubnet%d"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
virtual_network_name = "${azurerm_virtual_network.test.name}" // virtual_network_name = "${azurerm_virtual_network.test.name}"
address_prefix = "10.0.2.0/24" // address_prefix = "10.0.2.0/24"
} //}
` //`

View File

@ -1,213 +1,213 @@
package azurerm package azurerm
import ( //import (
"encoding/json" // "encoding/json"
"fmt" // "fmt"
"log" // "log"
"net/http" // "net/http"
"strings" // "strings"
"time" // "time"
//
"github.com/Azure/azure-sdk-for-go/arm/resources/resources" // "github.com/Azure/azure-sdk-for-go/arm/resources/resources"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema" // "github.com/hashicorp/terraform/helper/schema"
) //)
//
func resourceArmTemplateDeployment() *schema.Resource { //func resourceArmTemplateDeployment() *schema.Resource {
return &schema.Resource{ // return &schema.Resource{
Create: resourceArmTemplateDeploymentCreate, // Create: resourceArmTemplateDeploymentCreate,
Read: resourceArmTemplateDeploymentRead, // Read: resourceArmTemplateDeploymentRead,
Update: resourceArmTemplateDeploymentCreate, // Update: resourceArmTemplateDeploymentCreate,
Delete: resourceArmTemplateDeploymentDelete, // Delete: resourceArmTemplateDeploymentDelete,
//
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"resource_group_name": &schema.Schema{ // "resource_group_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"template_body": &schema.Schema{ // "template_body": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
StateFunc: normalizeJson, // StateFunc: normalizeJson,
}, // },
//
"parameters": &schema.Schema{ // "parameters": &schema.Schema{
Type: schema.TypeMap, // Type: schema.TypeMap,
Optional: true, // Optional: true,
}, // },
//
"outputs": &schema.Schema{ // "outputs": &schema.Schema{
Type: schema.TypeMap, // Type: schema.TypeMap,
Computed: true, // Computed: true,
}, // },
//
"deployment_mode": &schema.Schema{ // "deployment_mode": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
}, // },
} // }
} //}
//
func resourceArmTemplateDeploymentCreate(d *schema.ResourceData, meta interface{}) error { //func resourceArmTemplateDeploymentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient) // client := meta.(*ArmClient)
deployClient := client.deploymentsClient // deployClient := client.deploymentsClient
//
name := d.Get("name").(string) // name := d.Get("name").(string)
resGroup := d.Get("resource_group_name").(string) // resGroup := d.Get("resource_group_name").(string)
deploymentMode := d.Get("deployment_mode").(string) // deploymentMode := d.Get("deployment_mode").(string)
//
log.Printf("[INFO] preparing arguments for Azure ARM Template Deployment creation.") // log.Printf("[INFO] preparing arguments for Azure ARM Template Deployment creation.")
properties := resources.DeploymentProperties{ // properties := resources.DeploymentProperties{
Mode: resources.DeploymentMode(deploymentMode), // Mode: resources.DeploymentMode(deploymentMode),
} // }
//
if v, ok := d.GetOk("parameters"); ok { // if v, ok := d.GetOk("parameters"); ok {
params := v.(map[string]interface{}) // params := v.(map[string]interface{})
//
newParams := make(map[string]interface{}, len(params)) // newParams := make(map[string]interface{}, len(params))
for key, val := range params { // for key, val := range params {
newParams[key] = struct { // newParams[key] = struct {
Value interface{} // Value interface{}
}{ // }{
Value: val, // Value: val,
} // }
} // }
//
properties.Parameters = &newParams // properties.Parameters = &newParams
} // }
//
if v, ok := d.GetOk("template_body"); ok { // if v, ok := d.GetOk("template_body"); ok {
template, err := expandTemplateBody(v.(string)) // template, err := expandTemplateBody(v.(string))
if err != nil { // if err != nil {
return err // return err
} // }
//
properties.Template = &template // properties.Template = &template
} // }
//
deployment := resources.Deployment{ // deployment := resources.Deployment{
Properties: &properties, // Properties: &properties,
} // }
resp, err := deployClient.CreateOrUpdate(resGroup, name, deployment) // resp, err := deployClient.CreateOrUpdate(resGroup, name, deployment)
if err != nil { // if err != nil {
return nil // return nil
} // }
//
d.SetId(*resp.ID) // d.SetId(*resp.ID)
//
log.Printf("[DEBUG] Waiting for Template Deployment (%s) to become available", name) // log.Printf("[DEBUG] Waiting for Template Deployment (%s) to become available", name)
stateConf := &resource.StateChangeConf{ // stateConf := &resource.StateChangeConf{
Pending: []string{"creating", "updating", "accepted", "running"}, // Pending: []string{"creating", "updating", "accepted", "running"},
Target: []string{"succeeded"}, // Target: []string{"succeeded"},
Refresh: templateDeploymentStateRefreshFunc(client, resGroup, name), // Refresh: templateDeploymentStateRefreshFunc(client, resGroup, name),
Timeout: 40 * time.Minute, // Timeout: 40 * time.Minute,
} // }
if _, err := stateConf.WaitForState(); err != nil { // if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Template Deployment (%s) to become available: %s", name, err) // return fmt.Errorf("Error waiting for Template Deployment (%s) to become available: %s", name, err)
} // }
//
return resourceArmTemplateDeploymentRead(d, meta) // return resourceArmTemplateDeploymentRead(d, meta)
} //}
//
func resourceArmTemplateDeploymentRead(d *schema.ResourceData, meta interface{}) error { //func resourceArmTemplateDeploymentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient) // client := meta.(*ArmClient)
deployClient := client.deploymentsClient // deployClient := client.deploymentsClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["deployments"] // name := id.Path["deployments"]
if name == "" { // if name == "" {
name = id.Path["Deployments"] // name = id.Path["Deployments"]
} // }
//
resp, err := deployClient.Get(resGroup, name) // resp, err := deployClient.Get(resGroup, name)
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
d.SetId("") // d.SetId("")
return nil // return nil
} // }
if err != nil { // if err != nil {
return fmt.Errorf("Error making Read request on Azure RM Template Deployment %s: %s", name, err) // return fmt.Errorf("Error making Read request on Azure RM Template Deployment %s: %s", name, err)
} // }
var outputs map[string]string // var outputs map[string]string
if resp.Properties.Outputs != nil && len(*resp.Properties.Outputs) > 0 { // if resp.Properties.Outputs != nil && len(*resp.Properties.Outputs) > 0 {
outputs = make(map[string]string) // outputs = make(map[string]string)
for key, output := range *resp.Properties.Outputs { // for key, output := range *resp.Properties.Outputs {
outputMap := output.(map[string]interface{}) // outputMap := output.(map[string]interface{})
outputValue, ok := outputMap["value"] // outputValue, ok := outputMap["value"]
if !ok { // if !ok {
// No value // // No value
continue // continue
} // }
//
outputs[key] = outputValue.(string) // outputs[key] = outputValue.(string)
} // }
} // }
//
d.Set("outputs", outputs) // d.Set("outputs", outputs)
//
return nil // return nil
} //}
//
func resourceArmTemplateDeploymentDelete(d *schema.ResourceData, meta interface{}) error { //func resourceArmTemplateDeploymentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient) // client := meta.(*ArmClient)
deployClient := client.deploymentsClient // deployClient := client.deploymentsClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["deployments"] // name := id.Path["deployments"]
if name == "" { // if name == "" {
name = id.Path["Deployments"] // name = id.Path["Deployments"]
} // }
//
_, err = deployClient.Delete(resGroup, name) // _, err = deployClient.Delete(resGroup, name)
return nil // return nil
} //}
//
func expandTemplateBody(template string) (map[string]interface{}, error) { //func expandTemplateBody(template string) (map[string]interface{}, error) {
var templateBody map[string]interface{} // var templateBody map[string]interface{}
err := json.Unmarshal([]byte(template), &templateBody) // err := json.Unmarshal([]byte(template), &templateBody)
if err != nil { // if err != nil {
return nil, fmt.Errorf("Error Expanding the template_body for Azure RM Template Deployment") // return nil, fmt.Errorf("Error Expanding the template_body for Azure RM Template Deployment")
} // }
return templateBody, nil // return templateBody, nil
} //}
//
func normalizeJson(jsonString interface{}) string { //func normalizeJson(jsonString interface{}) string {
if jsonString == nil || jsonString == "" { // if jsonString == nil || jsonString == "" {
return "" // return ""
} // }
var j interface{} // var j interface{}
err := json.Unmarshal([]byte(jsonString.(string)), &j) // err := json.Unmarshal([]byte(jsonString.(string)), &j)
if err != nil { // if err != nil {
return fmt.Sprintf("Error parsing JSON: %s", err) // return fmt.Sprintf("Error parsing JSON: %s", err)
} // }
b, _ := json.Marshal(j) // b, _ := json.Marshal(j)
return string(b[:]) // return string(b[:])
} //}
//
func templateDeploymentStateRefreshFunc(client *ArmClient, resourceGroupName string, name string) resource.StateRefreshFunc { //func templateDeploymentStateRefreshFunc(client *ArmClient, resourceGroupName string, name string) resource.StateRefreshFunc {
return func() (interface{}, string, error) { // return func() (interface{}, string, error) {
res, err := client.deploymentsClient.Get(resourceGroupName, name) // res, err := client.deploymentsClient.Get(resourceGroupName, name)
if err != nil { // if err != nil {
return nil, "", fmt.Errorf("Error issuing read request in templateDeploymentStateRefreshFunc to Azure ARM for Template Deployment '%s' (RG: '%s'): %s", name, resourceGroupName, err) // return nil, "", fmt.Errorf("Error issuing read request in templateDeploymentStateRefreshFunc to Azure ARM for Template Deployment '%s' (RG: '%s'): %s", name, resourceGroupName, err)
} // }
//
return res, strings.ToLower(*res.Properties.ProvisioningState), nil // return res, strings.ToLower(*res.Properties.ProvisioningState), nil
} // }
} //}

View File

@ -1,251 +1,251 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"net/http" // "net/http"
"testing" // "testing"
//
"github.com/hashicorp/terraform/helper/acctest" // "github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform" // "github.com/hashicorp/terraform/terraform"
) //)
//
func TestAccAzureRMTemplateDeployment_basic(t *testing.T) { //func TestAccAzureRMTemplateDeployment_basic(t *testing.T) {
ri := acctest.RandInt() // ri := acctest.RandInt()
config := fmt.Sprintf(testAccAzureRMTemplateDeployment_basicExample, ri, ri) // config := fmt.Sprintf(testAccAzureRMTemplateDeployment_basicExample, ri, ri)
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMTemplateDeploymentDestroy, // CheckDestroy: testCheckAzureRMTemplateDeploymentDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: config, // Config: config,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMTemplateDeploymentExists("azurerm_template_deployment.test"), // testCheckAzureRMTemplateDeploymentExists("azurerm_template_deployment.test"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func TestAccAzureRMTemplateDeployment_withParams(t *testing.T) { //func TestAccAzureRMTemplateDeployment_withParams(t *testing.T) {
ri := acctest.RandInt() // ri := acctest.RandInt()
config := fmt.Sprintf(testAccAzureRMTemplateDeployment_withParams, ri, ri, ri) // config := fmt.Sprintf(testAccAzureRMTemplateDeployment_withParams, ri, ri, ri)
resource.Test(t, resource.TestCase{ // resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) }, // PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders, // Providers: testAccProviders,
CheckDestroy: testCheckAzureRMTemplateDeploymentDestroy, // CheckDestroy: testCheckAzureRMTemplateDeploymentDestroy,
Steps: []resource.TestStep{ // Steps: []resource.TestStep{
resource.TestStep{ // resource.TestStep{
Config: config, // Config: config,
Check: resource.ComposeTestCheckFunc( // Check: resource.ComposeTestCheckFunc(
testCheckAzureRMTemplateDeploymentExists("azurerm_template_deployment.test"), // testCheckAzureRMTemplateDeploymentExists("azurerm_template_deployment.test"),
resource.TestCheckResourceAttr("azurerm_template_deployment.test", "outputs.testOutput", "Output Value"), // resource.TestCheckResourceAttr("azurerm_template_deployment.test", "outputs.testOutput", "Output Value"),
), // ),
}, // },
}, // },
}) // })
} //}
//
func testCheckAzureRMTemplateDeploymentExists(name string) resource.TestCheckFunc { //func testCheckAzureRMTemplateDeploymentExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error { // return func(s *terraform.State) error {
// Ensure we have enough information in state to look up in API // // Ensure we have enough information in state to look up in API
rs, ok := s.RootModule().Resources[name] // rs, ok := s.RootModule().Resources[name]
if !ok { // if !ok {
return fmt.Errorf("Not found: %s", name) // return fmt.Errorf("Not found: %s", name)
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
if !hasResourceGroup { // if !hasResourceGroup {
return fmt.Errorf("Bad: no resource group found in state for template deployment: %s", name) // return fmt.Errorf("Bad: no resource group found in state for template deployment: %s", name)
} // }
//
conn := testAccProvider.Meta().(*ArmClient).deploymentsClient // conn := testAccProvider.Meta().(*ArmClient).deploymentsClient
//
resp, err := conn.Get(resourceGroup, name) // resp, err := conn.Get(resourceGroup, name)
if err != nil { // if err != nil {
return fmt.Errorf("Bad: Get on deploymentsClient: %s", err) // return fmt.Errorf("Bad: Get on deploymentsClient: %s", err)
} // }
//
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("Bad: TemplateDeployment %q (resource group: %q) does not exist", name, resourceGroup) // return fmt.Errorf("Bad: TemplateDeployment %q (resource group: %q) does not exist", name, resourceGroup)
} // }
//
return nil // return nil
} // }
} //}
//
func testCheckAzureRMTemplateDeploymentDestroy(s *terraform.State) error { //func testCheckAzureRMTemplateDeploymentDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*ArmClient).vmClient // conn := testAccProvider.Meta().(*ArmClient).vmClient
//
for _, rs := range s.RootModule().Resources { // for _, rs := range s.RootModule().Resources {
if rs.Type != "azurerm_template_deployment" { // if rs.Type != "azurerm_template_deployment" {
continue // continue
} // }
//
name := rs.Primary.Attributes["name"] // name := rs.Primary.Attributes["name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"] // resourceGroup := rs.Primary.Attributes["resource_group_name"]
//
resp, err := conn.Get(resourceGroup, name, "") // resp, err := conn.Get(resourceGroup, name, "")
//
if err != nil { // if err != nil {
return nil // return nil
} // }
//
if resp.StatusCode != http.StatusNotFound { // if resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("Template Deployment still exists:\n%#v", resp.Properties) // return fmt.Errorf("Template Deployment still exists:\n%#v", resp.Properties)
} // }
} // }
//
return nil // return nil
} //}
//
var testAccAzureRMTemplateDeployment_basicExample = ` //var testAccAzureRMTemplateDeployment_basicExample = `
resource "azurerm_resource_group" "test" { // resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} // }
//
resource "azurerm_template_deployment" "test" { // resource "azurerm_template_deployment" "test" {
name = "acctesttemplate-%d" // name = "acctesttemplate-%d"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
template_body = <<DEPLOY // template_body = <<DEPLOY
{ //{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", // "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0", // "contentVersion": "1.0.0.0",
"parameters": { // "parameters": {
"storageAccountType": { // "storageAccountType": {
"type": "string", // "type": "string",
"defaultValue": "Standard_LRS", // "defaultValue": "Standard_LRS",
"allowedValues": [ // "allowedValues": [
"Standard_LRS", // "Standard_LRS",
"Standard_GRS", // "Standard_GRS",
"Standard_ZRS" // "Standard_ZRS"
], // ],
"metadata": { // "metadata": {
"description": "Storage Account type" // "description": "Storage Account type"
} // }
} // }
}, // },
"variables": { // "variables": {
"location": "[resourceGroup().location]", // "location": "[resourceGroup().location]",
"storageAccountName": "[concat(uniquestring(resourceGroup().id), 'storage')]", // "storageAccountName": "[concat(uniquestring(resourceGroup().id), 'storage')]",
"publicIPAddressName": "[concat('myPublicIp', uniquestring(resourceGroup().id))]", // "publicIPAddressName": "[concat('myPublicIp', uniquestring(resourceGroup().id))]",
"publicIPAddressType": "Dynamic", // "publicIPAddressType": "Dynamic",
"apiVersion": "2015-06-15", // "apiVersion": "2015-06-15",
"dnsLabelPrefix": "terraform-acctest" // "dnsLabelPrefix": "terraform-acctest"
}, // },
"resources": [ // "resources": [
{ // {
"type": "Microsoft.Storage/storageAccounts", // "type": "Microsoft.Storage/storageAccounts",
"name": "[variables('storageAccountName')]", // "name": "[variables('storageAccountName')]",
"apiVersion": "[variables('apiVersion')]", // "apiVersion": "[variables('apiVersion')]",
"location": "[variables('location')]", // "location": "[variables('location')]",
"properties": { // "properties": {
"accountType": "[parameters('storageAccountType')]" // "accountType": "[parameters('storageAccountType')]"
} // }
}, // },
{ // {
"type": "Microsoft.Network/publicIPAddresses", // "type": "Microsoft.Network/publicIPAddresses",
"apiVersion": "[variables('apiVersion')]", // "apiVersion": "[variables('apiVersion')]",
"name": "[variables('publicIPAddressName')]", // "name": "[variables('publicIPAddressName')]",
"location": "[variables('location')]", // "location": "[variables('location')]",
"properties": { // "properties": {
"publicIPAllocationMethod": "[variables('publicIPAddressType')]", // "publicIPAllocationMethod": "[variables('publicIPAddressType')]",
"dnsSettings": { // "dnsSettings": {
"domainNameLabel": "[variables('dnsLabelPrefix')]" // "domainNameLabel": "[variables('dnsLabelPrefix')]"
} // }
} // }
} // }
] // ]
} //}
DEPLOY //DEPLOY
deployment_mode = "Complete" // deployment_mode = "Complete"
} // }
//
` //`
//
var testAccAzureRMTemplateDeployment_withParams = ` //var testAccAzureRMTemplateDeployment_withParams = `
resource "azurerm_resource_group" "test" { // resource "azurerm_resource_group" "test" {
name = "acctestrg-%d" // name = "acctestrg-%d"
location = "West US" // location = "West US"
} // }
//
output "test" { // output "test" {
value = "${azurerm_template_deployment.test.outputs.testOutput}" // value = "${azurerm_template_deployment.test.outputs.testOutput}"
} // }
//
resource "azurerm_template_deployment" "test" { // resource "azurerm_template_deployment" "test" {
name = "acctesttemplate-%d" // name = "acctesttemplate-%d"
resource_group_name = "${azurerm_resource_group.test.name}" // resource_group_name = "${azurerm_resource_group.test.name}"
template_body = <<DEPLOY // template_body = <<DEPLOY
{ //{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", // "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0", // "contentVersion": "1.0.0.0",
"parameters": { // "parameters": {
"storageAccountType": { // "storageAccountType": {
"type": "string", // "type": "string",
"defaultValue": "Standard_LRS", // "defaultValue": "Standard_LRS",
"allowedValues": [ // "allowedValues": [
"Standard_LRS", // "Standard_LRS",
"Standard_GRS", // "Standard_GRS",
"Standard_ZRS" // "Standard_ZRS"
], // ],
"metadata": { // "metadata": {
"description": "Storage Account type" // "description": "Storage Account type"
} // }
}, // },
"dnsLabelPrefix": { // "dnsLabelPrefix": {
"type": "string", // "type": "string",
"metadata": { // "metadata": {
"description": "DNS Label for the Public IP. Must be lowercase. It should match with the following regular expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$ or it will raise an error." // "description": "DNS Label for the Public IP. Must be lowercase. It should match with the following regular expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$ or it will raise an error."
} // }
} // }
}, // },
"variables": { // "variables": {
"location": "[resourceGroup().location]", // "location": "[resourceGroup().location]",
"storageAccountName": "[concat(uniquestring(resourceGroup().id), 'storage')]", // "storageAccountName": "[concat(uniquestring(resourceGroup().id), 'storage')]",
"publicIPAddressName": "[concat('myPublicIp', uniquestring(resourceGroup().id))]", // "publicIPAddressName": "[concat('myPublicIp', uniquestring(resourceGroup().id))]",
"publicIPAddressType": "Dynamic", // "publicIPAddressType": "Dynamic",
"apiVersion": "2015-06-15" // "apiVersion": "2015-06-15"
}, // },
"resources": [ // "resources": [
{ // {
"type": "Microsoft.Storage/storageAccounts", // "type": "Microsoft.Storage/storageAccounts",
"name": "[variables('storageAccountName')]", // "name": "[variables('storageAccountName')]",
"apiVersion": "[variables('apiVersion')]", // "apiVersion": "[variables('apiVersion')]",
"location": "[variables('location')]", // "location": "[variables('location')]",
"properties": { // "properties": {
"accountType": "[parameters('storageAccountType')]" // "accountType": "[parameters('storageAccountType')]"
} // }
}, // },
{ // {
"type": "Microsoft.Network/publicIPAddresses", // "type": "Microsoft.Network/publicIPAddresses",
"apiVersion": "[variables('apiVersion')]", // "apiVersion": "[variables('apiVersion')]",
"name": "[variables('publicIPAddressName')]", // "name": "[variables('publicIPAddressName')]",
"location": "[variables('location')]", // "location": "[variables('location')]",
"properties": { // "properties": {
"publicIPAllocationMethod": "[variables('publicIPAddressType')]", // "publicIPAllocationMethod": "[variables('publicIPAddressType')]",
"dnsSettings": { // "dnsSettings": {
"domainNameLabel": "[parameters('dnsLabelPrefix')]" // "domainNameLabel": "[parameters('dnsLabelPrefix')]"
} // }
} // }
} // }
], // ],
"outputs": { // "outputs": {
"testOutput": { // "testOutput": {
"type": "string", // "type": "string",
"value": "Output Value" // "value": "Output Value"
} // }
} // }
} //}
DEPLOY //DEPLOY
parameters { // parameters {
dnsLabelPrefix = "terraform-test-%d" // dnsLabelPrefix = "terraform-test-%d"
storageAccountType = "Standard_GRS" // storageAccountType = "Standard_GRS"
} // }
deployment_mode = "Complete" // deployment_mode = "Complete"
} // }
//
` //`

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,257 +1,257 @@
package azurerm package azurerm
import ( //import (
"fmt" // "fmt"
"log" // "log"
"net/http" // "net/http"
"time" // "time"
//
"github.com/Azure/azure-sdk-for-go/arm/network" // "github.com/Azure/azure-sdk-for-go/arm/network"
"github.com/hashicorp/terraform/helper/hashcode" // "github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource" // "github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema" // "github.com/hashicorp/terraform/helper/schema"
) //)
//
func resourceArmVirtualNetwork() *schema.Resource { //func resourceArmVirtualNetwork() *schema.Resource {
return &schema.Resource{ // return &schema.Resource{
Create: resourceArmVirtualNetworkCreate, // Create: resourceArmVirtualNetworkCreate,
Read: resourceArmVirtualNetworkRead, // Read: resourceArmVirtualNetworkRead,
Update: resourceArmVirtualNetworkCreate, // Update: resourceArmVirtualNetworkCreate,
Delete: resourceArmVirtualNetworkDelete, // Delete: resourceArmVirtualNetworkDelete,
//
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"address_space": &schema.Schema{ // "address_space": &schema.Schema{
Type: schema.TypeList, // Type: schema.TypeList,
Required: true, // Required: true,
Elem: &schema.Schema{Type: schema.TypeString}, // Elem: &schema.Schema{Type: schema.TypeString},
}, // },
//
"dns_servers": &schema.Schema{ // "dns_servers": &schema.Schema{
Type: schema.TypeList, // Type: schema.TypeList,
Optional: true, // Optional: true,
Elem: &schema.Schema{ // Elem: &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
}, // },
}, // },
//
"subnet": &schema.Schema{ // "subnet": &schema.Schema{
Type: schema.TypeSet, // Type: schema.TypeSet,
Optional: true, // Optional: true,
Computed: true, // Computed: true,
Elem: &schema.Resource{ // Elem: &schema.Resource{
Schema: map[string]*schema.Schema{ // Schema: map[string]*schema.Schema{
"name": &schema.Schema{ // "name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
"address_prefix": &schema.Schema{ // "address_prefix": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
}, // },
"security_group": &schema.Schema{ // "security_group": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Optional: true, // Optional: true,
}, // },
}, // },
}, // },
Set: resourceAzureSubnetHash, // Set: resourceAzureSubnetHash,
}, // },
//
"location": &schema.Schema{ // "location": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
StateFunc: azureRMNormalizeLocation, // StateFunc: azureRMNormalizeLocation,
}, // },
//
"resource_group_name": &schema.Schema{ // "resource_group_name": &schema.Schema{
Type: schema.TypeString, // Type: schema.TypeString,
Required: true, // Required: true,
ForceNew: true, // ForceNew: true,
}, // },
//
"tags": tagsSchema(), // "tags": tagsSchema(),
}, // },
} // }
} //}
//
func resourceArmVirtualNetworkCreate(d *schema.ResourceData, meta interface{}) error { //func resourceArmVirtualNetworkCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient) // client := meta.(*ArmClient)
vnetClient := client.vnetClient // vnetClient := client.vnetClient
//
log.Printf("[INFO] preparing arguments for Azure ARM virtual network creation.") // log.Printf("[INFO] preparing arguments for Azure ARM virtual network creation.")
//
name := d.Get("name").(string) // name := d.Get("name").(string)
location := d.Get("location").(string) // location := d.Get("location").(string)
resGroup := d.Get("resource_group_name").(string) // resGroup := d.Get("resource_group_name").(string)
tags := d.Get("tags").(map[string]interface{}) // tags := d.Get("tags").(map[string]interface{})
//
vnet := network.VirtualNetwork{ // vnet := network.VirtualNetwork{
Name: &name, // Name: &name,
Location: &location, // Location: &location,
Properties: getVirtualNetworkProperties(d), // Properties: getVirtualNetworkProperties(d),
Tags: expandTags(tags), // Tags: expandTags(tags),
} // }
//
resp, err := vnetClient.CreateOrUpdate(resGroup, name, vnet) // resp, err := vnetClient.CreateOrUpdate(resGroup, name, vnet)
if err != nil { // if err != nil {
return err // return err
} // }
//
d.SetId(*resp.ID) // d.SetId(*resp.ID)
//
log.Printf("[DEBUG] Waiting for Virtual Network (%s) to become available", name) // log.Printf("[DEBUG] Waiting for Virtual Network (%s) to become available", name)
stateConf := &resource.StateChangeConf{ // stateConf := &resource.StateChangeConf{
Pending: []string{"Accepted", "Updating"}, // Pending: []string{"Accepted", "Updating"},
Target: []string{"Succeeded"}, // Target: []string{"Succeeded"},
Refresh: virtualNetworkStateRefreshFunc(client, resGroup, name), // Refresh: virtualNetworkStateRefreshFunc(client, resGroup, name),
Timeout: 10 * time.Minute, // Timeout: 10 * time.Minute,
} // }
if _, err := stateConf.WaitForState(); err != nil { // if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Virtual Network (%s) to become available: %s", name, err) // return fmt.Errorf("Error waiting for Virtual Network (%s) to become available: %s", name, err)
} // }
//
return resourceArmVirtualNetworkRead(d, meta) // return resourceArmVirtualNetworkRead(d, meta)
} //}
//
func resourceArmVirtualNetworkRead(d *schema.ResourceData, meta interface{}) error { //func resourceArmVirtualNetworkRead(d *schema.ResourceData, meta interface{}) error {
vnetClient := meta.(*ArmClient).vnetClient // vnetClient := meta.(*ArmClient).vnetClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["virtualNetworks"] // name := id.Path["virtualNetworks"]
//
resp, err := vnetClient.Get(resGroup, name, "") // resp, err := vnetClient.Get(resGroup, name, "")
if resp.StatusCode == http.StatusNotFound { // if resp.StatusCode == http.StatusNotFound {
d.SetId("") // d.SetId("")
return nil // return nil
} // }
if err != nil { // if err != nil {
return fmt.Errorf("Error making Read request on Azure virtual network %s: %s", name, err) // return fmt.Errorf("Error making Read request on Azure virtual network %s: %s", name, err)
} // }
vnet := *resp.Properties // vnet := *resp.Properties
//
// update appropriate values // // update appropriate values
d.Set("address_space", vnet.AddressSpace.AddressPrefixes) // d.Set("address_space", vnet.AddressSpace.AddressPrefixes)
//
subnets := &schema.Set{ // subnets := &schema.Set{
F: resourceAzureSubnetHash, // F: resourceAzureSubnetHash,
} // }
//
for _, subnet := range *vnet.Subnets { // for _, subnet := range *vnet.Subnets {
s := map[string]interface{}{} // s := map[string]interface{}{}
//
s["name"] = *subnet.Name // s["name"] = *subnet.Name
s["address_prefix"] = *subnet.Properties.AddressPrefix // s["address_prefix"] = *subnet.Properties.AddressPrefix
if subnet.Properties.NetworkSecurityGroup != nil { // if subnet.Properties.NetworkSecurityGroup != nil {
s["security_group"] = *subnet.Properties.NetworkSecurityGroup.ID // s["security_group"] = *subnet.Properties.NetworkSecurityGroup.ID
} // }
//
subnets.Add(s) // subnets.Add(s)
} // }
d.Set("subnet", subnets) // d.Set("subnet", subnets)
//
dnses := []string{} // dnses := []string{}
for _, dns := range *vnet.DhcpOptions.DNSServers { // for _, dns := range *vnet.DhcpOptions.DNSServers {
dnses = append(dnses, dns) // dnses = append(dnses, dns)
} // }
d.Set("dns_servers", dnses) // d.Set("dns_servers", dnses)
//
flattenAndSetTags(d, resp.Tags) // flattenAndSetTags(d, resp.Tags)
//
return nil // return nil
} //}
//
func resourceArmVirtualNetworkDelete(d *schema.ResourceData, meta interface{}) error { //func resourceArmVirtualNetworkDelete(d *schema.ResourceData, meta interface{}) error {
vnetClient := meta.(*ArmClient).vnetClient // vnetClient := meta.(*ArmClient).vnetClient
//
id, err := parseAzureResourceID(d.Id()) // id, err := parseAzureResourceID(d.Id())
if err != nil { // if err != nil {
return err // return err
} // }
resGroup := id.ResourceGroup // resGroup := id.ResourceGroup
name := id.Path["virtualNetworks"] // name := id.Path["virtualNetworks"]
//
_, err = vnetClient.Delete(resGroup, name) // _, err = vnetClient.Delete(resGroup, name)
//
return err // return err
} //}
//
func getVirtualNetworkProperties(d *schema.ResourceData) *network.VirtualNetworkPropertiesFormat { //func getVirtualNetworkProperties(d *schema.ResourceData) *network.VirtualNetworkPropertiesFormat {
// first; get address space prefixes: // // first; get address space prefixes:
prefixes := []string{} // prefixes := []string{}
for _, prefix := range d.Get("address_space").([]interface{}) { // for _, prefix := range d.Get("address_space").([]interface{}) {
prefixes = append(prefixes, prefix.(string)) // prefixes = append(prefixes, prefix.(string))
} // }
//
// then; the dns servers: // // then; the dns servers:
dnses := []string{} // dnses := []string{}
for _, dns := range d.Get("dns_servers").([]interface{}) { // for _, dns := range d.Get("dns_servers").([]interface{}) {
dnses = append(dnses, dns.(string)) // dnses = append(dnses, dns.(string))
} // }
//
// then; the subnets: // // then; the subnets:
subnets := []network.Subnet{} // subnets := []network.Subnet{}
if subs := d.Get("subnet").(*schema.Set); subs.Len() > 0 { // if subs := d.Get("subnet").(*schema.Set); subs.Len() > 0 {
for _, subnet := range subs.List() { // for _, subnet := range subs.List() {
subnet := subnet.(map[string]interface{}) // subnet := subnet.(map[string]interface{})
//
name := subnet["name"].(string) // name := subnet["name"].(string)
prefix := subnet["address_prefix"].(string) // prefix := subnet["address_prefix"].(string)
secGroup := subnet["security_group"].(string) // secGroup := subnet["security_group"].(string)
//
var subnetObj network.Subnet // var subnetObj network.Subnet
subnetObj.Name = &name // subnetObj.Name = &name
subnetObj.Properties = &network.SubnetPropertiesFormat{} // subnetObj.Properties = &network.SubnetPropertiesFormat{}
subnetObj.Properties.AddressPrefix = &prefix // subnetObj.Properties.AddressPrefix = &prefix
//
if secGroup != "" { // if secGroup != "" {
subnetObj.Properties.NetworkSecurityGroup = &network.SecurityGroup{ // subnetObj.Properties.NetworkSecurityGroup = &network.SecurityGroup{
ID: &secGroup, // ID: &secGroup,
} // }
} // }
//
subnets = append(subnets, subnetObj) // subnets = append(subnets, subnetObj)
} // }
} // }
//
// finally; return the struct: // // finally; return the struct:
return &network.VirtualNetworkPropertiesFormat{ // return &network.VirtualNetworkPropertiesFormat{
AddressSpace: &network.AddressSpace{ // AddressSpace: &network.AddressSpace{
AddressPrefixes: &prefixes, // AddressPrefixes: &prefixes,
}, // },
DhcpOptions: &network.DhcpOptions{ // DhcpOptions: &network.DhcpOptions{
DNSServers: &dnses, // DNSServers: &dnses,
}, // },
Subnets: &subnets, // Subnets: &subnets,
} // }
} //}
//
func resourceAzureSubnetHash(v interface{}) int { //func resourceAzureSubnetHash(v interface{}) int {
m := v.(map[string]interface{}) // m := v.(map[string]interface{})
subnet := m["name"].(string) + m["address_prefix"].(string) // subnet := m["name"].(string) + m["address_prefix"].(string)
if securityGroup, present := m["security_group"]; present { // if securityGroup, present := m["security_group"]; present {
subnet = subnet + securityGroup.(string) // subnet = subnet + securityGroup.(string)
} // }
return hashcode.String(subnet) // return hashcode.String(subnet)
} //}
//
func virtualNetworkStateRefreshFunc(client *ArmClient, resourceGroupName string, networkName string) resource.StateRefreshFunc { //func virtualNetworkStateRefreshFunc(client *ArmClient, resourceGroupName string, networkName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) { // return func() (interface{}, string, error) {
res, err := client.vnetClient.Get(resourceGroupName, networkName, "") // res, err := client.vnetClient.Get(resourceGroupName, networkName, "")
if err != nil { // if err != nil {
return nil, "", fmt.Errorf("Error issuing read request in virtualNetworkStateRefreshFunc to Azure ARM for virtual network '%s' (RG: '%s'): %s", networkName, resourceGroupName, err) // return nil, "", fmt.Errorf("Error issuing read request in virtualNetworkStateRefreshFunc to Azure ARM for virtual network '%s' (RG: '%s'): %s", networkName, resourceGroupName, err)
} // }
//
return res, *res.Properties.ProvisioningState, nil // return res, *res.Properties.ProvisioningState, nil
} // }
} //}