Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

New resource 'azurerm_private_dns_mx_record' #4915

Merged
merged 3 commits into from
Nov 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,7 @@ func Provider() terraform.ResourceProvider {
"azurerm_private_dns_a_record": resourceArmPrivateDnsARecord(),
"azurerm_private_dns_aaaa_record": resourceArmPrivateDnsAaaaRecord(),
"azurerm_private_dns_cname_record": resourceArmPrivateDnsCNameRecord(),
"azurerm_private_dns_mx_record": resourceArmPrivateDnsMxRecord(),
"azurerm_private_dns_ptr_record": resourceArmPrivateDnsPtrRecord(),
"azurerm_private_dns_srv_record": resourceArmPrivateDnsSrvRecord(),
"azurerm_private_dns_zone_virtual_network_link": resourceArmPrivateDnsZoneVirtualNetworkLink(),
Expand Down
237 changes: 237 additions & 0 deletions azurerm/resource_arm_private_dns_mx_record.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
package azurerm

import (
"fmt"
"time"

"github.com/Azure/azure-sdk-for-go/services/privatedns/mgmt/2018-09-01/privatedns"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tags"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func resourceArmPrivateDnsMxRecord() *schema.Resource {
return &schema.Resource{
Create: resourceArmPrivateDnsMxRecordCreateUpdate,
Read: resourceArmPrivateDnsMxRecordRead,
Update: resourceArmPrivateDnsMxRecordCreateUpdate,
Delete: resourceArmPrivateDnsMxRecordDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Read: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(30 * time.Minute),
},

Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
ForceNew: true,
// name is optional and defaults to root zone (@) if not set
Optional: true,
Default: "@",
// lower-cased due to the broken API https://github.com/Azure/azure-rest-api-specs/issues/6641
ValidateFunc: validate.LowerCasedString,
},

// TODO: make this case sensitive once the API's fixed https://github.com/Azure/azure-rest-api-specs/issues/6641
"resource_group_name": azure.SchemaResourceGroupNameDiffSuppress(),

"zone_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.NoEmptyStrings,
},

"record": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"preference": {
Type: schema.TypeInt,
Required: true,
// 16 bit uint (rfc 974)
ValidateFunc: validation.IntBetween(0, 65535),
},
"exchange": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validate.NoEmptyStrings,
},
},
},
},

"ttl": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(1, 2147483647),
},

"tags": tags.Schema(),
},
}
}

func resourceArmPrivateDnsMxRecordCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).PrivateDns.RecordSetsClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*ArmClient).StopContext, d)
defer cancel()

name := d.Get("name").(string)
resGroup := d.Get("resource_group_name").(string)
zoneName := d.Get("zone_name").(string)

if features.ShouldResourcesBeImported() && d.IsNewResource() {
existing, err := client.Get(ctx, resGroup, zoneName, privatedns.MX, name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("Error checking for presence of existing Private DNS MX Record %q (Zone %q / Resource Group %q): %s", name, zoneName, resGroup, err)
}
}

if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_private_dns_mx_record", *existing.ID)
}
}

ttl := int64(d.Get("ttl").(int))
t := d.Get("tags").(map[string]interface{})

parameters := privatedns.RecordSet{
Name: &name,
RecordSetProperties: &privatedns.RecordSetProperties{
Metadata: tags.Expand(t),
TTL: &ttl,
MxRecords: expandAzureRmPrivateDnsMxRecords(d),
},
}

if _, err := client.CreateOrUpdate(ctx, resGroup, zoneName, privatedns.MX, name, parameters, "", ""); err != nil {
return fmt.Errorf("Error creating/updating Private DNS MX Record %q (Zone %q / Resource Group %q): %s", name, zoneName, resGroup, err)
}

resp, err := client.Get(ctx, resGroup, zoneName, privatedns.MX, name)
if err != nil {
return fmt.Errorf("Error retrieving Private DNS MX Record %q (Zone %q / Resource Group %q): %s", name, zoneName, resGroup, err)
}

if resp.ID == nil {
return fmt.Errorf("Cannot read Private DNS MX Record %s (resource group %s) ID", name, resGroup)
}

d.SetId(*resp.ID)

return resourceArmPrivateDnsMxRecordRead(d, meta)
}

func resourceArmPrivateDnsMxRecordRead(d *schema.ResourceData, meta interface{}) error {
dnsClient := meta.(*ArmClient).PrivateDns.RecordSetsClient
ctx, cancel := timeouts.ForRead(meta.(*ArmClient).StopContext, d)
defer cancel()

id, err := azure.ParseAzureResourceID(d.Id())
if err != nil {
return err
}

resGroup := id.ResourceGroup
name := id.Path["MX"]
zoneName := id.Path["privateDnsZones"]

resp, err := dnsClient.Get(ctx, resGroup, zoneName, privatedns.MX, name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
d.SetId("")
return nil
}
return fmt.Errorf("Error reading Private DNS MX record %s: %+v", name, err)
}

d.Set("name", name)
d.Set("resource_group_name", resGroup)
d.Set("zone_name", zoneName)
d.Set("ttl", resp.TTL)

if err := d.Set("record", flattenAzureRmPrivateDnsMxRecords(resp.MxRecords)); err != nil {
return err
}

return tags.FlattenAndSet(d, resp.Metadata)
}

func resourceArmPrivateDnsMxRecordDelete(d *schema.ResourceData, meta interface{}) error {
dnsClient := meta.(*ArmClient).PrivateDns.RecordSetsClient
ctx, cancel := timeouts.ForDelete(meta.(*ArmClient).StopContext, d)
defer cancel()

id, err := azure.ParseAzureResourceID(d.Id())
if err != nil {
return err
}

resGroup := id.ResourceGroup
name := id.Path["MX"]
zoneName := id.Path["privateDnsZones"]

if _, err = dnsClient.Delete(ctx, resGroup, zoneName, privatedns.MX, name, ""); err != nil {
return fmt.Errorf("Error deleting Private DNS MX Record %s: %+v", name, err)
}

return nil
}

func flattenAzureRmPrivateDnsMxRecords(records *[]privatedns.MxRecord) []map[string]interface{} {
results := make([]map[string]interface{}, 0)

if records != nil {
for _, record := range *records {
if record.Preference == nil ||
record.Exchange == nil {
continue
}

results = append(results, map[string]interface{}{
"preference": *record.Preference,
"exchange": *record.Exchange,
katbyte marked this conversation as resolved.
Show resolved Hide resolved
})
}
}

return results
}

func expandAzureRmPrivateDnsMxRecords(d *schema.ResourceData) *[]privatedns.MxRecord {
recordStrings := d.Get("record").(*schema.Set).List()
records := make([]privatedns.MxRecord, len(recordStrings))

for i, v := range recordStrings {
if v == nil {
continue
}
record := v.(map[string]interface{})
phires marked this conversation as resolved.
Show resolved Hide resolved
preference := int32(record["preference"].(int))
exchange := record["exchange"].(string)

mxRecord := privatedns.MxRecord{
Preference: &preference,
Exchange: &exchange,
}

records[i] = mxRecord
}

return &records
}
Loading