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_policy_assignment #1051

Merged
merged 3 commits into from
Mar 30, 2018
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
5 changes: 5 additions & 0 deletions azurerm/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ type ArmClient struct {
appServicesClient web.AppsClient

// Policy
policyAssignmentsClient policy.AssignmentsClient
policyDefinitionsClient policy.DefinitionsClient
}

Expand Down Expand Up @@ -885,6 +886,10 @@ func (c *ArmClient) registerWebClients(endpoint, subscriptionId string, auth aut
}

func (c *ArmClient) registerPolicyClients(endpoint, subscriptionId string, auth autorest.Authorizer) {
policyAssignmentsClient := policy.NewAssignmentsClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&policyAssignmentsClient.Client, auth)
c.policyAssignmentsClient = policyAssignmentsClient

policyDefinitionsClient := policy.NewDefinitionsClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&policyDefinitionsClient.Client, auth)
c.policyDefinitionsClient = policyDefinitionsClient
Expand Down
30 changes: 30 additions & 0 deletions azurerm/import_arm_policy_assignment_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package azurerm

import (
"testing"

"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)

func TestAccAzureRMPolicyAssignment_importComplete(t *testing.T) {
rInt := acctest.RandInt()
location := testLocation()
resourceName := "azurerm_policy_assignment.test"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testCheckAzureRMPolicyAssignmentDestroy,
Steps: []resource.TestStep{
{
Config: testAzureRMPolicyAssignment_complete(rInt, location),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
1 change: 1 addition & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ func Provider() terraform.ResourceProvider {
"azurerm_network_security_group": resourceArmNetworkSecurityGroup(),
"azurerm_network_security_rule": resourceArmNetworkSecurityRule(),
"azurerm_network_watcher": resourceArmNetworkWatcher(),
"azurerm_policy_assignment": resourceArmPolicyAssignment(),
"azurerm_policy_definition": resourceArmPolicyDefinition(),
"azurerm_postgresql_configuration": resourceArmPostgreSQLConfiguration(),
"azurerm_postgresql_database": resourceArmPostgreSQLDatabase(),
Expand Down
196 changes: 196 additions & 0 deletions azurerm/resource_arm_policy_assignment.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
package azurerm

import (
"fmt"
"log"

"time"

"context"
"strconv"

"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-12-01/policy"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/structure"
"github.com/hashicorp/terraform/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func resourceArmPolicyAssignment() *schema.Resource {
return &schema.Resource{
Create: resourceArmPolicyAssignmentCreate,
Read: resourceArmPolicyAssignmentRead,
Delete: resourceArmPolicyAssignmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

"scope": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

"policy_definition_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},

"display_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},

"parameters": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.ValidateJsonString,
DiffSuppressFunc: structure.SuppressJsonDiff,
},
},
}
}

func resourceArmPolicyAssignmentCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).policyAssignmentsClient
ctx := meta.(*ArmClient).StopContext

name := d.Get("name").(string)
scope := d.Get("scope").(string)

policyDefinitionId := d.Get("policy_definition_id").(string)
displayName := d.Get("display_name").(string)

assignment := policy.Assignment{
AssignmentProperties: &policy.AssignmentProperties{
PolicyDefinitionID: utils.String(policyDefinitionId),
DisplayName: utils.String(displayName),
Scope: utils.String(scope),
},
}

if v := d.Get("description").(string); v != "" {
assignment.AssignmentProperties.Description = utils.String(v)
}

if v := d.Get("parameters").(string); v != "" {
expandedParams, err := structure.ExpandJsonFromString(v)
if err != nil {
return fmt.Errorf("Error expanding JSON from Parameters %q: %+v", v, err)
}

assignment.AssignmentProperties.Parameters = &expandedParams
}

_, err := client.Create(ctx, scope, name, assignment)
if err != nil {
return err
}

// Policy Assignments are eventually consistent; wait for them to stabilize
log.Printf("[DEBUG] Waiting for Policy Assignment %q to become available", name)
stateConf := &resource.StateChangeConf{
Pending: []string{"404"},
Target: []string{"200"},
Refresh: policyAssignmentRefreshFunc(ctx, client, scope, name),
Timeout: 5 * time.Minute,
MinTimeout: 10 * time.Second,
ContinuousTargetOccurence: 10,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Policy Assignment %q to become available: %s", name, err)
}

resp, err := client.Get(ctx, scope, name)
if err != nil {
return err
}

d.SetId(*resp.ID)

return resourceArmPolicyAssignmentRead(d, meta)
}

func resourceArmPolicyAssignmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).policyAssignmentsClient
ctx := meta.(*ArmClient).StopContext

id := d.Id()

resp, err := client.GetByID(ctx, id)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[INFO] Error reading Policy Assignment %q - removing from state", id)
d.SetId("")
return nil
}

return fmt.Errorf("Error reading Policy Assignment %q: %+v", id, err)
}

d.Set("name", resp.Name)

if props := resp.AssignmentProperties; props != nil {
d.Set("scope", props.Scope)
d.Set("policy_definition_id", props.PolicyDefinitionID)
d.Set("description", props.Description)
d.Set("display_name", props.DisplayName)

if params := props.Parameters; params != nil {
json, err := structure.FlattenJsonToString(*params)
if err != nil {
return fmt.Errorf("Error serializing JSON from Parameters: %+v", err)
}

d.Set("parameters", json)
}
}

return nil
}

func resourceArmPolicyAssignmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).policyAssignmentsClient
ctx := meta.(*ArmClient).StopContext

id := d.Id()

resp, err := client.DeleteByID(ctx, id)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
return nil
}

return fmt.Errorf("Error deleting Policy Assignment %q: %+v", id, err)
}

return nil
}

func policyAssignmentRefreshFunc(ctx context.Context, client policy.AssignmentsClient, scope string, name string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
res, err := client.Get(ctx, scope, name)
if err != nil {
return nil, strconv.Itoa(res.StatusCode), fmt.Errorf("Error issuing read request in policyAssignmentRefreshFunc for Policy Assignment %q (Scope: %q): %s", name, scope, err)
}

return res, strconv.Itoa(res.StatusCode), nil
}
}
Loading