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

Support Weighted DNS Records with Data Sources and Tests #8057

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,5 @@ website/vendor
!command/test-fixtures/**/*.tfstate
!command/test-fixtures/**/.terraform/
diff_*.zip
scan.py
scan.py
terraform-provider-alicloud
189 changes: 189 additions & 0 deletions alicloud/data_source_alicloud_alidns_records_weight.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
package alicloud

import (
"log"

"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)

func dataSourceAlicloudAlidnsRecordsWeight() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudAlidnsRecordsWeightRead,
Schema: map[string]*schema.Schema{
"domain_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"line": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "default",
},
"status": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"ENABLE", "DISABLE"}, false),
Default: "ENABLE",
},
"weight_greater_than": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Default: 0,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},
"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"records": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"domain_name": {
Type: schema.TypeString,
Computed: true,
},
"line": {
Type: schema.TypeString,
Computed: true,
},
"rr": {
Type: schema.TypeString,
Computed: true,
},
"record_id": {
Type: schema.TypeString,
Computed: true,
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"ttl": {
Type: schema.TypeInt,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"value": {
Type: schema.TypeString,
Computed: true,
},
"weight": {
Type: schema.TypeInt,
Computed: true,
},
"wrr_status": {
Type: schema.TypeString,
Computed: true,
},
"remark": {
Type: schema.TypeString,
Computed: true,
},
"priority": {
Type: schema.TypeInt,
Computed: true,
},
},
},
},
},
}
}

func dataSourceAlicloudAlidnsRecordsWeightRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)

request := alidns.CreateDescribeDomainRecordsRequest()
request.DomainName = d.Get("domain_name").(string)
request.PageSize = requests.NewInteger(PageSizeLarge)
request.PageNumber = requests.NewInteger(1)

var records []map[string]interface{}
var recordIDs []string // To store unique IDs for hash generation

for {
raw, err := client.WithAlidnsClient(func(client *alidns.Client) (interface{}, error) {
return client.DescribeDomainRecords(request)
})
if err != nil {
return WrapError(err)
}

response := raw.(*alidns.DescribeDomainRecordsResponse)
for _, record := range response.DomainRecords.Record {
wrrStatus, err := fetchWRRStatus(client, record.DomainName, record.RR)
if err != nil {
log.Printf("[DEBUG] Failed to fetch WRR status for record %s: %v", record.RecordId, err)
wrrStatus = "DISABLE"
}

detailedRecord, err := client.WithAlidnsClient(func(client *alidns.Client) (interface{}, error) {
request := alidns.CreateDescribeDomainRecordInfoRequest()
request.RecordId = record.RecordId
return client.DescribeDomainRecordInfo(request)
})

remark := ""
if err == nil {
remark = detailedRecord.(*alidns.DescribeDomainRecordInfoResponse).Remark
} else {
log.Printf("[DEBUG] Failed to fetch remark for record %s: %v", record.RecordId, err)
}

records = append(records, map[string]interface{}{
"domain_name": record.DomainName,
"line": record.Line,
"rr": record.RR,
"record_id": record.RecordId,
"status": record.Status,
"ttl": record.TTL,
"type": record.Type,
"value": record.Value,
"weight": record.Weight,
"remark": remark,
"wrr_status": wrrStatus,
})

recordIDs = append(recordIDs, record.RecordId) // Add the record ID to the list
}

if len(response.DomainRecords.Record) < PageSizeLarge {
break
}

page, err := getNextpageNumber(request.PageNumber)
if err != nil {
return WrapError(err)
}
request.PageNumber = page
}

if err := d.Set("records", records); err != nil {
return WrapError(err)
}

if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), records)
}

// Use the list of record IDs to generate a unique hash
d.SetId(dataResourceIdHash(recordIDs))
return nil
}
118 changes: 118 additions & 0 deletions alicloud/data_source_alicloud_alidns_records_weight_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package alicloud

import (
"fmt"
"testing"

"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
)

func TestAccAlicloudAlidnsRecordsWeightDataSource(t *testing.T) {
rand := acctest.RandInt()
resourceId := "data.alicloud_alidns_records_weight.default"

testAccConfig := dataSourceTestAccConfigFunc(resourceId,
fmt.Sprintf("tf-testacc%salidnsweight%v.abc", defaultRegionToTest, rand),
dataSourceAlidnsRecordsWeightConfigDependence)

testAccCheck := func(expected map[string]string) resource.TestCheckFunc {
return resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(resourceId, "records.#", "1"),
resource.TestCheckResourceAttr(resourceId, "records.0.domain_name", expected["domain_name"]),
resource.TestCheckResourceAttr(resourceId, "records.0.rr", expected["rr"]),
resource.TestCheckResourceAttr(resourceId, "records.0.type", expected["type"]),
resource.TestCheckResourceAttr(resourceId, "records.0.value", expected["value"]),
resource.TestCheckResourceAttr(resourceId, "records.0.ttl", expected["ttl"]),
resource.TestCheckResourceAttr(resourceId, "records.0.weight", expected["weight"]),
resource.TestCheckResourceAttr(resourceId, "records.0.wrr_status", expected["wrr_status"]),
resource.TestCheckResourceAttr(resourceId, "records.0.remark", expected["remark"]),
resource.TestCheckResourceAttr(resourceId, "records.0.priority", expected["priority"]),
)
}

resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
Providers: testAccProviders,
CheckDestroy: testAccCheckAliCloudAlidnsRecordWeightDestroy,
Steps: []resource.TestStep{
{
Config: testAccConfig(map[string]interface{}{
"domain_name": "${alicloud_dns_domain.default.name}",
"rr": "test1",
"type": "A",
"value": "1.1.1.1",
"ttl": "900",
"weight": "60",
"wrr_status": "ENABLE",
"remark": "test new record",
"priority": "5",
}),
Check: testAccCheck(map[string]string{
"domain_name": fmt.Sprintf("tf-testacc%salidnsweight%v.abc", defaultRegionToTest, rand),
"rr": "test1",
"type": "A",
"value": "1.1.1.1",
"ttl": "900",
"weight": "60",
"wrr_status": "ENABLE",
"remark": "test new record",
"priority": "5",
}),
},
},
})
}

func dataSourceAlidnsRecordsWeightConfigDependence(name string) string {
return fmt.Sprintf(`
resource "alicloud_dns_domain" "default" {
domain_name = "%s"
}

resource "alicloud_alidns_record_weight" "default" {
domain_name = "${alicloud_dns_domain.default.domain_name}"
rr = "test1"
type = "A"
value = "1.1.1.1"
ttl = 900
weight = 60
wrr_status = "ENABLE"
remark = "test new record"
priority = 5
}
`, name)
}

func testAccCheckAliCloudAlidnsRecordWeightDestroy(s *terraform.State) error {
client := testAccProvider.Meta().(*connectivity.AliyunClient)
for _, rs := range s.RootModule().Resources {
if rs.Type != "alicloud_alidns_record_weight" {
continue
}

// Check if the record still exists
request := alidns.CreateDescribeDomainRecordInfoRequest()
request.RecordId = rs.Primary.ID

_, err := client.WithAlidnsClient(func(alidnsClient *alidns.Client) (interface{}, error) {
return alidnsClient.DescribeDomainRecordInfo(request)
})

if err == nil {
return fmt.Errorf("record weight %s still exists", rs.Primary.ID)
}

// If error is not related to a missing record, return it
if !IsExpectedErrors(err, []string{"InvalidRecordId.NotFound"}) {
return err
}
}

return nil
}
2 changes: 2 additions & 0 deletions alicloud/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,7 @@ func Provider() terraform.ResourceProvider {
"alicloud_alidns_domain_groups": dataSourceAlicloudAlidnsDomainGroups(),
"alicloud_kms_key_versions": dataSourceAlicloudKmsKeyVersions(),
"alicloud_alidns_records": dataSourceAlicloudAlidnsRecords(),
"alicloud_alidns_records_weight": dataSourceAlicloudAlidnsRecordsWeight(),
"alicloud_resource_manager_accounts": dataSourceAlicloudResourceManagerAccounts(),
"alicloud_resource_manager_resource_directories": dataSourceAlicloudResourceManagerResourceDirectories(),
"alicloud_resource_manager_handshakes": dataSourceAlicloudResourceManagerHandshakes(),
Expand Down Expand Up @@ -1140,6 +1141,7 @@ func Provider() terraform.ResourceProvider {
"alicloud_alikafka_sasl_user": resourceAliCloudAlikafkaSaslUser(),
"alicloud_alikafka_sasl_acl": resourceAlicloudAlikafkaSaslAcl(),
"alicloud_dns_record": resourceAlicloudDnsRecord(),
"alicloud_alidns_record_weight": resourceAlicloudAlidnsRecordWeight(),
"alicloud_dns": resourceAlicloudDns(),
"alicloud_dns_group": resourceAlicloudDnsGroup(),
"alicloud_key_pair": resourceAliCloudEcsKeyPair(),
Expand Down
Loading