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_servicebus_namespace_authorization_rule #1498

Merged
merged 5 commits into from
Jul 9, 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
89 changes: 89 additions & 0 deletions azurerm/helpers/azure/servicebus.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package azure

import (
"fmt"
"log"
"regexp"

"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"

"github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus"
)

//validation
func ValidateServiceBusNamespaceName() schema.SchemaValidateFunc {
return validation.StringMatch(
regexp.MustCompile("^[a-zA-Z][-a-zA-Z0-9]{4,48}[a-zA-Z0-9]$"),
"The namespace name can contain only letters, numbers, and hyphens. The namespace must start with a letter, and it must end with a letter or number and be between 6 and 50 characters long.",
)
}

func ValidateServiceBusTopicName() schema.SchemaValidateFunc {
return validation.StringMatch(
regexp.MustCompile("^[a-zA-Z][-._a-zA-Z0-9]{0,258}([a-zA-Z0-9])?$"),
"The topic name can contain only letters, numbers, periods, hyphens and underscores. The namespace must start with a letter, and it must end with a letter or number and be less then 260 characters long.",
)
}

func ValidateServiceBusAuthorizationRuleName() schema.SchemaValidateFunc {
return validation.StringMatch(
regexp.MustCompile("^[a-zA-Z0-9][-._a-zA-Z0-9]{0,48}([a-zA-Z0-9])?$"),
"The name can contain only letters, numbers, periods, hyphens and underscores. The name must start and end with a letter or number and be less the 50 characters long.",
)
}

func ExpandServiceBusAuthorizationRuleRights(d *schema.ResourceData) *[]servicebus.AccessRights {
rights := []servicebus.AccessRights{}

if d.Get("manage").(bool) {
//manage implies all, so just return it
rights = append(rights, []servicebus.AccessRights{servicebus.Listen, servicebus.Send, servicebus.Manage}...)
return &rights
}

if d.Get("listen").(bool) {
rights = append(rights, servicebus.Listen)
}

if d.Get("send").(bool) {
rights = append(rights, servicebus.Send)
}

return &rights
}

func FlattenServiceBusAuthorizationRuleRights(rights *[]servicebus.AccessRights) (listen bool, send bool, manage bool) {
//zero (initial) value for a bool in go is false

if rights != nil {
for _, right := range *rights {
switch right {
case servicebus.Listen:
listen = true
case servicebus.Send:
send = true
case servicebus.Manage:
manage = true
default:
log.Printf("[DEBUG] Unknown Authorization Rule Right '%s'", right)
}
}
}

return
}

//shared schema

func ServiceBusAuthorizationRuleCustomizeDiff(d *schema.ResourceDiff, _ interface{}) error {
_, hasListen := d.GetOk("listen")
_, hasSend := d.GetOk("send")
_, hasManage := d.GetOk("manage")

if !hasListen && !hasSend && !hasManage {
return fmt.Errorf("One of the `listen`, `send` or `manage` properties needs to be set")
}

return nil
}
237 changes: 119 additions & 118 deletions azurerm/provider.go

Large diffs are not rendered by default.

192 changes: 192 additions & 0 deletions azurerm/resource_arm_servicebus_namespace_authorization_rule.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
package azurerm

import (
"fmt"
"log"

"github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus"
"github.com/hashicorp/terraform/helper/schema"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func resourceArmServiceAuthRuleSchemaFrom(schema map[string]*schema.Schema) map[string]*schema.Schema {
return schema
}

func resourceArmServiceBusNamespaceAuthorizationRule() *schema.Resource {
return &schema.Resource{
Create: resourceArmServiceBusNamespaceAuthorizationRuleCreateUpdate,
Read: resourceArmServiceBusNamespaceAuthorizationRuleRead,
Update: resourceArmServiceBusNamespaceAuthorizationRuleCreateUpdate,
Delete: resourceArmServiceBusNamespaceAuthorizationRuleDelete,

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

Schema: resourceArmServiceAuthRuleSchemaFrom(map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: azure.ValidateServiceBusAuthorizationRuleName(),
},

"namespace_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: azure.ValidateServiceBusNamespaceName(),
},

"resource_group_name": resourceGroupNameSchema(),

"listen": {
Type: schema.TypeBool,
Optional: true,
Computed: true, //because we set this to true if managed is chosen
},

"send": {
Type: schema.TypeBool,
Optional: true,
Computed: true, //because we set this to true if managed is chosen
Copy link
Contributor

Choose a reason for hiding this comment

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

send and listen want default values of false since otherwise it's not possible to disable send/listen by simply removing the code / explicitly setting these values to false, which is misleading (as is an option in other providers, but we're having to work around due to the SDK)

},

"manage": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},

"primary_key": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},

"primary_connection_string": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},

"secondary_key": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},

"secondary_connection_string": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
}),

CustomizeDiff: azure.ServiceBusAuthorizationRuleCustomizeDiff,
}
}

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

log.Printf("[INFO] preparing arguments for AzureRM ServiceBus Namespace Authorization Rule creation.")

name := d.Get("name").(string)
resGroup := d.Get("resource_group_name").(string)
namespaceName := d.Get("namespace_name").(string)

parameters := servicebus.SBAuthorizationRule{
Name: &name,
SBAuthorizationRuleProperties: &servicebus.SBAuthorizationRuleProperties{
Rights: azure.ExpandServiceBusAuthorizationRuleRights(d),
},
}

_, err := client.CreateOrUpdateAuthorizationRule(ctx, resGroup, namespaceName, name, parameters)
if err != nil {
return err
}

read, err := client.GetAuthorizationRule(ctx, resGroup, namespaceName, name)
if err != nil {
return err
}

if read.ID == nil {
return fmt.Errorf("Cannot read ServiceBus Namespace Authorization Rule %s (resource group %s) ID", name, resGroup)
}

d.SetId(*read.ID)

return resourceArmServiceBusNamespaceAuthorizationRuleRead(d, meta)
}

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

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

resGroup := id.ResourceGroup
namespaceName := id.Path["namespaces"]
name := id.Path["AuthorizationRules"] //this is slightly different then a topic rule (Authorization vs authorization)

resp, err := client.GetAuthorizationRule(ctx, resGroup, namespaceName, name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
d.SetId("")
return nil
}
return fmt.Errorf("Error making Read request on Azure ServiceBus Namespace Authorization Rule %s: %+v", name, err)
}

d.Set("name", name)
d.Set("namespace_name", namespaceName)
d.Set("resource_group_name", resGroup)

if properties := resp.SBAuthorizationRuleProperties; properties != nil {
listen, send, manage := azure.FlattenServiceBusAuthorizationRuleRights(properties.Rights)
d.Set("listen", listen)
d.Set("send", send)
d.Set("manage", manage)
}

keysResp, err := client.ListKeys(ctx, resGroup, namespaceName, name)
if err != nil {
return fmt.Errorf("Error making Read request on Azure ServiceBus Namespace Authorization Rule List Keys %s: %+v", name, err)
}

d.Set("primary_key", keysResp.PrimaryKey)
d.Set("primary_connection_string", keysResp.PrimaryConnectionString)
d.Set("secondary_key", keysResp.SecondaryKey)
d.Set("secondary_connection_string", keysResp.SecondaryConnectionString)
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 access rights -> secondary_connection_string via the [XX]Properties object & nil-check them?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

There are no properties object returned by list keys.


return nil
}

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

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

resGroup := id.ResourceGroup
namespaceName := id.Path["namespaces"]
name := id.Path["AuthorizationRules"] //this is slightly different then topic (Authorization vs authorization)

if _, err = client.DeleteAuthorizationRule(ctx, resGroup, namespaceName, name); err != nil {
return fmt.Errorf("Error issuing Azure ARM delete request of ServiceBus Namespace Authorization Rule %q (Resource Group %q): %+v", name, resGroup, err)
}

return nil
}
Loading