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_ip_group_cidr #20225

Merged
merged 4 commits into from
Jan 30, 2023
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
185 changes: 185 additions & 0 deletions internal/services/network/ip_group_cidr_resource.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
package network

import (
"fmt"
"strings"
"time"

"github.com/hashicorp/terraform-provider-azurerm/helpers/tf"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
"github.com/hashicorp/terraform-provider-azurerm/internal/locks"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/network/parse"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/network/validate"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation"
"github.com/hashicorp/terraform-provider-azurerm/internal/timeouts"
"github.com/hashicorp/terraform-provider-azurerm/utils"
"github.com/tombuildsstuff/kermit/sdk/network/2022-07-01/network"
)

func resourceIpGroupCidr() *pluginsdk.Resource {
return &pluginsdk.Resource{
Create: resourceIpGroupCidrCreateUpdate,
Read: resourceIpGroupCidrRead,
Delete: resourceIpGroupCidrDelete,

Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error {
_, err := parse.IpGroupCidrID(id)
return err
}),

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

Schema: map[string]*pluginsdk.Schema{
"ip_group_id": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.IpGroupID,
},
"cidr": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringIsNotEmpty,
},
},
}
}

func resourceIpGroupCidrCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Network.IPGroupsClient
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()

cidr := d.Get("cidr").(string)
cidrName := strings.ReplaceAll(cidr, "/", "_")
ipGroupId, err := parse.IpGroupID(d.Get("ip_group_id").(string))
if err != nil {
return err
}
id := parse.NewIpGroupCidrID(subscriptionId, ipGroupId.ResourceGroup, ipGroupId.Name, cidrName)

locks.ByID(ipGroupId.ID())
defer locks.UnlockByID(ipGroupId.ID())

existing, err := client.Get(ctx, ipGroupId.ResourceGroup, ipGroupId.Name, "")
if err != nil {
if utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("checking for presence of existing %s: %s", ipGroupId, err)
}
}

if d.IsNewResource() {
if utils.SliceContainsValue(*existing.IPAddresses, cidr) {
return tf.ImportAsExistsError("azurerm_ip_group_cidr", id.ID())
}
}

ipAddresses := make([]string, 0)
if existing.IPAddresses != nil {
ipAddresses = *existing.IPAddresses
}
ipAddresses = append(ipAddresses, cidr)

params := network.IPGroup{
Name: &ipGroupId.Name,
Location: existing.Location,
Tags: existing.Tags,
IPGroupPropertiesFormat: &network.IPGroupPropertiesFormat{
IPAddresses: &ipAddresses,
},
}

future, err := client.CreateOrUpdate(ctx, ipGroupId.ResourceGroup, ipGroupId.Name, params)
if err != nil {
return fmt.Errorf("creating/updating %s: %+v", id, err)
}

if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("waiting for the completion of %s: %+v", id, err)
}

d.SetId(id.ID())

return resourceIpGroupCidrRead(d, meta)
}

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

id, err := parse.IpGroupCidrID(d.Id())
if err != nil {
return err
}
ipGroupId := parse.NewIpGroupID(id.SubscriptionId, id.ResourceGroup, id.IpGroupName)
cidr := strings.ReplaceAll(id.CidrName, "_", "/")

resp, err := client.Get(ctx, id.ResourceGroup, id.IpGroupName, "")
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
return fmt.Errorf("making Read request on IP Group %q (Resource Group %q): %+v", ipGroupId.Name, ipGroupId.ResourceGroup, err)
}
if !utils.SliceContainsValue(*resp.IPAddresses, cidr) {
d.SetId("")
return nil
}
}

d.Set("ip_group_id", ipGroupId.ID())
d.Set("cidr", cidr)

return nil
}

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

cidr := d.Get("cidr").(string)
ipGroupId, err := parse.IpGroupID(d.Get("ip_group_id").(string))
if err != nil {
return err
}

locks.ByID(ipGroupId.ID())
defer locks.UnlockByID(ipGroupId.ID())

existing, err := client.Get(ctx, ipGroupId.ResourceGroup, ipGroupId.Name, "")
if err != nil {
if utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("reading existing %s: %s", ipGroupId, err)
}
}

ipAddresses := *existing.IPAddresses
ipAddresses = utils.RemoveFromStringArray(ipAddresses, cidr)

params := network.IPGroup{
Name: &ipGroupId.Name,
Location: existing.Location,
Tags: existing.Tags,
IPGroupPropertiesFormat: &network.IPGroupPropertiesFormat{
IPAddresses: &ipAddresses,
},
}

future, err := client.CreateOrUpdate(ctx, ipGroupId.ResourceGroup, ipGroupId.Name, params)
if err != nil {
return fmt.Errorf("creating/updating %s: %+v", ipGroupId.ID(), err)
}

if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("deleting IP Group CIDR %q (IP Group %q - Resource Group %q): %+v", cidr, ipGroupId.Name, ipGroupId.ResourceGroup, err)
}

return err
}
149 changes: 149 additions & 0 deletions internal/services/network/ip_group_cidr_resource_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
package network_test

import (
"context"
"fmt"
"testing"

"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance"
"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/network/parse"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/utils"
)

type IPGroupCidrResource struct{}

func TestAccIpGroupCidr_basic(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_ip_group_cidr", "test")
r := IPGroupCidrResource{}
data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.basic(data),
Check: acceptance.ComposeTestCheckFunc(
check.That("azurerm_ip_group_cidr.test").ExistsInAzure(r),
),
},
data.ImportStep(),
})
}

func TestAccIpGroupCidr_multiple(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_ip_group_cidr", "test")
r := IPGroupCidrResource{}
data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.basic(data),
Check: acceptance.ComposeTestCheckFunc(
check.That("azurerm_ip_group_cidr.test").ExistsInAzure(r),
),
},
data.ImportStep(),
{
Config: r.multiple(data),
Check: acceptance.ComposeTestCheckFunc(
check.That("azurerm_ip_group.test").Key("tags.env").HasValue("prod"),
check.That("azurerm_ip_group_cidr.test").ExistsInAzure(r),
check.That("azurerm_ip_group_cidr.multiple_1").ExistsInAzure(r),
check.That("azurerm_ip_group_cidr.multiple_2").ExistsInAzure(r),
),
},
data.ImportStep(),
})
}

func TestAccIpGroupCidr_requiresImport(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_ip_group_cidr", "test")
r := IPGroupCidrResource{}
data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.basic(data),
Check: acceptance.ComposeTestCheckFunc(
check.That("azurerm_ip_group_cidr.test").ExistsInAzure(r),
),
},
{
Config: r.requiresImport(data),
ExpectError: acceptance.RequiresImportError("azurerm_ip_group_cidr"),
},
})
}

func (t IPGroupCidrResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) {
id, err := parse.IpGroupCidrID(state.ID)
if err != nil {
return nil, err
}

resp, err := clients.Network.IPGroupsClient.Get(ctx, id.ResourceGroup, id.IpGroupName, "")
if err != nil {
return nil, fmt.Errorf("reading IP Group (%s): %+v", id, err)
}

if !utils.SliceContainsValue(*resp.IPAddresses, state.Attributes["cidr"]) {
return utils.Bool(false), nil
}

return utils.Bool(true), nil
}

func (IPGroupCidrResource) basic(data acceptance.TestData) string {
return fmt.Sprintf(`
provider "azurerm" {
features {}
}

resource "azurerm_resource_group" "test" {
name = "acctestRG-network-%d"
location = "%s"
}

resource "azurerm_ip_group" "test" {
name = "acceptanceTestIpGroup1"
location = azurerm_resource_group.test.location
resource_group_name = azurerm_resource_group.test.name
tags = {
env = "prod"
}

lifecycle {
ignore_changes = ["cidrs"]
}
}

resource "azurerm_ip_group_cidr" "test" {
ip_group_id = azurerm_ip_group.test.id
cidr = "10.0.0.0/24"
}


`, data.RandomInteger, data.Locations.Primary)
}

func (r IPGroupCidrResource) multiple(data acceptance.TestData) string {
return fmt.Sprintf(`
%s

resource "azurerm_ip_group_cidr" "multiple_1" {
ip_group_id = azurerm_ip_group.test.id
cidr = "10.10.0.0/24"
}

resource "azurerm_ip_group_cidr" "multiple_2" {
ip_group_id = azurerm_ip_group.test.id
cidr = "10.20.0.0/24"
}
`, r.basic(data))
}

func (r IPGroupCidrResource) requiresImport(data acceptance.TestData) string {
return fmt.Sprintf(`
%s

resource "azurerm_ip_group_cidr" "import" {
ip_group_id = azurerm_ip_group_cidr.test.ip_group_id
cidr = azurerm_ip_group_cidr.test.cidr
}
`, r.basic(data))
}
Loading