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 data source 'azurerm_resources' #3529

Merged
merged 11 commits into from
Oct 14, 2019
181 changes: 181 additions & 0 deletions azurerm/data_source_resource.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
package azurerm

import (
"fmt"
"log"
"strings"

"github.com/google/uuid"
"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/internal/tags"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
)

func dataSourceArmResource() *schema.Resource {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

given this is returning multiple results, this'd make more sense as:

Suggested change
func dataSourceArmResource() *schema.Resource {
func dataSourceArmResources() *schema.Resource {

return &schema.Resource{
Read: dataSourceArmResourceRead,
Schema: map[string]*schema.Schema{
"resource_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"name", "resource_group_name", "type", "required_tags"},
},
tiwood marked this conversation as resolved.
Show resolved Hide resolved
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"resource_id"},
},
"resource_group_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"resource_id"},
},
"type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"resource_id"},
},

"required_tags": tags.Schema(),

"resources": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"location": azure.SchemaLocationForDataSource(),
"tags": tags.SchemaDataSource(),
},
},
},
},
}
}

func dataSourceArmResourceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).Resource.ResourcesClient
ctx, cancel := timeouts.ForRead(meta.(*ArmClient).StopContext, d)
defer cancel()

resourceGroupName := d.Get("resource_group_name").(string)
resourceName := d.Get("name").(string)
resourceType := d.Get("type").(string)
resourceID := d.Get("resource_id").(string)

var filter string

if resourceGroupName != "" {
v := fmt.Sprintf("resourceGroup eq '%s'", resourceGroupName)
filter = filter + v
}

if resourceName != "" {
if strings.Contains(filter, "eq") {
filter = filter + " and "
}
v := fmt.Sprintf("name eq '%s'", resourceName)
filter = filter + v
}

if resourceType != "" {
if strings.Contains(filter, "eq") {
filter = filter + " and "
}
v := fmt.Sprintf("resourceType eq '%s'", resourceType)
filter = filter + v
}

tiwood marked this conversation as resolved.
Show resolved Hide resolved
requiredTags := d.Get("required_tags").(map[string]interface{})

resources := make([]map[string]interface{}, 0)

resource, err := client.ListComplete(ctx, filter, "", nil)
if err != nil {
return fmt.Errorf("Error getting resources: %+v", err)
}

for resource.NotDone() {
res := resource.Value()

tiwood marked this conversation as resolved.
Show resolved Hide resolved
// currently the Azure-Go-SDK method "GetByID" does not work for some resources, as the
// API Version is hard coded, therefore we use ListComplete and look for the ResourceID 'manually'
if resourceID != "" && *res.ID != resourceID {
err = resource.NextWithContext(ctx)
if err != nil {
return fmt.Errorf("Error loading Resource List: %s", err)
}
continue
}

// currently its not supported to use a other filters together with the tags filter
// therefore we need to filter the resources manually.
tagMatches := 0
for requiredTagName, requiredTagVal := range requiredTags {
for tagName, tagVal := range res.Tags {
tiwood marked this conversation as resolved.
Show resolved Hide resolved
if requiredTagName == tagName && requiredTagVal == *tagVal {
tagMatches++
}
}
}

if tagMatches == len(requiredTags) {
s := make(map[string]interface{})

if v := *res.Name; v != "" {
s["name"] = v
}
tiwood marked this conversation as resolved.
Show resolved Hide resolved

if v := *res.ID; v != "" {
s["id"] = v
}
tiwood marked this conversation as resolved.
Show resolved Hide resolved

if v := *res.Type; v != "" {
s["type"] = v
}
tiwood marked this conversation as resolved.
Show resolved Hide resolved

if v := *res.Location; v != "" {
s["location"] = v
}
tiwood marked this conversation as resolved.
Show resolved Hide resolved

tags := make(map[string]interface{}, len(res.Tags))
for key, value := range res.Tags {
tags[key] = *value
tiwood marked this conversation as resolved.
Show resolved Hide resolved
}

s["tags"] = tags

resources = append(resources, s)
tiwood marked this conversation as resolved.
Show resolved Hide resolved
} else {
log.Printf("[DEBUG] azurerm_resource - resources %q (id: %q) skipped as a required tag is not set or has the wrong value.", *res.Name, *res.ID)
}

err = resource.NextWithContext(ctx)
if err != nil {
return fmt.Errorf("Error loading Resource List: %s", err)
}
}

d.SetId("resource-" + uuid.New().String())
if err := d.Set("resources", resources); err != nil {
return fmt.Errorf("Error setting `resources`: %+v", err)
}

return nil
}
176 changes: 176 additions & 0 deletions azurerm/data_source_resource_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
package azurerm

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
)

func TestAccDataSourceAzureRMResource_ByResourceID(t *testing.T) {
dataSourceName := "data.azurerm_resource.test"
ri := tf.AccRandTimeInt()
rs := acctest.RandString(4)
location := testLocation()
config := testAccDataSourceAzureRMResource_ByResourceID(ri, rs, location)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: config,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(dataSourceName, "resources.#", "1"),
),
},
},
})
}

func TestAccDataSourceAzureRMResource_ByName(t *testing.T) {
dataSourceName := "data.azurerm_resource.test"
ri := tf.AccRandTimeInt()
rs := acctest.RandString(4)
location := testLocation()
config := testAccDataSourceAzureRMResource_ByName(ri, rs, location)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: config,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(dataSourceName, "resources.#", "1"),
),
},
},
})
}

func TestAccDataSourceAzureRMResource_ByResourceGroup(t *testing.T) {
dataSourceName := "data.azurerm_resource.test"
ri := tf.AccRandTimeInt()
rs := acctest.RandString(4)
location := testLocation()
config := testAccDataSourceAzureRMResource_ByResourceGroup(ri, rs, location)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: config,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(dataSourceName, "resources.#", "1"),
),
},
},
})
}

func TestAccDataSourceAzureRMResource_ByResourceType(t *testing.T) {
dataSourceName := "data.azurerm_resource.test"
ri := tf.AccRandTimeInt()
rs := acctest.RandString(4)
location := testLocation()
config := testAccDataSourceAzureRMResource_ByResourceType(ri, rs, location)

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: config,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(dataSourceName, "resources.#", "1"),
),
},
},
})
}

func TestAccDataSourceAzureRMResource_FilteredByTags(t *testing.T) {
dataSourceName := "data.azurerm_resource.test"
ri := tf.AccRandTimeInt()
rs := acctest.RandString(4)
location := testLocation()
config := testAccDataSourceAzureRMResource_FilteredByTags(ri, rs, location)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: config,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(dataSourceName, "resources.#", "1"),
),
},
},
})
}

func testAccDataSourceAzureRMResource_ByResourceID(rInt int, rString string, location string) string {
r := testAccDataSourceAzureRMStorageAccount_basic(rInt, rString, location)
return fmt.Sprintf(`
%s

data "azurerm_resource" "test" {
resource_id = "${azurerm_storage_account.test.id}"
}
`, r)
}

func testAccDataSourceAzureRMResource_ByName(rInt int, rString string, location string) string {
r := testAccDataSourceAzureRMStorageAccount_basic(rInt, rString, location)
return fmt.Sprintf(`
%s

data "azurerm_resource" "test" {
name = "${azurerm_storage_account.test.name}"
}
`, r)
}

func testAccDataSourceAzureRMResource_ByResourceGroup(rInt int, rString string, location string) string {
r := testAccDataSourceAzureRMStorageAccount_basic(rInt, rString, location)
return fmt.Sprintf(`
%s

data "azurerm_resource" "test" {
resource_group_name = "${azurerm_storage_account.test.resource_group_name}"
}
`, r)
}

func testAccDataSourceAzureRMResource_ByResourceType(rInt int, rString string, location string) string {
r := testAccDataSourceAzureRMStorageAccount_basic(rInt, rString, location)
return fmt.Sprintf(`
%s

data "azurerm_resource" "test" {
resource_group_name = "${azurerm_storage_account.test.resource_group_name}"
type = "Microsoft.Storage/storageAccounts"
}
`, r)
}

func testAccDataSourceAzureRMResource_FilteredByTags(rInt int, rString string, location string) string {
r := testAccDataSourceAzureRMStorageAccount_basic(rInt, rString, location)
return fmt.Sprintf(`
%s

data "azurerm_resource" "test" {
name = "${azurerm_storage_account.test.name}"
resource_group_name = "${azurerm_storage_account.test.resource_group_name}"

required_tags = {
environment = "production"
}
}
`, r)
}
5 changes: 5 additions & 0 deletions azurerm/internal/services/resource/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ type Client struct {
DeploymentsClient *resources.DeploymentsClient
LocksClient *locks.ManagementLocksClient
ProvidersClient *providers.ProvidersClient
ResourcesClient *resources.Client
}

func BuildClient(o *common.ClientOptions) *Client {
Expand All @@ -28,10 +29,14 @@ func BuildClient(o *common.ClientOptions) *Client {
ProvidersClient := providers.NewProvidersClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId)
o.ConfigureClient(&ProvidersClient.Client, o.ResourceManagerAuthorizer)

ResourcesClient := resources.NewClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId)
o.ConfigureClient(&ResourcesClient.Client, o.ResourceManagerAuthorizer)

return &Client{
GroupsClient: &GroupsClient,
DeploymentsClient: &DeploymentsClient,
LocksClient: &LocksClient,
ProvidersClient: &ProvidersClient,
ResourcesClient: &ResourcesClient,
}
}
1 change: 1 addition & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ func Provider() terraform.ResourceProvider {
"azurerm_recovery_services_vault": dataSourceArmRecoveryServicesVault(),
"azurerm_recovery_services_protection_policy_vm": dataSourceArmRecoveryServicesProtectionPolicyVm(),
"azurerm_redis_cache": dataSourceArmRedisCache(),
"azurerm_resource": dataSourceArmResource(),
tiwood marked this conversation as resolved.
Show resolved Hide resolved
"azurerm_resource_group": dataSourceArmResourceGroup(),
"azurerm_role_definition": dataSourceArmRoleDefinition(),
"azurerm_route_table": dataSourceArmRouteTable(),
Expand Down
Loading