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"
"log"
"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/compute"
"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/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"
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) {
var version string
if terraform.VersionPrerelease != "" {
@ -130,7 +113,23 @@ func (c *Config) getArmClient() (*ArmClient, error) {
}
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 {
return nil, err
}
@ -284,7 +283,7 @@ func (c *Config) getArmClient() (*ArmClient, error) {
ssc := storage.NewAccountsClient(c.SubscriptionID)
setUserAgent(&ssc.Client)
ssc.Authorizer = spt
ssc.Sender = autorest.CreateSender(withRequestLogging(), withPollWatcher())
ssc.Sender = autorest.CreateSender(withRequestLogging())
client.storageServiceClient = ssc
suc := storage.NewUsageOperationsClient(c.SubscriptionID)
@ -349,6 +348,7 @@ func (armClient *ArmClient) getBlobStorageClientForStorageAccount(resourceGroupN
blobClient := storageClient.GetBlobService()
return &blobClient, true, nil
}
func (armClient *ArmClient) getQueueServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.QueueServiceClient, bool, error) {
key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName)
if err != nil {

View File

@ -2,12 +2,9 @@ package azurerm
import (
"fmt"
"log"
"net/http"
"reflect"
"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/terraform/helper/mutexkv"
"github.com/hashicorp/terraform/helper/resource"
@ -21,25 +18,25 @@ import (
func Provider() terraform.ResourceProvider {
return &schema.Provider{
Schema: map[string]*schema.Schema{
"subscription_id": &schema.Schema{
"subscription_id": {
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_SUBSCRIPTION_ID", ""),
},
"client_id": &schema.Schema{
"client_id": {
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_ID", ""),
},
"client_secret": &schema.Schema{
"client_secret": {
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_SECRET", ""),
},
"tenant_id": &schema.Schema{
"tenant_id": {
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("ARM_TENANT_ID", ""),
@ -47,37 +44,40 @@ func Provider() terraform.ResourceProvider {
},
ResourcesMap: map[string]*schema.Resource{
"azurerm_availability_set": resourceArmAvailabilitySet(),
"azurerm_cdn_endpoint": resourceArmCdnEndpoint(),
"azurerm_cdn_profile": resourceArmCdnProfile(),
"azurerm_dns_a_record": resourceArmDnsARecord(),
"azurerm_dns_aaaa_record": resourceArmDnsAAAARecord(),
"azurerm_dns_cname_record": resourceArmDnsCNameRecord(),
"azurerm_dns_mx_record": resourceArmDnsMxRecord(),
"azurerm_dns_ns_record": resourceArmDnsNsRecord(),
"azurerm_dns_srv_record": resourceArmDnsSrvRecord(),
"azurerm_dns_txt_record": resourceArmDnsTxtRecord(),
"azurerm_dns_zone": resourceArmDnsZone(),
"azurerm_local_network_gateway": resourceArmLocalNetworkGateway(),
"azurerm_network_interface": resourceArmNetworkInterface(),
"azurerm_network_security_group": resourceArmNetworkSecurityGroup(),
"azurerm_network_security_rule": resourceArmNetworkSecurityRule(),
"azurerm_public_ip": resourceArmPublicIp(),
"azurerm_resource_group": resourceArmResourceGroup(),
"azurerm_route": resourceArmRoute(),
"azurerm_route_table": resourceArmRouteTable(),
"azurerm_search_service": resourceArmSearchService(),
"azurerm_sql_database": resourceArmSqlDatabase(),
"azurerm_sql_firewall_rule": resourceArmSqlFirewallRule(),
"azurerm_sql_server": resourceArmSqlServer(),
"azurerm_storage_account": resourceArmStorageAccount(),
"azurerm_storage_blob": resourceArmStorageBlob(),
"azurerm_storage_container": resourceArmStorageContainer(),
"azurerm_storage_queue": resourceArmStorageQueue(),
"azurerm_subnet": resourceArmSubnet(),
"azurerm_template_deployment": resourceArmTemplateDeployment(),
"azurerm_virtual_machine": resourceArmVirtualMachine(),
"azurerm_virtual_network": resourceArmVirtualNetwork(),
// These resources use the Azure ARM SDK
"azurerm_availability_set": resourceArmAvailabilitySet(),
//"azurerm_cdn_endpoint": resourceArmCdnEndpoint(),
//"azurerm_cdn_profile": resourceArmCdnProfile(),
//"azurerm_local_network_gateway": resourceArmLocalNetworkGateway(),
//"azurerm_network_interface": resourceArmNetworkInterface(),
//"azurerm_network_security_group": resourceArmNetworkSecurityGroup(),
//"azurerm_network_security_rule": resourceArmNetworkSecurityRule(),
//"azurerm_public_ip": resourceArmPublicIp(),
//"azurerm_route": resourceArmRoute(),
//"azurerm_route_table": resourceArmRouteTable(),
//"azurerm_storage_account": resourceArmStorageAccount(),
"azurerm_storage_blob": resourceArmStorageBlob(),
//"azurerm_storage_container": resourceArmStorageContainer(),
"azurerm_storage_queue": resourceArmStorageQueue(),
//"azurerm_subnet": resourceArmSubnet(),
//"azurerm_template_deployment": resourceArmTemplateDeployment(),
//"azurerm_virtual_machine": resourceArmVirtualMachine(),
//"azurerm_virtual_network": resourceArmVirtualNetwork(),
// These resources use the Riviera SDK
"azurerm_dns_a_record": resourceArmDnsARecord(),
"azurerm_dns_aaaa_record": resourceArmDnsAAAARecord(),
"azurerm_dns_cname_record": resourceArmDnsCNameRecord(),
"azurerm_dns_mx_record": resourceArmDnsMxRecord(),
"azurerm_dns_ns_record": resourceArmDnsNsRecord(),
"azurerm_dns_srv_record": resourceArmDnsSrvRecord(),
"azurerm_dns_txt_record": resourceArmDnsTxtRecord(),
"azurerm_dns_zone": resourceArmDnsZone(),
"azurerm_resource_group": resourceArmResourceGroup(),
"azurerm_search_service": resourceArmSearchService(),
"azurerm_sql_database": resourceArmSqlDatabase(),
"azurerm_sql_firewall_rule": resourceArmSqlFirewallRule(),
"azurerm_sql_server": resourceArmSqlServer(),
},
ConfigureFunc: providerConfigure,
}
@ -197,39 +197,6 @@ func azureRMNormalizeLocation(location interface{}) string {
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
var armMutexKV = mutexkv.NewMutexKV()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,86 +1,16 @@
package azurerm
import (
"fmt"
"net/http"
"testing"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
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) {
//
//import (
// "fmt"
// "net/http"
// "testing"
//
// "github.com/hashicorp/terraform/helper/resource"
// "github.com/hashicorp/terraform/terraform"
//)
//
//func TestAccAzureRMNetworkInterface_basic(t *testing.T) {
//
// resource.Test(t, resource.TestCase{
// PreCheck: func() { testAccPreCheck(t) },
@ -91,221 +21,149 @@ func TestAccAzureRMNetworkInterface_withTags(t *testing.T) {
// Config: testAccAzureRMNetworkInterface_basic,
// Check: resource.ComposeTestCheckFunc(
// 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 {
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 {
return fmt.Errorf("Not found: %s", name)
}
name := rs.Primary.Attributes["name"]
resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
if !hasResourceGroup {
return fmt.Errorf("Bad: no resource group found in state for availability set: %s", name)
}
conn := testAccProvider.Meta().(*ArmClient).ifaceClient
resp, err := conn.Get(resourceGroup, name, "")
if err != nil {
return fmt.Errorf("Bad: Get on ifaceClient: %s", err)
}
if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("Bad: Network Interface %q (resource group: %q) does not exist", name, resourceGroup)
}
return nil
}
}
func testCheckAzureRMNetworkInterfaceDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*ArmClient).ifaceClient
for _, rs := range s.RootModule().Resources {
if rs.Type != "azurerm_network_interface" {
continue
}
name := rs.Primary.Attributes["name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"]
resp, err := conn.Get(resourceGroup, name, "")
if err != nil {
return nil
}
if resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("Network Interface still exists:\n%#v", resp.Properties)
}
}
return nil
}
var testAccAzureRMNetworkInterface_basic = `
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"
}
}
`
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}"
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}"
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" {
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 = `
//
//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{
//// PreCheck: func() { testAccPreCheck(t) },
//// Providers: testAccProviders,
//// CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy,
//// Steps: []resource.TestStep{
//// resource.TestStep{
//// Config: testAccAzureRMNetworkInterface_basic,
//// Check: resource.ComposeTestCheckFunc(
//// 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 {
// 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 {
// return fmt.Errorf("Not found: %s", name)
// }
//
// name := rs.Primary.Attributes["name"]
// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
// if !hasResourceGroup {
// return fmt.Errorf("Bad: no resource group found in state for availability set: %s", name)
// }
//
// conn := testAccProvider.Meta().(*ArmClient).ifaceClient
//
// resp, err := conn.Get(resourceGroup, name, "")
// if err != nil {
// return fmt.Errorf("Bad: Get on ifaceClient: %s", err)
// }
//
// if resp.StatusCode == http.StatusNotFound {
// return fmt.Errorf("Bad: Network Interface %q (resource group: %q) does not exist", name, resourceGroup)
// }
//
// return nil
// }
//}
//
//func testCheckAzureRMNetworkInterfaceDestroy(s *terraform.State) error {
// conn := testAccProvider.Meta().(*ArmClient).ifaceClient
//
// for _, rs := range s.RootModule().Resources {
// if rs.Type != "azurerm_network_interface" {
// continue
// }
//
// name := rs.Primary.Attributes["name"]
// resourceGroup := rs.Primary.Attributes["resource_group_name"]
//
// resp, err := conn.Get(resourceGroup, name, "")
//
// if err != nil {
// return nil
// }
//
// if resp.StatusCode != http.StatusNotFound {
// return fmt.Errorf("Network Interface still exists:\n%#v", resp.Properties)
// }
// }
//
// return nil
//}
//
//var testAccAzureRMNetworkInterface_basic = `
//resource "azurerm_resource_group" "test" {
// name = "acceptanceTestResourceGroup1"
// location = "West US"
@ -325,11 +183,71 @@ resource "azurerm_network_interface" "test" {
// address_prefix = "10.0.2.0/24"
//}
//
//resource "azurerm_subnet" "test1" {
// name = "testsubnet1"
//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"
// }
//}
//`
//
//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}"
// 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" {
@ -343,11 +261,94 @@ resource "azurerm_network_interface" "test" {
// private_ip_address_allocation = "dynamic"
// }
//
// ip_configuration {
// name = "testconfiguration2"
// subnet_id = "${azurerm_subnet.test1.id}"
// private_ip_address_allocation = "dynamic"
// primary = true
// 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" {
//// 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
import (
"bytes"
"fmt"
"log"
"net/http"
"time"
"github.com/Azure/azure-sdk-for-go/arm/network"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceArmNetworkSecurityGroup() *schema.Resource {
return &schema.Resource{
Create: resourceArmNetworkSecurityGroupCreate,
Read: resourceArmNetworkSecurityGroupRead,
Update: resourceArmNetworkSecurityGroupCreate,
Delete: resourceArmNetworkSecurityGroupDelete,
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"location": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
StateFunc: azureRMNormalizeLocation,
},
"resource_group_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"security_rule": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"description": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if len(value) > 140 {
errors = append(errors, fmt.Errorf(
"The network security rule description can be no longer than 140 chars"))
}
return
},
},
"protocol": &schema.Schema{
Type: schema.TypeString,
Required: true,
ValidateFunc: validateNetworkSecurityRuleProtocol,
},
"source_port_range": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"destination_port_range": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"source_address_prefix": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"destination_address_prefix": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"access": &schema.Schema{
Type: schema.TypeString,
Required: true,
ValidateFunc: validateNetworkSecurityRuleAccess,
},
"priority": &schema.Schema{
Type: schema.TypeInt,
Required: true,
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := v.(int)
if value < 100 || value > 4096 {
errors = append(errors, fmt.Errorf(
"The `priority` can only be between 100 and 4096"))
}
return
},
},
"direction": &schema.Schema{
Type: schema.TypeString,
Required: true,
ValidateFunc: validateNetworkSecurityRuleDirection,
},
},
},
Set: resourceArmNetworkSecurityGroupRuleHash,
},
"tags": tagsSchema(),
},
}
}
func resourceArmNetworkSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient)
secClient := client.secGroupClient
name := d.Get("name").(string)
location := d.Get("location").(string)
resGroup := d.Get("resource_group_name").(string)
tags := d.Get("tags").(map[string]interface{})
sgRules, sgErr := expandAzureRmSecurityRules(d)
if sgErr != nil {
return fmt.Errorf("Error Building list of Network Security Group Rules: %s", sgErr)
}
sg := network.SecurityGroup{
Name: &name,
Location: &location,
Properties: &network.SecurityGroupPropertiesFormat{
SecurityRules: &sgRules,
},
Tags: expandTags(tags),
}
resp, err := secClient.CreateOrUpdate(resGroup, name, sg)
if err != nil {
return err
}
d.SetId(*resp.ID)
log.Printf("[DEBUG] Waiting for Network Security Group (%s) to become available", name)
stateConf := &resource.StateChangeConf{
Pending: []string{"Accepted", "Updating"},
Target: []string{"Succeeded"},
Refresh: securityGroupStateRefreshFunc(client, resGroup, name),
Timeout: 10 * time.Minute,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Network Securty Group (%s) to become available: %s", name, err)
}
return resourceArmNetworkSecurityGroupRead(d, meta)
}
func resourceArmNetworkSecurityGroupRead(d *schema.ResourceData, meta interface{}) error {
secGroupClient := meta.(*ArmClient).secGroupClient
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resGroup := id.ResourceGroup
name := id.Path["networkSecurityGroups"]
resp, err := secGroupClient.Get(resGroup, name, "")
if resp.StatusCode == http.StatusNotFound {
d.SetId("")
return nil
}
if err != nil {
return fmt.Errorf("Error making Read request on Azure Network Security Group %s: %s", name, err)
}
if resp.Properties.SecurityRules != nil {
d.Set("security_rule", flattenNetworkSecurityRules(resp.Properties.SecurityRules))
}
flattenAndSetTags(d, resp.Tags)
return nil
}
func resourceArmNetworkSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error {
secGroupClient := meta.(*ArmClient).secGroupClient
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resGroup := id.ResourceGroup
name := id.Path["networkSecurityGroups"]
_, err = secGroupClient.Delete(resGroup, name)
return err
}
func resourceArmNetworkSecurityGroupRuleHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["protocol"].(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["source_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("%d-", m["priority"].(int)))
buf.WriteString(fmt.Sprintf("%s-", m["direction"].(string)))
return hashcode.String(buf.String())
}
func securityGroupStateRefreshFunc(client *ArmClient, resourceGroupName string, securityGroupName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
res, err := client.secGroupClient.Get(resourceGroupName, securityGroupName, "")
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 res, *res.Properties.ProvisioningState, nil
}
}
func flattenNetworkSecurityRules(rules *[]network.SecurityRule) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(*rules))
for _, rule := range *rules {
sgRule := make(map[string]interface{})
sgRule["name"] = *rule.Name
sgRule["destination_address_prefix"] = *rule.Properties.DestinationAddressPrefix
sgRule["destination_port_range"] = *rule.Properties.DestinationPortRange
sgRule["source_address_prefix"] = *rule.Properties.SourceAddressPrefix
sgRule["source_port_range"] = *rule.Properties.SourcePortRange
sgRule["priority"] = int(*rule.Properties.Priority)
sgRule["access"] = rule.Properties.Access
sgRule["direction"] = rule.Properties.Direction
sgRule["protocol"] = rule.Properties.Protocol
if rule.Properties.Description != nil {
sgRule["description"] = *rule.Properties.Description
}
result = append(result, sgRule)
}
return result
}
func expandAzureRmSecurityRules(d *schema.ResourceData) ([]network.SecurityRule, error) {
sgRules := d.Get("security_rule").(*schema.Set).List()
rules := make([]network.SecurityRule, 0, len(sgRules))
for _, sgRaw := range sgRules {
data := sgRaw.(map[string]interface{})
source_port_range := data["source_port_range"].(string)
destination_port_range := data["destination_port_range"].(string)
source_address_prefix := data["source_address_prefix"].(string)
destination_address_prefix := data["destination_address_prefix"].(string)
priority := data["priority"].(int)
properties := network.SecurityRulePropertiesFormat{
SourcePortRange: &source_port_range,
DestinationPortRange: &destination_port_range,
SourceAddressPrefix: &source_address_prefix,
DestinationAddressPrefix: &destination_address_prefix,
Priority: &priority,
Access: network.SecurityRuleAccess(data["access"].(string)),
Direction: network.SecurityRuleDirection(data["direction"].(string)),
Protocol: network.SecurityRuleProtocol(data["protocol"].(string)),
}
if v := data["description"].(string); v != "" {
properties.Description = &v
}
name := data["name"].(string)
rule := network.SecurityRule{
Name: &name,
Properties: &properties,
}
rules = append(rules, rule)
}
return rules, nil
}
//import (
// "bytes"
// "fmt"
// "log"
// "net/http"
// "time"
//
// "github.com/Azure/azure-sdk-for-go/arm/network"
// "github.com/hashicorp/terraform/helper/hashcode"
// "github.com/hashicorp/terraform/helper/resource"
// "github.com/hashicorp/terraform/helper/schema"
//)
//
//func resourceArmNetworkSecurityGroup() *schema.Resource {
// return &schema.Resource{
// Create: resourceArmNetworkSecurityGroupCreate,
// Read: resourceArmNetworkSecurityGroupRead,
// Update: resourceArmNetworkSecurityGroupCreate,
// Delete: resourceArmNetworkSecurityGroupDelete,
//
// Schema: map[string]*schema.Schema{
// "name": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// ForceNew: true,
// },
//
// "location": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// ForceNew: true,
// StateFunc: azureRMNormalizeLocation,
// },
//
// "resource_group_name": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// ForceNew: true,
// },
//
// "security_rule": &schema.Schema{
// Type: schema.TypeSet,
// Optional: true,
// Computed: true,
// Elem: &schema.Resource{
// Schema: map[string]*schema.Schema{
// "name": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// },
//
// "description": &schema.Schema{
// Type: schema.TypeString,
// Optional: true,
// ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
// value := v.(string)
// if len(value) > 140 {
// errors = append(errors, fmt.Errorf(
// "The network security rule description can be no longer than 140 chars"))
// }
// return
// },
// },
//
// "protocol": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// ValidateFunc: validateNetworkSecurityRuleProtocol,
// },
//
// "source_port_range": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// },
//
// "destination_port_range": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// },
//
// "source_address_prefix": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// },
//
// "destination_address_prefix": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// },
//
// "access": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// ValidateFunc: validateNetworkSecurityRuleAccess,
// },
//
// "priority": &schema.Schema{
// Type: schema.TypeInt,
// Required: true,
// ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
// value := v.(int)
// if value < 100 || value > 4096 {
// errors = append(errors, fmt.Errorf(
// "The `priority` can only be between 100 and 4096"))
// }
// return
// },
// },
//
// "direction": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// ValidateFunc: validateNetworkSecurityRuleDirection,
// },
// },
// },
// Set: resourceArmNetworkSecurityGroupRuleHash,
// },
//
// "tags": tagsSchema(),
// },
// }
//}
//
//func resourceArmNetworkSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error {
// client := meta.(*ArmClient)
// secClient := client.secGroupClient
//
// name := d.Get("name").(string)
// location := d.Get("location").(string)
// resGroup := d.Get("resource_group_name").(string)
// tags := d.Get("tags").(map[string]interface{})
//
// sgRules, sgErr := expandAzureRmSecurityRules(d)
// if sgErr != nil {
// return fmt.Errorf("Error Building list of Network Security Group Rules: %s", sgErr)
// }
//
// sg := network.SecurityGroup{
// Name: &name,
// Location: &location,
// Properties: &network.SecurityGroupPropertiesFormat{
// SecurityRules: &sgRules,
// },
// Tags: expandTags(tags),
// }
//
// resp, err := secClient.CreateOrUpdate(resGroup, name, sg)
// if err != nil {
// return err
// }
//
// d.SetId(*resp.ID)
//
// log.Printf("[DEBUG] Waiting for Network Security Group (%s) to become available", name)
// stateConf := &resource.StateChangeConf{
// Pending: []string{"Accepted", "Updating"},
// Target: []string{"Succeeded"},
// Refresh: securityGroupStateRefreshFunc(client, resGroup, name),
// Timeout: 10 * time.Minute,
// }
// if _, err := stateConf.WaitForState(); err != nil {
// return fmt.Errorf("Error waiting for Network Securty Group (%s) to become available: %s", name, err)
// }
//
// return resourceArmNetworkSecurityGroupRead(d, meta)
//}
//
//func resourceArmNetworkSecurityGroupRead(d *schema.ResourceData, meta interface{}) error {
// secGroupClient := meta.(*ArmClient).secGroupClient
//
// id, err := parseAzureResourceID(d.Id())
// if err != nil {
// return err
// }
// resGroup := id.ResourceGroup
// name := id.Path["networkSecurityGroups"]
//
// resp, err := secGroupClient.Get(resGroup, name, "")
// if resp.StatusCode == http.StatusNotFound {
// d.SetId("")
// return nil
// }
// if err != nil {
// return fmt.Errorf("Error making Read request on Azure Network Security Group %s: %s", name, err)
// }
//
// if resp.Properties.SecurityRules != nil {
// d.Set("security_rule", flattenNetworkSecurityRules(resp.Properties.SecurityRules))
// }
//
// flattenAndSetTags(d, resp.Tags)
//
// return nil
//}
//
//func resourceArmNetworkSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error {
// secGroupClient := meta.(*ArmClient).secGroupClient
//
// id, err := parseAzureResourceID(d.Id())
// if err != nil {
// return err
// }
// resGroup := id.ResourceGroup
// name := id.Path["networkSecurityGroups"]
//
// _, err = secGroupClient.Delete(resGroup, name)
//
// return err
//}
//
//func resourceArmNetworkSecurityGroupRuleHash(v interface{}) int {
// var buf bytes.Buffer
// m := v.(map[string]interface{})
// buf.WriteString(fmt.Sprintf("%s-", m["protocol"].(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["source_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("%d-", m["priority"].(int)))
// buf.WriteString(fmt.Sprintf("%s-", m["direction"].(string)))
//
// return hashcode.String(buf.String())
//}
//
//func securityGroupStateRefreshFunc(client *ArmClient, resourceGroupName string, securityGroupName string) resource.StateRefreshFunc {
// return func() (interface{}, string, error) {
// res, err := client.secGroupClient.Get(resourceGroupName, securityGroupName, "")
// 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 res, *res.Properties.ProvisioningState, nil
// }
//}
//
//func flattenNetworkSecurityRules(rules *[]network.SecurityRule) []map[string]interface{} {
// result := make([]map[string]interface{}, 0, len(*rules))
// for _, rule := range *rules {
// sgRule := make(map[string]interface{})
// sgRule["name"] = *rule.Name
// sgRule["destination_address_prefix"] = *rule.Properties.DestinationAddressPrefix
// sgRule["destination_port_range"] = *rule.Properties.DestinationPortRange
// sgRule["source_address_prefix"] = *rule.Properties.SourceAddressPrefix
// sgRule["source_port_range"] = *rule.Properties.SourcePortRange
// sgRule["priority"] = int(*rule.Properties.Priority)
// sgRule["access"] = rule.Properties.Access
// sgRule["direction"] = rule.Properties.Direction
// sgRule["protocol"] = rule.Properties.Protocol
//
// if rule.Properties.Description != nil {
// sgRule["description"] = *rule.Properties.Description
// }
//
// result = append(result, sgRule)
// }
// return result
//}
//
//func expandAzureRmSecurityRules(d *schema.ResourceData) ([]network.SecurityRule, error) {
// sgRules := d.Get("security_rule").(*schema.Set).List()
// rules := make([]network.SecurityRule, 0, len(sgRules))
//
// for _, sgRaw := range sgRules {
// data := sgRaw.(map[string]interface{})
//
// source_port_range := data["source_port_range"].(string)
// destination_port_range := data["destination_port_range"].(string)
// source_address_prefix := data["source_address_prefix"].(string)
// destination_address_prefix := data["destination_address_prefix"].(string)
// priority := data["priority"].(int)
//
// properties := network.SecurityRulePropertiesFormat{
// SourcePortRange: &source_port_range,
// DestinationPortRange: &destination_port_range,
// SourceAddressPrefix: &source_address_prefix,
// DestinationAddressPrefix: &destination_address_prefix,
// Priority: &priority,
// Access: network.SecurityRuleAccess(data["access"].(string)),
// Direction: network.SecurityRuleDirection(data["direction"].(string)),
// Protocol: network.SecurityRuleProtocol(data["protocol"].(string)),
// }
//
// if v := data["description"].(string); v != "" {
// properties.Description = &v
// }
//
// name := data["name"].(string)
// rule := network.SecurityRule{
// Name: &name,
// Properties: &properties,
// }
//
// rules = append(rules, rule)
// }
//
// return rules, nil
//}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,309 +1,309 @@
package azurerm
import (
"fmt"
"net/http"
"regexp"
"strings"
"github.com/Azure/azure-sdk-for-go/arm/storage"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceArmStorageAccount() *schema.Resource {
return &schema.Resource{
Create: resourceArmStorageAccountCreate,
Read: resourceArmStorageAccountRead,
Update: resourceArmStorageAccountUpdate,
Delete: resourceArmStorageAccountDelete,
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateArmStorageAccountName,
},
"resource_group_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"location": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
StateFunc: azureRMNormalizeLocation,
},
"account_type": &schema.Schema{
Type: schema.TypeString,
Required: true,
ValidateFunc: validateArmStorageAccountType,
},
"primary_location": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"secondary_location": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"primary_blob_endpoint": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"secondary_blob_endpoint": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"primary_queue_endpoint": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"secondary_queue_endpoint": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"primary_table_endpoint": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"secondary_table_endpoint": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
// NOTE: The API does not appear to expose a secondary file endpoint
"primary_file_endpoint": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"primary_access_key": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"secondary_access_key": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"tags": tagsSchema(),
},
}
}
func resourceArmStorageAccountCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).storageServiceClient
resourceGroupName := d.Get("resource_group_name").(string)
storageAccountName := d.Get("name").(string)
accountType := d.Get("account_type").(string)
location := d.Get("location").(string)
tags := d.Get("tags").(map[string]interface{})
opts := storage.AccountCreateParameters{
Location: &location,
Properties: &storage.AccountPropertiesCreateParameters{
AccountType: storage.AccountType(accountType),
},
Tags: expandTags(tags),
}
accResp, err := client.Create(resourceGroupName, storageAccountName, opts)
if err != nil {
return fmt.Errorf("Error creating Azure Storage Account '%s': %s", storageAccountName, err)
}
_, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK)
if err != nil {
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
account, err := client.GetProperties(resourceGroupName, storageAccountName)
if err != nil {
return fmt.Errorf("Error retrieving Azure Storage Account %q: %s", storageAccountName, err)
}
d.SetId(*account.ID)
return resourceArmStorageAccountRead(d, meta)
}
// 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
// available requires a call to Update per parameter...
func resourceArmStorageAccountUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).storageServiceClient
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
storageAccountName := id.Path["storageAccounts"]
resourceGroupName := id.ResourceGroup
d.Partial(true)
if d.HasChange("account_type") {
accountType := d.Get("account_type").(string)
opts := storage.AccountUpdateParameters{
Properties: &storage.AccountPropertiesUpdateParameters{
AccountType: storage.AccountType(accountType),
},
}
accResp, err := client.Update(resourceGroupName, storageAccountName, opts)
if err != nil {
return fmt.Errorf("Error updating Azure Storage Account type %q: %s", storageAccountName, err)
}
_, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK)
if err != nil {
return fmt.Errorf("Error updating Azure Storage Account type %q: %s", storageAccountName, err)
}
d.SetPartial("account_type")
}
if d.HasChange("tags") {
tags := d.Get("tags").(map[string]interface{})
opts := storage.AccountUpdateParameters{
Tags: expandTags(tags),
}
accResp, err := client.Update(resourceGroupName, storageAccountName, opts)
if err != nil {
return fmt.Errorf("Error updating Azure Storage Account tags %q: %s", storageAccountName, err)
}
_, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK)
if err != nil {
return fmt.Errorf("Error updating Azure Storage Account tags %q: %s", storageAccountName, err)
}
d.SetPartial("tags")
}
d.Partial(false)
return nil
}
func resourceArmStorageAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).storageServiceClient
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
name := id.Path["storageAccounts"]
resGroup := id.ResourceGroup
resp, err := client.GetProperties(resGroup, name)
if err != nil {
if resp.StatusCode == http.StatusNotFound {
d.SetId("")
return nil
}
return fmt.Errorf("Error reading the state of AzureRM Storage Account %q: %s", name, err)
}
keys, err := client.ListKeys(resGroup, name)
if err != nil {
return err
}
d.Set("primary_access_key", keys.Key1)
d.Set("secondary_access_key", keys.Key2)
d.Set("location", resp.Location)
d.Set("account_type", resp.Properties.AccountType)
d.Set("primary_location", resp.Properties.PrimaryLocation)
d.Set("secondary_location", resp.Properties.SecondaryLocation)
if resp.Properties.PrimaryEndpoints != nil {
d.Set("primary_blob_endpoint", resp.Properties.PrimaryEndpoints.Blob)
d.Set("primary_queue_endpoint", resp.Properties.PrimaryEndpoints.Queue)
d.Set("primary_table_endpoint", resp.Properties.PrimaryEndpoints.Table)
d.Set("primary_file_endpoint", resp.Properties.PrimaryEndpoints.File)
}
if resp.Properties.SecondaryEndpoints != nil {
if resp.Properties.SecondaryEndpoints.Blob != nil {
d.Set("secondary_blob_endpoint", resp.Properties.SecondaryEndpoints.Blob)
} else {
d.Set("secondary_blob_endpoint", "")
}
if resp.Properties.SecondaryEndpoints.Queue != nil {
d.Set("secondary_queue_endpoint", resp.Properties.SecondaryEndpoints.Queue)
} else {
d.Set("secondary_queue_endpoint", "")
}
if resp.Properties.SecondaryEndpoints.Table != nil {
d.Set("secondary_table_endpoint", resp.Properties.SecondaryEndpoints.Table)
} else {
d.Set("secondary_table_endpoint", "")
}
}
flattenAndSetTags(d, resp.Tags)
return nil
}
func resourceArmStorageAccountDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).storageServiceClient
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
name := id.Path["storageAccounts"]
resGroup := id.ResourceGroup
accResp, err := client.Delete(resGroup, name)
if err != nil {
return fmt.Errorf("Error issuing AzureRM delete request for storage account %q: %s", name, err)
}
_, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response, http.StatusNotFound)
if err != nil {
return fmt.Errorf("Error polling for AzureRM delete request for storage account %q: %s", name, err)
}
return nil
}
func validateArmStorageAccountName(v interface{}, k string) (ws []string, es []error) {
input := v.(string)
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"))
}
return
}
func validateArmStorageAccountType(v interface{}, k string) (ws []string, es []error) {
validAccountTypes := []string{"standard_lrs", "standard_zrs",
"standard_grs", "standard_ragrs", "premium_lrs"}
input := strings.ToLower(v.(string))
for _, valid := range validAccountTypes {
if valid == input {
return
}
}
es = append(es, fmt.Errorf("Invalid storage account type %q", input))
return
}
//import (
// "fmt"
// "net/http"
// "regexp"
// "strings"
//
// "github.com/Azure/azure-sdk-for-go/arm/storage"
// "github.com/hashicorp/terraform/helper/schema"
//)
//
//func resourceArmStorageAccount() *schema.Resource {
// return &schema.Resource{
// Create: resourceArmStorageAccountCreate,
// Read: resourceArmStorageAccountRead,
// Update: resourceArmStorageAccountUpdate,
// Delete: resourceArmStorageAccountDelete,
//
// Schema: map[string]*schema.Schema{
// "name": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// ForceNew: true,
// ValidateFunc: validateArmStorageAccountName,
// },
//
// "resource_group_name": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// ForceNew: true,
// },
//
// "location": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// ForceNew: true,
// StateFunc: azureRMNormalizeLocation,
// },
//
// "account_type": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// ValidateFunc: validateArmStorageAccountType,
// },
//
// "primary_location": &schema.Schema{
// Type: schema.TypeString,
// Computed: true,
// },
//
// "secondary_location": &schema.Schema{
// Type: schema.TypeString,
// Computed: true,
// },
//
// "primary_blob_endpoint": &schema.Schema{
// Type: schema.TypeString,
// Computed: true,
// },
//
// "secondary_blob_endpoint": &schema.Schema{
// Type: schema.TypeString,
// Computed: true,
// },
//
// "primary_queue_endpoint": &schema.Schema{
// Type: schema.TypeString,
// Computed: true,
// },
//
// "secondary_queue_endpoint": &schema.Schema{
// Type: schema.TypeString,
// Computed: true,
// },
//
// "primary_table_endpoint": &schema.Schema{
// Type: schema.TypeString,
// Computed: true,
// },
//
// "secondary_table_endpoint": &schema.Schema{
// Type: schema.TypeString,
// Computed: true,
// },
//
// // NOTE: The API does not appear to expose a secondary file endpoint
// "primary_file_endpoint": &schema.Schema{
// Type: schema.TypeString,
// Computed: true,
// },
//
// "primary_access_key": &schema.Schema{
// Type: schema.TypeString,
// Computed: true,
// },
//
// "secondary_access_key": &schema.Schema{
// Type: schema.TypeString,
// Computed: true,
// },
//
// "tags": tagsSchema(),
// },
// }
//}
//
//func resourceArmStorageAccountCreate(d *schema.ResourceData, meta interface{}) error {
// client := meta.(*ArmClient).storageServiceClient
//
// resourceGroupName := d.Get("resource_group_name").(string)
// storageAccountName := d.Get("name").(string)
// accountType := d.Get("account_type").(string)
// location := d.Get("location").(string)
// tags := d.Get("tags").(map[string]interface{})
//
// opts := storage.AccountCreateParameters{
// Location: &location,
// Properties: &storage.AccountPropertiesCreateParameters{
// AccountType: storage.AccountType(accountType),
// },
// Tags: expandTags(tags),
// }
//
// accResp, err := client.Create(resourceGroupName, storageAccountName, opts)
// if err != nil {
// return fmt.Errorf("Error creating Azure Storage Account '%s': %s", storageAccountName, err)
// }
// _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK)
// if err != nil {
// 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
// account, err := client.GetProperties(resourceGroupName, storageAccountName)
// if err != nil {
// return fmt.Errorf("Error retrieving Azure Storage Account %q: %s", storageAccountName, err)
// }
//
// d.SetId(*account.ID)
//
// return resourceArmStorageAccountRead(d, meta)
//}
//
//// 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
//// available requires a call to Update per parameter...
//func resourceArmStorageAccountUpdate(d *schema.ResourceData, meta interface{}) error {
// client := meta.(*ArmClient).storageServiceClient
// id, err := parseAzureResourceID(d.Id())
// if err != nil {
// return err
// }
// storageAccountName := id.Path["storageAccounts"]
// resourceGroupName := id.ResourceGroup
//
// d.Partial(true)
//
// if d.HasChange("account_type") {
// accountType := d.Get("account_type").(string)
//
// opts := storage.AccountUpdateParameters{
// Properties: &storage.AccountPropertiesUpdateParameters{
// AccountType: storage.AccountType(accountType),
// },
// }
// accResp, err := client.Update(resourceGroupName, storageAccountName, opts)
// if err != nil {
// return fmt.Errorf("Error updating Azure Storage Account type %q: %s", storageAccountName, err)
// }
// _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK)
// if err != nil {
// return fmt.Errorf("Error updating Azure Storage Account type %q: %s", storageAccountName, err)
// }
//
// d.SetPartial("account_type")
// }
//
// if d.HasChange("tags") {
// tags := d.Get("tags").(map[string]interface{})
//
// opts := storage.AccountUpdateParameters{
// Tags: expandTags(tags),
// }
// accResp, err := client.Update(resourceGroupName, storageAccountName, opts)
// if err != nil {
// return fmt.Errorf("Error updating Azure Storage Account tags %q: %s", storageAccountName, err)
// }
// _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK)
// if err != nil {
// return fmt.Errorf("Error updating Azure Storage Account tags %q: %s", storageAccountName, err)
// }
//
// d.SetPartial("tags")
// }
//
// d.Partial(false)
// return nil
//}
//
//func resourceArmStorageAccountRead(d *schema.ResourceData, meta interface{}) error {
// client := meta.(*ArmClient).storageServiceClient
//
// id, err := parseAzureResourceID(d.Id())
// if err != nil {
// return err
// }
// name := id.Path["storageAccounts"]
// resGroup := id.ResourceGroup
//
// resp, err := client.GetProperties(resGroup, name)
// if err != nil {
// if resp.StatusCode == http.StatusNotFound {
// d.SetId("")
// return nil
// }
//
// return fmt.Errorf("Error reading the state of AzureRM Storage Account %q: %s", name, err)
// }
//
// keys, err := client.ListKeys(resGroup, name)
// if err != nil {
// return err
// }
//
// d.Set("primary_access_key", keys.Key1)
// d.Set("secondary_access_key", keys.Key2)
// d.Set("location", resp.Location)
// d.Set("account_type", resp.Properties.AccountType)
// d.Set("primary_location", resp.Properties.PrimaryLocation)
// d.Set("secondary_location", resp.Properties.SecondaryLocation)
//
// if resp.Properties.PrimaryEndpoints != nil {
// d.Set("primary_blob_endpoint", resp.Properties.PrimaryEndpoints.Blob)
// d.Set("primary_queue_endpoint", resp.Properties.PrimaryEndpoints.Queue)
// d.Set("primary_table_endpoint", resp.Properties.PrimaryEndpoints.Table)
// d.Set("primary_file_endpoint", resp.Properties.PrimaryEndpoints.File)
// }
//
// if resp.Properties.SecondaryEndpoints != nil {
// if resp.Properties.SecondaryEndpoints.Blob != nil {
// d.Set("secondary_blob_endpoint", resp.Properties.SecondaryEndpoints.Blob)
// } else {
// d.Set("secondary_blob_endpoint", "")
// }
// if resp.Properties.SecondaryEndpoints.Queue != nil {
// d.Set("secondary_queue_endpoint", resp.Properties.SecondaryEndpoints.Queue)
// } else {
// d.Set("secondary_queue_endpoint", "")
// }
// if resp.Properties.SecondaryEndpoints.Table != nil {
// d.Set("secondary_table_endpoint", resp.Properties.SecondaryEndpoints.Table)
// } else {
// d.Set("secondary_table_endpoint", "")
// }
// }
//
// flattenAndSetTags(d, resp.Tags)
//
// return nil
//}
//
//func resourceArmStorageAccountDelete(d *schema.ResourceData, meta interface{}) error {
// client := meta.(*ArmClient).storageServiceClient
//
// id, err := parseAzureResourceID(d.Id())
// if err != nil {
// return err
// }
// name := id.Path["storageAccounts"]
// resGroup := id.ResourceGroup
//
// accResp, err := client.Delete(resGroup, name)
// if err != nil {
// return fmt.Errorf("Error issuing AzureRM delete request for storage account %q: %s", name, err)
// }
// _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response, http.StatusNotFound)
// if err != nil {
// return fmt.Errorf("Error polling for AzureRM delete request for storage account %q: %s", name, err)
// }
//
// return nil
//}
//
//func validateArmStorageAccountName(v interface{}, k string) (ws []string, es []error) {
// input := v.(string)
//
// 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"))
// }
//
// return
//}
//
//func validateArmStorageAccountType(v interface{}, k string) (ws []string, es []error) {
// validAccountTypes := []string{"standard_lrs", "standard_zrs",
// "standard_grs", "standard_ragrs", "premium_lrs"}
//
// input := strings.ToLower(v.(string))
//
// for _, valid := range validAccountTypes {
// if valid == input {
// return
// }
// }
//
// es = append(es, fmt.Errorf("Invalid storage account type %q", input))
// return
//}

View File

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

View File

@ -16,12 +16,12 @@ func resourceArmStorageBlob() *schema.Resource {
Delete: resourceArmStorageBlobDelete,
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"resource_group_name": &schema.Schema{
"resource_group_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
@ -31,25 +31,25 @@ func resourceArmStorageBlob() *schema.Resource {
Required: true,
ForceNew: true,
},
"storage_container_name": &schema.Schema{
"storage_container_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"type": &schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateArmStorageBlobType,
},
"size": &schema.Schema{
"size": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Default: 0,
ValidateFunc: validateArmStorageBlobSize,
},
"url": &schema.Schema{
"url": {
Type: schema.TypeString,
Computed: true,
},
@ -204,7 +204,7 @@ func resourceArmStorageBlobDelete(d *schema.ResourceData, meta interface{}) erro
storageContainerName := d.Get("storage_container_name").(string)
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)
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,251 +1,251 @@
package azurerm
import (
"fmt"
"net/http"
"testing"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccAzureRMTemplateDeployment_basic(t *testing.T) {
ri := acctest.RandInt()
config := fmt.Sprintf(testAccAzureRMTemplateDeployment_basicExample, ri, ri)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testCheckAzureRMTemplateDeploymentDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: config,
Check: resource.ComposeTestCheckFunc(
testCheckAzureRMTemplateDeploymentExists("azurerm_template_deployment.test"),
),
},
},
})
}
func TestAccAzureRMTemplateDeployment_withParams(t *testing.T) {
ri := acctest.RandInt()
config := fmt.Sprintf(testAccAzureRMTemplateDeployment_withParams, ri, ri, ri)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testCheckAzureRMTemplateDeploymentDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: config,
Check: resource.ComposeTestCheckFunc(
testCheckAzureRMTemplateDeploymentExists("azurerm_template_deployment.test"),
resource.TestCheckResourceAttr("azurerm_template_deployment.test", "outputs.testOutput", "Output Value"),
),
},
},
})
}
func testCheckAzureRMTemplateDeploymentExists(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 {
return fmt.Errorf("Not found: %s", name)
}
name := rs.Primary.Attributes["name"]
resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
if !hasResourceGroup {
return fmt.Errorf("Bad: no resource group found in state for template deployment: %s", name)
}
conn := testAccProvider.Meta().(*ArmClient).deploymentsClient
resp, err := conn.Get(resourceGroup, name)
if err != nil {
return fmt.Errorf("Bad: Get on deploymentsClient: %s", err)
}
if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("Bad: TemplateDeployment %q (resource group: %q) does not exist", name, resourceGroup)
}
return nil
}
}
func testCheckAzureRMTemplateDeploymentDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*ArmClient).vmClient
for _, rs := range s.RootModule().Resources {
if rs.Type != "azurerm_template_deployment" {
continue
}
name := rs.Primary.Attributes["name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"]
resp, err := conn.Get(resourceGroup, name, "")
if err != nil {
return nil
}
if resp.StatusCode != http.StatusNotFound {
return fmt.Errorf("Template Deployment still exists:\n%#v", resp.Properties)
}
}
return nil
}
var testAccAzureRMTemplateDeployment_basicExample = `
resource "azurerm_resource_group" "test" {
name = "acctestrg-%d"
location = "West US"
}
resource "azurerm_template_deployment" "test" {
name = "acctesttemplate-%d"
resource_group_name = "${azurerm_resource_group.test.name}"
template_body = <<DEPLOY
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"storageAccountType": {
"type": "string",
"defaultValue": "Standard_LRS",
"allowedValues": [
"Standard_LRS",
"Standard_GRS",
"Standard_ZRS"
],
"metadata": {
"description": "Storage Account type"
}
}
},
"variables": {
"location": "[resourceGroup().location]",
"storageAccountName": "[concat(uniquestring(resourceGroup().id), 'storage')]",
"publicIPAddressName": "[concat('myPublicIp', uniquestring(resourceGroup().id))]",
"publicIPAddressType": "Dynamic",
"apiVersion": "2015-06-15",
"dnsLabelPrefix": "terraform-acctest"
},
"resources": [
{
"type": "Microsoft.Storage/storageAccounts",
"name": "[variables('storageAccountName')]",
"apiVersion": "[variables('apiVersion')]",
"location": "[variables('location')]",
"properties": {
"accountType": "[parameters('storageAccountType')]"
}
},
{
"type": "Microsoft.Network/publicIPAddresses",
"apiVersion": "[variables('apiVersion')]",
"name": "[variables('publicIPAddressName')]",
"location": "[variables('location')]",
"properties": {
"publicIPAllocationMethod": "[variables('publicIPAddressType')]",
"dnsSettings": {
"domainNameLabel": "[variables('dnsLabelPrefix')]"
}
}
}
]
}
DEPLOY
deployment_mode = "Complete"
}
`
var testAccAzureRMTemplateDeployment_withParams = `
resource "azurerm_resource_group" "test" {
name = "acctestrg-%d"
location = "West US"
}
output "test" {
value = "${azurerm_template_deployment.test.outputs.testOutput}"
}
resource "azurerm_template_deployment" "test" {
name = "acctesttemplate-%d"
resource_group_name = "${azurerm_resource_group.test.name}"
template_body = <<DEPLOY
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"storageAccountType": {
"type": "string",
"defaultValue": "Standard_LRS",
"allowedValues": [
"Standard_LRS",
"Standard_GRS",
"Standard_ZRS"
],
"metadata": {
"description": "Storage Account type"
}
},
"dnsLabelPrefix": {
"type": "string",
"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."
}
}
},
"variables": {
"location": "[resourceGroup().location]",
"storageAccountName": "[concat(uniquestring(resourceGroup().id), 'storage')]",
"publicIPAddressName": "[concat('myPublicIp', uniquestring(resourceGroup().id))]",
"publicIPAddressType": "Dynamic",
"apiVersion": "2015-06-15"
},
"resources": [
{
"type": "Microsoft.Storage/storageAccounts",
"name": "[variables('storageAccountName')]",
"apiVersion": "[variables('apiVersion')]",
"location": "[variables('location')]",
"properties": {
"accountType": "[parameters('storageAccountType')]"
}
},
{
"type": "Microsoft.Network/publicIPAddresses",
"apiVersion": "[variables('apiVersion')]",
"name": "[variables('publicIPAddressName')]",
"location": "[variables('location')]",
"properties": {
"publicIPAllocationMethod": "[variables('publicIPAddressType')]",
"dnsSettings": {
"domainNameLabel": "[parameters('dnsLabelPrefix')]"
}
}
}
],
"outputs": {
"testOutput": {
"type": "string",
"value": "Output Value"
}
}
}
DEPLOY
parameters {
dnsLabelPrefix = "terraform-test-%d"
storageAccountType = "Standard_GRS"
}
deployment_mode = "Complete"
}
`
//import (
// "fmt"
// "net/http"
// "testing"
//
// "github.com/hashicorp/terraform/helper/acctest"
// "github.com/hashicorp/terraform/helper/resource"
// "github.com/hashicorp/terraform/terraform"
//)
//
//func TestAccAzureRMTemplateDeployment_basic(t *testing.T) {
// ri := acctest.RandInt()
// config := fmt.Sprintf(testAccAzureRMTemplateDeployment_basicExample, ri, ri)
// resource.Test(t, resource.TestCase{
// PreCheck: func() { testAccPreCheck(t) },
// Providers: testAccProviders,
// CheckDestroy: testCheckAzureRMTemplateDeploymentDestroy,
// Steps: []resource.TestStep{
// resource.TestStep{
// Config: config,
// Check: resource.ComposeTestCheckFunc(
// testCheckAzureRMTemplateDeploymentExists("azurerm_template_deployment.test"),
// ),
// },
// },
// })
//}
//
//func TestAccAzureRMTemplateDeployment_withParams(t *testing.T) {
// ri := acctest.RandInt()
// config := fmt.Sprintf(testAccAzureRMTemplateDeployment_withParams, ri, ri, ri)
// resource.Test(t, resource.TestCase{
// PreCheck: func() { testAccPreCheck(t) },
// Providers: testAccProviders,
// CheckDestroy: testCheckAzureRMTemplateDeploymentDestroy,
// Steps: []resource.TestStep{
// resource.TestStep{
// Config: config,
// Check: resource.ComposeTestCheckFunc(
// testCheckAzureRMTemplateDeploymentExists("azurerm_template_deployment.test"),
// resource.TestCheckResourceAttr("azurerm_template_deployment.test", "outputs.testOutput", "Output Value"),
// ),
// },
// },
// })
//}
//
//func testCheckAzureRMTemplateDeploymentExists(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 {
// return fmt.Errorf("Not found: %s", name)
// }
//
// name := rs.Primary.Attributes["name"]
// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"]
// if !hasResourceGroup {
// return fmt.Errorf("Bad: no resource group found in state for template deployment: %s", name)
// }
//
// conn := testAccProvider.Meta().(*ArmClient).deploymentsClient
//
// resp, err := conn.Get(resourceGroup, name)
// if err != nil {
// return fmt.Errorf("Bad: Get on deploymentsClient: %s", err)
// }
//
// if resp.StatusCode == http.StatusNotFound {
// return fmt.Errorf("Bad: TemplateDeployment %q (resource group: %q) does not exist", name, resourceGroup)
// }
//
// return nil
// }
//}
//
//func testCheckAzureRMTemplateDeploymentDestroy(s *terraform.State) error {
// conn := testAccProvider.Meta().(*ArmClient).vmClient
//
// for _, rs := range s.RootModule().Resources {
// if rs.Type != "azurerm_template_deployment" {
// continue
// }
//
// name := rs.Primary.Attributes["name"]
// resourceGroup := rs.Primary.Attributes["resource_group_name"]
//
// resp, err := conn.Get(resourceGroup, name, "")
//
// if err != nil {
// return nil
// }
//
// if resp.StatusCode != http.StatusNotFound {
// return fmt.Errorf("Template Deployment still exists:\n%#v", resp.Properties)
// }
// }
//
// return nil
//}
//
//var testAccAzureRMTemplateDeployment_basicExample = `
// resource "azurerm_resource_group" "test" {
// name = "acctestrg-%d"
// location = "West US"
// }
//
// resource "azurerm_template_deployment" "test" {
// name = "acctesttemplate-%d"
// resource_group_name = "${azurerm_resource_group.test.name}"
// template_body = <<DEPLOY
//{
// "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
// "contentVersion": "1.0.0.0",
// "parameters": {
// "storageAccountType": {
// "type": "string",
// "defaultValue": "Standard_LRS",
// "allowedValues": [
// "Standard_LRS",
// "Standard_GRS",
// "Standard_ZRS"
// ],
// "metadata": {
// "description": "Storage Account type"
// }
// }
// },
// "variables": {
// "location": "[resourceGroup().location]",
// "storageAccountName": "[concat(uniquestring(resourceGroup().id), 'storage')]",
// "publicIPAddressName": "[concat('myPublicIp', uniquestring(resourceGroup().id))]",
// "publicIPAddressType": "Dynamic",
// "apiVersion": "2015-06-15",
// "dnsLabelPrefix": "terraform-acctest"
// },
// "resources": [
// {
// "type": "Microsoft.Storage/storageAccounts",
// "name": "[variables('storageAccountName')]",
// "apiVersion": "[variables('apiVersion')]",
// "location": "[variables('location')]",
// "properties": {
// "accountType": "[parameters('storageAccountType')]"
// }
// },
// {
// "type": "Microsoft.Network/publicIPAddresses",
// "apiVersion": "[variables('apiVersion')]",
// "name": "[variables('publicIPAddressName')]",
// "location": "[variables('location')]",
// "properties": {
// "publicIPAllocationMethod": "[variables('publicIPAddressType')]",
// "dnsSettings": {
// "domainNameLabel": "[variables('dnsLabelPrefix')]"
// }
// }
// }
// ]
//}
//DEPLOY
// deployment_mode = "Complete"
// }
//
//`
//
//var testAccAzureRMTemplateDeployment_withParams = `
// resource "azurerm_resource_group" "test" {
// name = "acctestrg-%d"
// location = "West US"
// }
//
// output "test" {
// value = "${azurerm_template_deployment.test.outputs.testOutput}"
// }
//
// resource "azurerm_template_deployment" "test" {
// name = "acctesttemplate-%d"
// resource_group_name = "${azurerm_resource_group.test.name}"
// template_body = <<DEPLOY
//{
// "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
// "contentVersion": "1.0.0.0",
// "parameters": {
// "storageAccountType": {
// "type": "string",
// "defaultValue": "Standard_LRS",
// "allowedValues": [
// "Standard_LRS",
// "Standard_GRS",
// "Standard_ZRS"
// ],
// "metadata": {
// "description": "Storage Account type"
// }
// },
// "dnsLabelPrefix": {
// "type": "string",
// "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."
// }
// }
// },
// "variables": {
// "location": "[resourceGroup().location]",
// "storageAccountName": "[concat(uniquestring(resourceGroup().id), 'storage')]",
// "publicIPAddressName": "[concat('myPublicIp', uniquestring(resourceGroup().id))]",
// "publicIPAddressType": "Dynamic",
// "apiVersion": "2015-06-15"
// },
// "resources": [
// {
// "type": "Microsoft.Storage/storageAccounts",
// "name": "[variables('storageAccountName')]",
// "apiVersion": "[variables('apiVersion')]",
// "location": "[variables('location')]",
// "properties": {
// "accountType": "[parameters('storageAccountType')]"
// }
// },
// {
// "type": "Microsoft.Network/publicIPAddresses",
// "apiVersion": "[variables('apiVersion')]",
// "name": "[variables('publicIPAddressName')]",
// "location": "[variables('location')]",
// "properties": {
// "publicIPAllocationMethod": "[variables('publicIPAddressType')]",
// "dnsSettings": {
// "domainNameLabel": "[parameters('dnsLabelPrefix')]"
// }
// }
// }
// ],
// "outputs": {
// "testOutput": {
// "type": "string",
// "value": "Output Value"
// }
// }
//}
//DEPLOY
// parameters {
// dnsLabelPrefix = "terraform-test-%d"
// storageAccountType = "Standard_GRS"
// }
// 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
import (
"fmt"
"log"
"net/http"
"time"
"github.com/Azure/azure-sdk-for-go/arm/network"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceArmVirtualNetwork() *schema.Resource {
return &schema.Resource{
Create: resourceArmVirtualNetworkCreate,
Read: resourceArmVirtualNetworkRead,
Update: resourceArmVirtualNetworkCreate,
Delete: resourceArmVirtualNetworkDelete,
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"address_space": &schema.Schema{
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"dns_servers": &schema.Schema{
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"subnet": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"address_prefix": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"security_group": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
},
},
Set: resourceAzureSubnetHash,
},
"location": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
StateFunc: azureRMNormalizeLocation,
},
"resource_group_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"tags": tagsSchema(),
},
}
}
func resourceArmVirtualNetworkCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient)
vnetClient := client.vnetClient
log.Printf("[INFO] preparing arguments for Azure ARM virtual network creation.")
name := d.Get("name").(string)
location := d.Get("location").(string)
resGroup := d.Get("resource_group_name").(string)
tags := d.Get("tags").(map[string]interface{})
vnet := network.VirtualNetwork{
Name: &name,
Location: &location,
Properties: getVirtualNetworkProperties(d),
Tags: expandTags(tags),
}
resp, err := vnetClient.CreateOrUpdate(resGroup, name, vnet)
if err != nil {
return err
}
d.SetId(*resp.ID)
log.Printf("[DEBUG] Waiting for Virtual Network (%s) to become available", name)
stateConf := &resource.StateChangeConf{
Pending: []string{"Accepted", "Updating"},
Target: []string{"Succeeded"},
Refresh: virtualNetworkStateRefreshFunc(client, resGroup, name),
Timeout: 10 * time.Minute,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Virtual Network (%s) to become available: %s", name, err)
}
return resourceArmVirtualNetworkRead(d, meta)
}
func resourceArmVirtualNetworkRead(d *schema.ResourceData, meta interface{}) error {
vnetClient := meta.(*ArmClient).vnetClient
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resGroup := id.ResourceGroup
name := id.Path["virtualNetworks"]
resp, err := vnetClient.Get(resGroup, name, "")
if resp.StatusCode == http.StatusNotFound {
d.SetId("")
return nil
}
if err != nil {
return fmt.Errorf("Error making Read request on Azure virtual network %s: %s", name, err)
}
vnet := *resp.Properties
// update appropriate values
d.Set("address_space", vnet.AddressSpace.AddressPrefixes)
subnets := &schema.Set{
F: resourceAzureSubnetHash,
}
for _, subnet := range *vnet.Subnets {
s := map[string]interface{}{}
s["name"] = *subnet.Name
s["address_prefix"] = *subnet.Properties.AddressPrefix
if subnet.Properties.NetworkSecurityGroup != nil {
s["security_group"] = *subnet.Properties.NetworkSecurityGroup.ID
}
subnets.Add(s)
}
d.Set("subnet", subnets)
dnses := []string{}
for _, dns := range *vnet.DhcpOptions.DNSServers {
dnses = append(dnses, dns)
}
d.Set("dns_servers", dnses)
flattenAndSetTags(d, resp.Tags)
return nil
}
func resourceArmVirtualNetworkDelete(d *schema.ResourceData, meta interface{}) error {
vnetClient := meta.(*ArmClient).vnetClient
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resGroup := id.ResourceGroup
name := id.Path["virtualNetworks"]
_, err = vnetClient.Delete(resGroup, name)
return err
}
func getVirtualNetworkProperties(d *schema.ResourceData) *network.VirtualNetworkPropertiesFormat {
// first; get address space prefixes:
prefixes := []string{}
for _, prefix := range d.Get("address_space").([]interface{}) {
prefixes = append(prefixes, prefix.(string))
}
// then; the dns servers:
dnses := []string{}
for _, dns := range d.Get("dns_servers").([]interface{}) {
dnses = append(dnses, dns.(string))
}
// then; the subnets:
subnets := []network.Subnet{}
if subs := d.Get("subnet").(*schema.Set); subs.Len() > 0 {
for _, subnet := range subs.List() {
subnet := subnet.(map[string]interface{})
name := subnet["name"].(string)
prefix := subnet["address_prefix"].(string)
secGroup := subnet["security_group"].(string)
var subnetObj network.Subnet
subnetObj.Name = &name
subnetObj.Properties = &network.SubnetPropertiesFormat{}
subnetObj.Properties.AddressPrefix = &prefix
if secGroup != "" {
subnetObj.Properties.NetworkSecurityGroup = &network.SecurityGroup{
ID: &secGroup,
}
}
subnets = append(subnets, subnetObj)
}
}
// finally; return the struct:
return &network.VirtualNetworkPropertiesFormat{
AddressSpace: &network.AddressSpace{
AddressPrefixes: &prefixes,
},
DhcpOptions: &network.DhcpOptions{
DNSServers: &dnses,
},
Subnets: &subnets,
}
}
func resourceAzureSubnetHash(v interface{}) int {
m := v.(map[string]interface{})
subnet := m["name"].(string) + m["address_prefix"].(string)
if securityGroup, present := m["security_group"]; present {
subnet = subnet + securityGroup.(string)
}
return hashcode.String(subnet)
}
func virtualNetworkStateRefreshFunc(client *ArmClient, resourceGroupName string, networkName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
res, err := client.vnetClient.Get(resourceGroupName, networkName, "")
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 res, *res.Properties.ProvisioningState, nil
}
}
//import (
// "fmt"
// "log"
// "net/http"
// "time"
//
// "github.com/Azure/azure-sdk-for-go/arm/network"
// "github.com/hashicorp/terraform/helper/hashcode"
// "github.com/hashicorp/terraform/helper/resource"
// "github.com/hashicorp/terraform/helper/schema"
//)
//
//func resourceArmVirtualNetwork() *schema.Resource {
// return &schema.Resource{
// Create: resourceArmVirtualNetworkCreate,
// Read: resourceArmVirtualNetworkRead,
// Update: resourceArmVirtualNetworkCreate,
// Delete: resourceArmVirtualNetworkDelete,
//
// Schema: map[string]*schema.Schema{
// "name": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// ForceNew: true,
// },
//
// "address_space": &schema.Schema{
// Type: schema.TypeList,
// Required: true,
// Elem: &schema.Schema{Type: schema.TypeString},
// },
//
// "dns_servers": &schema.Schema{
// Type: schema.TypeList,
// Optional: true,
// Elem: &schema.Schema{
// Type: schema.TypeString,
// },
// },
//
// "subnet": &schema.Schema{
// Type: schema.TypeSet,
// Optional: true,
// Computed: true,
// Elem: &schema.Resource{
// Schema: map[string]*schema.Schema{
// "name": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// },
// "address_prefix": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// },
// "security_group": &schema.Schema{
// Type: schema.TypeString,
// Optional: true,
// },
// },
// },
// Set: resourceAzureSubnetHash,
// },
//
// "location": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// ForceNew: true,
// StateFunc: azureRMNormalizeLocation,
// },
//
// "resource_group_name": &schema.Schema{
// Type: schema.TypeString,
// Required: true,
// ForceNew: true,
// },
//
// "tags": tagsSchema(),
// },
// }
//}
//
//func resourceArmVirtualNetworkCreate(d *schema.ResourceData, meta interface{}) error {
// client := meta.(*ArmClient)
// vnetClient := client.vnetClient
//
// log.Printf("[INFO] preparing arguments for Azure ARM virtual network creation.")
//
// name := d.Get("name").(string)
// location := d.Get("location").(string)
// resGroup := d.Get("resource_group_name").(string)
// tags := d.Get("tags").(map[string]interface{})
//
// vnet := network.VirtualNetwork{
// Name: &name,
// Location: &location,
// Properties: getVirtualNetworkProperties(d),
// Tags: expandTags(tags),
// }
//
// resp, err := vnetClient.CreateOrUpdate(resGroup, name, vnet)
// if err != nil {
// return err
// }
//
// d.SetId(*resp.ID)
//
// log.Printf("[DEBUG] Waiting for Virtual Network (%s) to become available", name)
// stateConf := &resource.StateChangeConf{
// Pending: []string{"Accepted", "Updating"},
// Target: []string{"Succeeded"},
// Refresh: virtualNetworkStateRefreshFunc(client, resGroup, name),
// Timeout: 10 * time.Minute,
// }
// if _, err := stateConf.WaitForState(); err != nil {
// return fmt.Errorf("Error waiting for Virtual Network (%s) to become available: %s", name, err)
// }
//
// return resourceArmVirtualNetworkRead(d, meta)
//}
//
//func resourceArmVirtualNetworkRead(d *schema.ResourceData, meta interface{}) error {
// vnetClient := meta.(*ArmClient).vnetClient
//
// id, err := parseAzureResourceID(d.Id())
// if err != nil {
// return err
// }
// resGroup := id.ResourceGroup
// name := id.Path["virtualNetworks"]
//
// resp, err := vnetClient.Get(resGroup, name, "")
// if resp.StatusCode == http.StatusNotFound {
// d.SetId("")
// return nil
// }
// if err != nil {
// return fmt.Errorf("Error making Read request on Azure virtual network %s: %s", name, err)
// }
// vnet := *resp.Properties
//
// // update appropriate values
// d.Set("address_space", vnet.AddressSpace.AddressPrefixes)
//
// subnets := &schema.Set{
// F: resourceAzureSubnetHash,
// }
//
// for _, subnet := range *vnet.Subnets {
// s := map[string]interface{}{}
//
// s["name"] = *subnet.Name
// s["address_prefix"] = *subnet.Properties.AddressPrefix
// if subnet.Properties.NetworkSecurityGroup != nil {
// s["security_group"] = *subnet.Properties.NetworkSecurityGroup.ID
// }
//
// subnets.Add(s)
// }
// d.Set("subnet", subnets)
//
// dnses := []string{}
// for _, dns := range *vnet.DhcpOptions.DNSServers {
// dnses = append(dnses, dns)
// }
// d.Set("dns_servers", dnses)
//
// flattenAndSetTags(d, resp.Tags)
//
// return nil
//}
//
//func resourceArmVirtualNetworkDelete(d *schema.ResourceData, meta interface{}) error {
// vnetClient := meta.(*ArmClient).vnetClient
//
// id, err := parseAzureResourceID(d.Id())
// if err != nil {
// return err
// }
// resGroup := id.ResourceGroup
// name := id.Path["virtualNetworks"]
//
// _, err = vnetClient.Delete(resGroup, name)
//
// return err
//}
//
//func getVirtualNetworkProperties(d *schema.ResourceData) *network.VirtualNetworkPropertiesFormat {
// // first; get address space prefixes:
// prefixes := []string{}
// for _, prefix := range d.Get("address_space").([]interface{}) {
// prefixes = append(prefixes, prefix.(string))
// }
//
// // then; the dns servers:
// dnses := []string{}
// for _, dns := range d.Get("dns_servers").([]interface{}) {
// dnses = append(dnses, dns.(string))
// }
//
// // then; the subnets:
// subnets := []network.Subnet{}
// if subs := d.Get("subnet").(*schema.Set); subs.Len() > 0 {
// for _, subnet := range subs.List() {
// subnet := subnet.(map[string]interface{})
//
// name := subnet["name"].(string)
// prefix := subnet["address_prefix"].(string)
// secGroup := subnet["security_group"].(string)
//
// var subnetObj network.Subnet
// subnetObj.Name = &name
// subnetObj.Properties = &network.SubnetPropertiesFormat{}
// subnetObj.Properties.AddressPrefix = &prefix
//
// if secGroup != "" {
// subnetObj.Properties.NetworkSecurityGroup = &network.SecurityGroup{
// ID: &secGroup,
// }
// }
//
// subnets = append(subnets, subnetObj)
// }
// }
//
// // finally; return the struct:
// return &network.VirtualNetworkPropertiesFormat{
// AddressSpace: &network.AddressSpace{
// AddressPrefixes: &prefixes,
// },
// DhcpOptions: &network.DhcpOptions{
// DNSServers: &dnses,
// },
// Subnets: &subnets,
// }
//}
//
//func resourceAzureSubnetHash(v interface{}) int {
// m := v.(map[string]interface{})
// subnet := m["name"].(string) + m["address_prefix"].(string)
// if securityGroup, present := m["security_group"]; present {
// subnet = subnet + securityGroup.(string)
// }
// return hashcode.String(subnet)
//}
//
//func virtualNetworkStateRefreshFunc(client *ArmClient, resourceGroupName string, networkName string) resource.StateRefreshFunc {
// return func() (interface{}, string, error) {
// res, err := client.vnetClient.Get(resourceGroupName, networkName, "")
// 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 res, *res.Properties.ProvisioningState, nil
// }
//}