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_security_center_contact #2045

Merged
merged 10 commits into from
Oct 13, 2018
Merged
Show file tree
Hide file tree
Changes from 3 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
16 changes: 16 additions & 0 deletions azurerm/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import (
"github.com/Azure/azure-sdk-for-go/services/preview/operationalinsights/mgmt/2015-11-01-preview/operationalinsights"
"github.com/Azure/azure-sdk-for-go/services/preview/operationsmanagement/mgmt/2015-11-01-preview/operationsmanagement"
"github.com/Azure/azure-sdk-for-go/services/preview/resources/mgmt/2018-03-01-preview/management"
"github.com/Azure/azure-sdk-for-go/services/preview/security/mgmt/2017-08-01-preview/security"
"github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2015-05-01-preview/sql"
"github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices"
"github.com/Azure/azure-sdk-for-go/services/redis/mgmt/2018-03-01/redis"
Expand Down Expand Up @@ -252,6 +253,10 @@ type ArmClient struct {
// Search
searchServicesClient search.ServicesClient

// Security Centre
securityCenterPricingClient security.PricingsClient
securityCenterContactsClient security.ContactsClient

// ServiceBus
serviceBusQueuesClient servicebus.QueuesClient
serviceBusNamespacesClient servicebus.NamespacesClient
Expand Down Expand Up @@ -492,6 +497,7 @@ func getArmClient(c *authentication.Config) (*ArmClient, error) {
client.registerRelayClients(endpoint, c.SubscriptionID, auth, sender)
client.registerResourcesClients(endpoint, c.SubscriptionID, auth)
client.registerSearchClients(endpoint, c.SubscriptionID, auth)
client.registerSecurityCenterClients(endpoint, c.SubscriptionID, "Global", auth)
client.registerServiceBusClients(endpoint, c.SubscriptionID, auth)
client.registerServiceFabricClients(endpoint, c.SubscriptionID, auth)
client.registerSchedulerClients(endpoint, c.SubscriptionID, auth)
Expand Down Expand Up @@ -1016,6 +1022,16 @@ func (c *ArmClient) registerSearchClients(endpoint, subscriptionId string, auth
c.searchServicesClient = searchClient
}

func (c *ArmClient) registerSecurityCenterClients(endpoint, subscriptionId, ascLocation string, auth autorest.Authorizer) {
securityCenterPricingClient := security.NewPricingsClientWithBaseURI(endpoint, subscriptionId, ascLocation)
c.configureClient(&securityCenterPricingClient.Client, auth)
c.securityCenterPricingClient = securityCenterPricingClient

securityCenterContactsClient := security.NewContactsClientWithBaseURI(endpoint, subscriptionId, ascLocation)
c.configureClient(&securityCenterContactsClient.Client, auth)
c.securityCenterContactsClient = securityCenterContactsClient
}

func (c *ArmClient) registerServiceBusClients(endpoint, subscriptionId string, auth autorest.Authorizer) {
queuesClient := servicebus.NewQueuesClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&queuesClient.Client, auth)
Expand Down
2 changes: 2 additions & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,8 @@ func Provider() terraform.ResourceProvider {
"azurerm_route": resourceArmRoute(),
"azurerm_route_table": resourceArmRouteTable(),
"azurerm_search_service": resourceArmSearchService(),
"azurerm_securitycenter_subscription_pricing": resourceArmSecurityCenterSubscriptionPricing(),
"azurerm_securitycenter_contact": resourceArmSecurityCenterContact(),
Copy link
Contributor

Choose a reason for hiding this comment

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

(as in the other PR) I think this'd be better as security_center?

"azurerm_servicebus_namespace": resourceArmServiceBusNamespace(),
"azurerm_servicebus_namespace_authorization_rule": resourceArmServiceBusNamespaceAuthorizationRule(),
"azurerm_servicebus_queue": resourceArmServiceBusQueue(),
Expand Down
2 changes: 0 additions & 2 deletions azurerm/resource_arm_search_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ func testCheckAzureRMSearchServiceExists(name string) resource.TestCheckFunc {
ctx := testAccProvider.Meta().(*ArmClient).StopContext

resp, err := client.Get(ctx, resourceGroup, searchName, nil)

if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
return fmt.Errorf("Search Service %q (resource group %q) was not found: %+v", searchName, resourceGroup, err)
Expand All @@ -94,7 +93,6 @@ func testCheckAzureRMSearchServiceDestroy(s *terraform.State) error {
ctx := testAccProvider.Meta().(*ArmClient).StopContext

resp, err := client.Get(ctx, resourceGroup, searchName, nil)

if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
return nil
Expand Down
153 changes: 153 additions & 0 deletions azurerm/resource_arm_securitycenter_contact.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package azurerm

import (
"fmt"
"log"
"strings"

"github.com/Azure/azure-sdk-for-go/services/preview/security/mgmt/2017-08-01-preview/security"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress"

"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

//seems you can only set one contact:
// Invalid security contact name was provided - only 'defaultX' is allowed where X is an index
// Invalid security contact name 'default0' was provided. Expected 'default1'
// Message="Invalid security contact name 'default2' was provided. Expected 'default1'"

func resourceArmSecurityCenterContact() *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.

as discussed on Slack - I think it'd be worth combining these into an azurerm_security_center resource with blocks for each thing?

Copy link
Contributor

Choose a reason for hiding this comment

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

as discussed on Slack - I think it'd be worth combining these into an azurerm_security_center resource with blocks for each thing?

Copy link
Contributor

Choose a reason for hiding this comment

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

can we document this resource too?

return &schema.Resource{
Create: resourceArmSecurityCenterContactCreateUpdate,
Read: resourceArmSecurityCenterContactRead,
Update: resourceArmSecurityCenterContactCreateUpdate,
Delete: resourceArmSecurityCenterContactDelete,

Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"email": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: suppress.CaseDifference,
Copy link
Contributor

Choose a reason for hiding this comment

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

is there a reason to do this?

//todo validation
},

"phone": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: suppress.CaseDifference,
Copy link
Contributor

Choose a reason for hiding this comment

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

I don't think this is necessary for a phone number?

ValidateFunc: validation.NoZeroValues,
},

"alert_notifications": {
Type: schema.TypeBool,
Required: true,
},

"alerts_to_admins": {
Type: schema.TypeBool,
Required: true,
},
},
}
}

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

contact := security.Contact{
ContactProperties: &security.ContactProperties{
Email: utils.String(d.Get("email").(string)),
Phone: utils.String(d.Get("phone").(string)),
},
}

if alertNotifications := d.Get("alert_notifications").(bool); alertNotifications {
contact.AlertNotifications = security.On
} else {
contact.AlertNotifications = security.Off
}

if alertNotifications := d.Get("alerts_to_admins").(bool); alertNotifications {
contact.AlertsToAdmins = security.AlertsToAdminsOn
} else {
contact.AlertsToAdmins = security.AlertsToAdminsOff
}

if d.IsNewResource() {
_, err := client.Create(ctx, "default1", contact)
if err != nil {
return fmt.Errorf("Error creating Security Center Contact: %+v", err)
}

resp, err := client.Get(ctx, "default1")
if err != nil {
return fmt.Errorf("Error reading Security Center Contact: %+v", err)
}
if resp.ID == nil {
return fmt.Errorf("Security Center Contact ID is nil")
}

d.SetId(*resp.ID)
} else {
_, err := client.Update(ctx, "default1", contact)
if err != nil {
return fmt.Errorf("Error updating Security Center Contact: %+v", err)
}
}

return resourceArmSecurityCenterContactRead(d, meta)
}

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

//id is in format of `/subscriptions/20ff7fc3-e762-44dd-bd96-b71116dcdc23/providers/Microsoft.Security/securityContacts/john`
//parseAzureResourceID doesn't support id without a resource group
Copy link
Contributor

Choose a reason for hiding this comment

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

we should probably think about creating an overload which doesn't require it - there's a few instances of this now (key vault)

bits := strings.Split(d.Id(), "/")
name := bits[len(bits)-1]

resp, err := client.Get(ctx, name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[DEBUG] Security Center Subscription Contact was not found: %v", err)
d.SetId("")
return nil
}

return fmt.Errorf("Error reading Security Center Contact: %+v", err)
}

if properties := resp.ContactProperties; properties != nil {
d.Set("email", properties.Email)
d.Set("phone", properties.Phone)
d.Set("alert_notifications", properties.AlertNotifications == security.On)
d.Set("alerts_to_admins", properties.AlertsToAdmins == security.AlertsToAdminsOn)
}

return nil
}

func resourceArmSecurityCenterContactDelete(_ *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).securityCenterContactsClient
ctx := meta.(*ArmClient).StopContext

resp, err := client.Delete(ctx, "default1")
if err != nil {
if utils.ResponseWasNotFound(resp) {
log.Printf("[DEBUG] Security Center Subscription Contact was not found: %v", err)
return nil
}

return fmt.Errorf("Error deleting Security Center Contact: %+v", err)
}

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

import (
"fmt"
"testing"

"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func TestAccAzureRMSecurityCenterContact_basic(t *testing.T) {
resourceName := "azurerm_securitycenter_contact.test"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccAzureRMSecurityCenterContact_template("[email protected]", "+1-555-555-5555", true, true),
Check: resource.ComposeTestCheckFunc(
testCheckAzureRMSecurityCenterContactExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "email", "[email protected]"),
resource.TestCheckResourceAttr(resourceName, "phone", "+1-555-555-5555"),
resource.TestCheckResourceAttr(resourceName, "alert_notifications", "true"),
resource.TestCheckResourceAttr(resourceName, "alerts_to_admins", "true"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func TestAccAzureRMSecurityCenterContact_update(t *testing.T) {
resourceName := "azurerm_securitycenter_contact.test"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccAzureRMSecurityCenterContact_template("[email protected]", "+1-555-555-5555", true, true),
Check: resource.ComposeTestCheckFunc(
testCheckAzureRMSecurityCenterContactExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "email", "[email protected]"),
resource.TestCheckResourceAttr(resourceName, "phone", "+1-555-555-5555"),
resource.TestCheckResourceAttr(resourceName, "alert_notifications", "true"),
resource.TestCheckResourceAttr(resourceName, "alerts_to_admins", "true"),
),
},
{
Config: testAccAzureRMSecurityCenterContact_template("[email protected]", "+1-555-678-6789", false, false),
Check: resource.ComposeTestCheckFunc(
testCheckAzureRMSecurityCenterContactExists(resourceName),
resource.TestCheckResourceAttr(resourceName, "email", "[email protected]"),
resource.TestCheckResourceAttr(resourceName, "phone", "+1-555-678-6789"),
Copy link
Contributor

Choose a reason for hiding this comment

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

could we make this an international number to ensure that works too? +44 1234 567890 should work as an example

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Oddly enough international numbers do not seem to work, for that and some other variations i tried:

* azurerm_security_center_contact.test: Error updating Security Center Contact: security.ContactsClient#Update: Failure responding to request: StatusCode=400 -- Original Error: autorest/azure: Service returned an error. Status=400 Code="InvalidInputJson" Message="Invalid security contact phone was provided."

resource.TestCheckResourceAttr(resourceName, "alert_notifications", "false"),
resource.TestCheckResourceAttr(resourceName, "alerts_to_admins", "false"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func testCheckAzureRMSecurityCenterContactExists(name string) resource.TestCheckFunc {
return func(s *terraform.State) error {
client := testAccProvider.Meta().(*ArmClient).securityCenterContactsClient
ctx := testAccProvider.Meta().(*ArmClient).StopContext

rs, ok := s.RootModule().Resources[name]
if !ok {
return fmt.Errorf("Not found: %s", name)
}

contactName := rs.Primary.Attributes["securityContacts"]

resp, err := client.Get(ctx, contactName)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
return fmt.Errorf("Security Center Subscription Contact %q was not found: %+v", contactName, err)
}

return fmt.Errorf("Bad: GetContact: %+v", err)
}

return nil
}
}

func testAccAzureRMSecurityCenterContact_template(email, phone string, notifications, adminAlerts bool) string {
return fmt.Sprintf(`
resource "azurerm_securitycenter_contact" "test" {
email = "%s"
phone = "%s"

alert_notifications = %t
alerts_to_admins = %t
}
`, email, phone, notifications, adminAlerts)
}
Loading