Skip to content

Instantly share code, notes, and snippets.

@niski84
Created May 13, 2024 21:24
Show Gist options
  • Save niski84/4931743153a629c9faafcbf6007d3ca0 to your computer and use it in GitHub Desktop.
Save niski84/4931743153a629c9faafcbf6007d3ca0 to your computer and use it in GitHub Desktop.
modifyRecordAlias updates the AliasTarget of a specific DNS record in Route53.
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/route53"
)
// modifyRecordAlias updates the AliasTarget of a specific DNS record in Route53.
func modifyRecordAlias(svc *route53.Route53, hostedZoneID, recordName, newTargetAlias string) error {
fmt.Printf("Modifying AliasTarget for record %s in hosted zone %s\n", recordName, hostedZoneID)
// First, find the record to modify
input := &route53.ListResourceRecordSetsInput{
HostedZoneId: aws.String(hostedZoneID),
}
result, err := svc.ListResourceRecordSets(input)
if err != nil {
return wrapError(err, "ListResourceRecordSets")
}
var targetRecord *route53.ResourceRecordSet
for _, recordSet := range result.ResourceRecordSets {
if *recordSet.Name == recordName + "." && recordSet.AliasTarget != nil {
targetRecord = recordSet
break
}
}
if targetRecord == nil {
return fmt.Errorf("record not found or is not an alias")
}
// Update the AliasTarget to point to the new DNS name
targetRecord.AliasTarget.DNSName = aws.String(newTargetAlias)
// Prepare the change batch for the update
changeBatch := &route53.ChangeBatch{
Changes: []*route53.Change{
{
Action: aws.String("UPSERT"),
ResourceRecordSet: targetRecord,
},
},
}
changeInput := &route53.ChangeResourceRecordSetsInput{
HostedZoneId: aws.String(hostedZoneID),
ChangeBatch: changeBatch,
}
_, err = svc.ChangeResourceRecordSets(changeInput)
if err != nil {
return wrapError(err, "ChangeResourceRecordSets")
}
fmt.Printf("Successfully modified AliasTarget for record %s to %s\n", recordName, newTargetAlias)
return nil
}
func TestModifyRecordAlias(t *testing.T) {
// Create a new AWS session (you would normally restrict this to a specific region)
sess := session.Must(session.NewSession(&aws.Config{
Region: aws.String("us-west-2"), // Example region
}))
svc := route53.New(sess)
// Assuming you have valid hostedZoneID, recordName, and newTargetAlias
hostedZoneID := "valid-hosted-zone-id"
recordName := "valid-record-name.example.com"
newTargetAlias := "new-target-alias.example.com"
// Call the function (this will make a real API call, be careful with this)
err := route53manager.ModifyRecordAlias(svc, hostedZoneID, recordName, newTargetAlias)
// Check for errors
if err != nil {
t.Errorf("Expected no error, got %v", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment