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

Add virtual resource association: azurerm_nat_gateway_public_ip #6450

Merged
merged 10 commits into from
May 27, 2020
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
package network

import (
"fmt"
"log"
"time"

"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2020-03-01/network"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"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/internal/clients"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/locks"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/network/parse"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/network/validate"
azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/schema"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func resourceArmNatGatewayPublicIpAssociation() *schema.Resource {
return &schema.Resource{
Create: resourceArmNatGatewayPublicIpAssociationCreate,
Read: resourceArmNatGatewayPublicIpAssociationRead,
Delete: resourceArmNatGatewayPublicIpAssociationDelete,

Importer: azSchema.ValidateResourceIDPriorToImport(func(id string) error {
_, err := parse.NatGatewayID(id)
return err
}),

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

Schema: map[string]*schema.Schema{
"nat_gateway_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.NatGatewayID,
},

"public_ip_address_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: azure.ValidateResourceID,
},
},
}
}

func resourceArmNatGatewayPublicIpAssociationCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Network.NatGatewayClient
ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d)
defer cancel()

log.Printf("[INFO] preparing arguments for Nat Gateway <-> Public Ip Association creation.")
natGatewayId := d.Get("nat_gateway_id").(string)
publicIpAddressId := d.Get("public_ip_address_id").(string)
parsedNatGatewayId, err := parse.NatGatewayID(natGatewayId)
if err != nil {
return err
}

locks.ByName(parsedNatGatewayId.Name, natGatewayResourceName)
defer locks.UnlockByName(parsedNatGatewayId.Name, natGatewayResourceName)

natGateway, err := client.Get(ctx, parsedNatGatewayId.ResourceGroup, parsedNatGatewayId.Name, "")
if err != nil {
if utils.ResponseWasNotFound(natGateway.Response) {
return fmt.Errorf("Nat Gateway %q (Resource Group %q) was not found.", parsedNatGatewayId.Name, parsedNatGatewayId.ResourceGroup)
}
return fmt.Errorf("failed to retrieve Nat Gateway %q (Resource Group %q): %+v", parsedNatGatewayId.Name, parsedNatGatewayId.ResourceGroup, err)
}

publicIpAddresses := make([]network.SubResource, 0)
if natGateway.PublicIPAddresses != nil {
for _, existingPublicIPAddress := range *natGateway.PublicIPAddresses {
if existingPublicIPAddress.ID != nil {
if *existingPublicIPAddress.ID == publicIpAddressId {
return tf.ImportAsExistsError("azurerm_nat_gateway_public_ip_association", *natGateway.ID)
}

publicIpAddresses = append(publicIpAddresses, existingPublicIPAddress)
}
}
}

publicIpAddresses = append(publicIpAddresses, network.SubResource{
ID: utils.String(publicIpAddressId),
})
natGateway.PublicIPAddresses = &publicIpAddresses

future, err := client.CreateOrUpdate(ctx, parsedNatGatewayId.ResourceGroup, parsedNatGatewayId.Name, natGateway)
if err != nil {
return fmt.Errorf("failed to update Public IP Association for Nat Gateway %q (Resource Group %q): %+v", parsedNatGatewayId.Name, parsedNatGatewayId.ResourceGroup, err)
}

if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("failed to wait for completion of Public IP Association for Nat Gateway %q (Resource Group %q): %+v", parsedNatGatewayId.Name, parsedNatGatewayId.ResourceGroup, err)
}

resp, err := client.Get(ctx, parsedNatGatewayId.ResourceGroup, parsedNatGatewayId.Name, "")
if err != nil {
return fmt.Errorf("failed to retrieve Nat Gateway %q (Resource Group %q): %+v", parsedNatGatewayId.Name, parsedNatGatewayId.ResourceGroup, err)
}
d.SetId(*resp.ID)

return resourceArmNatGatewayPublicIpAssociationRead(d, meta)
}

func resourceArmNatGatewayPublicIpAssociationRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Network.NatGatewayClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()

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

natGateway, err := client.Get(ctx, id.ResourceGroup, id.Name, "")
if err != nil {
if utils.ResponseWasNotFound(natGateway.Response) {
log.Printf("[DEBUG] Nat Gateway %q (Resource Group %q) could not be found - removing from state!", id.Name, id.ResourceGroup)
d.SetId("")
return nil
}
return fmt.Errorf("failed to retrieve Nat Gateway %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}

if natGateway.PublicIPAddresses == nil {
log.Printf("[DEBUG] Nat Gateway %q (Resource Group %q) doesn't have a Public IP - removing from state!", id.Name, id.ResourceGroup)
d.SetId("")
return nil
}

d.Set("nat_gateway_id", natGateway.ID)

return nil
}

func resourceArmNatGatewayPublicIpAssociationDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Network.NatGatewayClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()

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

publicIpAddressId := d.Get("public_ip_address_id").(string)

locks.ByName(id.Name, natGatewayResourceName)
defer locks.UnlockByName(id.Name, natGatewayResourceName)

natGateway, err := client.Get(ctx, id.ResourceGroup, id.Name, "")
if err != nil {
if utils.ResponseWasNotFound(natGateway.Response) {
return fmt.Errorf("Nat Gateway %q (Resource Group %q) was not found.", id.Name, id.ResourceGroup)
}

return fmt.Errorf("failed to retrieve Nat Gateway %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}

publicIpAddresses := make([]network.SubResource, 0)
if publicIPAddresses := natGateway.PublicIPAddresses; publicIPAddresses != nil {
for _, publicIPAddress := range *publicIPAddresses {
if publicIPAddress.ID == nil {
continue
}

if *publicIPAddress.ID != publicIpAddressId {
publicIpAddresses = append(publicIpAddresses, publicIPAddress)
}
}
}
natGateway.PublicIPAddresses = &publicIpAddresses

future, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.Name, natGateway)
if err != nil {
return fmt.Errorf("failed to remove Public Ip Association for Nat Gateway %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}

if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("failed to wait for removal of Public Ip Association for Nat Gateway %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}

return nil
}
2 changes: 2 additions & 0 deletions azurerm/internal/services/network/nat_gateway_resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,12 @@ func resourceArmNatGateway() *schema.Resource {
"public_ip_address_ids": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: azure.ValidateResourceID,
},
Deprecated: "Deprecated in favor of `azurerm_nat_gateway_public_ip_association`. The dependency relation between `azurerm_nat_gateway` and `azurerm_public_ip` isn't detected by implicit dependency. So `azurerm_nat_gateway_public_ip_association` is added to resolve this issue.",
},

"public_ip_prefix_ids": {
Expand Down
31 changes: 31 additions & 0 deletions azurerm/internal/services/network/parse/nat_gateway.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package parse

import (
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
)

type NatGatewayId struct {
Name string
ResourceGroup string
}

func NatGatewayID(input string) (*NatGatewayId, error) {
id, err := azure.ParseAzureResourceID(input)
if err != nil {
return nil, err
}

natGateway := NatGatewayId{
ResourceGroup: id.ResourceGroup,
}

if natGateway.Name, err = id.PopSegment("natGateways"); err != nil {
return nil, err
}

if err := id.ValidateNoEmptySegments(input); err != nil {
return nil, err
}

return &natGateway, nil
}
70 changes: 70 additions & 0 deletions azurerm/internal/services/network/parse/nat_gateway_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package parse

import (
"testing"
)

func TestNatGatewayID(t *testing.T) {
testData := []struct {
Name string
Input string
Error bool
Expect *NatGatewayId
}{
{
Name: "Empty",
Input: "",
Error: true,
},
{
Name: "No Resource Groups Segment",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000",
Error: true,
},
{
Name: "No Resource Groups Value",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups",
Error: true,
},
{
Name: "Resource Group ID",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1",
Error: true,
},
{
Name: "Missing Nat Gateway Value",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Network/natGateways",
Error: true,
},
{
Name: "Nat Gateway ID",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Network/natGateways/gateway1",
Error: false,
Expect: &NatGatewayId{
Name: "gateway1",
ResourceGroup: "group1",
},
},
}

for _, v := range testData {
t.Logf("[DEBUG] Testing %q", v.Name)

actual, err := NatGatewayID(v.Input)
if err != nil {
if v.Error {
continue
}

t.Fatalf("Expected a value but got an error: %s", err)
}

if actual.Name != v.Expect.Name {
t.Fatalf("Expected %q but got %q for Name", v.Expect.Name, actual.Name)
}

if actual.ResourceGroup != v.Expect.ResourceGroup {
t.Fatalf("Expected %q but got %q for Resource Group", v.Expect.ResourceGroup, actual.ResourceGroup)
}
}
}
1 change: 1 addition & 0 deletions azurerm/internal/services/network/registration.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ func (r Registration) SupportedResources() map[string]*schema.Resource {
"azurerm_private_endpoint": resourceArmPrivateEndpoint(),
"azurerm_private_link_service": resourceArmPrivateLinkService(),
"azurerm_public_ip": resourceArmPublicIp(),
"azurerm_nat_gateway_public_ip_association": resourceArmNatGatewayPublicIpAssociation(),
"azurerm_public_ip_prefix": resourceArmPublicIpPrefix(),
"azurerm_network_security_group": resourceArmNetworkSecurityGroup(),
"azurerm_network_security_rule": resourceArmNetworkSecurityRule(),
Expand Down
Loading