Skip to content

Commit

Permalink
Merge pull request #963 from terraform-providers/f-scheduler_job_coll…
Browse files Browse the repository at this point in the history
…ection

Added new resource azurerm_scheduler_job_collection
  • Loading branch information
katbyte authored Mar 13, 2018
2 parents 69a5988 + 6d96f4e commit 21929db
Show file tree
Hide file tree
Showing 9 changed files with 558 additions and 0 deletions.
11 changes: 11 additions & 0 deletions azurerm/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-06-01/subscriptions"
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-09-01/locks"
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources"
"github.com/Azure/azure-sdk-for-go/services/scheduler/mgmt/2016-03-01/scheduler"
"github.com/Azure/azure-sdk-for-go/services/search/mgmt/2015-08-19/search"
"github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus"
"github.com/Azure/azure-sdk-for-go/services/sql/mgmt/2015-05-01-preview/sql"
Expand Down Expand Up @@ -173,6 +174,9 @@ type ArmClient struct {
serviceBusTopicsClient servicebus.TopicsClient
serviceBusSubscriptionsClient servicebus.SubscriptionsClient

//Scheduler
schedulerJobCollectionsClient scheduler.JobCollectionsClient

// Storage
storageServiceClient storage.AccountsClient
storageUsageClient storage.UsageClient
Expand Down Expand Up @@ -358,6 +362,7 @@ func getArmClient(c *authentication.Config) (*ArmClient, error) {
client.registerResourcesClients(endpoint, c.SubscriptionID, auth)
client.registerSearchClients(endpoint, c.SubscriptionID, auth)
client.registerServiceBusClients(endpoint, c.SubscriptionID, auth)
client.registerSchedulerClients(endpoint, c.SubscriptionID, auth)
client.registerStorageClients(endpoint, c.SubscriptionID, auth)
client.registerTrafficManagerClients(endpoint, c.SubscriptionID, auth)
client.registerWebClients(endpoint, c.SubscriptionID, auth)
Expand Down Expand Up @@ -807,6 +812,12 @@ func (c *ArmClient) registerServiceBusClients(endpoint, subscriptionId string, a
c.serviceBusSubscriptionsClient = subscriptionsClient
}

func (c *ArmClient) registerSchedulerClients(endpoint, subscriptionId string, auth autorest.Authorizer) {
jobsClient := scheduler.NewJobCollectionsClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&jobsClient.Client, auth)
c.schedulerJobCollectionsClient = jobsClient
}

func (c *ArmClient) registerStorageClients(endpoint, subscriptionId string, auth autorest.Authorizer) {
accountsClient := storage.NewAccountsClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&accountsClient.Client, auth)
Expand Down
1 change: 1 addition & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ func Provider() terraform.ResourceProvider {
"azurerm_servicebus_topic": resourceArmServiceBusTopic(),
"azurerm_servicebus_topic_authorization_rule": resourceArmServiceBusTopicAuthorizationRule(),
"azurerm_snapshot": resourceArmSnapshot(),
"azurerm_scheduler_job_collection": resourceArmSchedulerJobCollection(),
"azurerm_sql_database": resourceArmSqlDatabase(),
"azurerm_sql_elasticpool": resourceArmSqlElasticPool(),
"azurerm_sql_firewall_rule": resourceArmSqlFirewallRule(),
Expand Down
274 changes: 274 additions & 0 deletions azurerm/resource_arm_scheduler_job_collection.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,274 @@
package azurerm

import (
"fmt"
"log"

"github.com/Azure/azure-sdk-for-go/services/scheduler/mgmt/2016-03-01/scheduler"

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

func resourceArmSchedulerJobCollection() *schema.Resource {
return &schema.Resource{
Create: resourceArmSchedulerJobCollectionCreateUpdate,
Read: resourceArmSchedulerJobCollectionRead,
Update: resourceArmSchedulerJobCollectionCreateUpdate,
Delete: resourceArmSchedulerJobCollectionDelete,

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

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

"location": locationSchema(),

"resource_group_name": resourceGroupNameSchema(),

"tags": tagsSchema(),

"sku": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
ValidateFunc: validation.StringInSlice([]string{
string(scheduler.Free),
string(scheduler.Standard),
string(scheduler.P10Premium),
string(scheduler.P20Premium),
}, true),
},

//optional
"state": {
Type: schema.TypeString,
Optional: true,
Default: string(scheduler.Enabled),
DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
ValidateFunc: validation.StringInSlice([]string{
string(scheduler.Enabled),
string(scheduler.Suspended),
string(scheduler.Disabled),
}, true),
},

"quota": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{

//max_job_occurrence doesn't seem to do anything and always remains empty

"max_job_count": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntAtLeast(0),
},

"max_recurrence_frequency": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
ValidateFunc: validation.StringInSlice([]string{
string(scheduler.Minute),
string(scheduler.Hour),
string(scheduler.Day),
string(scheduler.Week),
string(scheduler.Month),
}, true),
},

//this sets MaxRecurrance.Interval, and the documentation in the api states:
// Gets or sets the interval between retries.
"max_retry_interval": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntAtLeast(1), //changes depending on the frequency, unknown maximums
},
},
},
},
},
}
}

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

name := d.Get("name").(string)
location := d.Get("location").(string)
resourceGroup := d.Get("resource_group_name").(string)
tags := d.Get("tags").(map[string]interface{})

log.Printf("[DEBUG] Creating/updating Scheduler Job Collection %q (resource group %q)", name, resourceGroup)

collection := scheduler.JobCollectionDefinition{
Location: utils.String(location),
Tags: expandTags(tags),
Properties: &scheduler.JobCollectionProperties{
Sku: &scheduler.Sku{
Name: scheduler.SkuDefinition(d.Get("sku").(string)),
},
},
}

if state, ok := d.Get("state").(string); ok {
collection.Properties.State = scheduler.JobCollectionState(state)
}
collection.Properties.Quota = expandAzureArmSchedulerJobCollectionQuota(d)

//create job collection
collection, err := client.CreateOrUpdate(ctx, resourceGroup, name, collection)
if err != nil {
return fmt.Errorf("Error creating/updating Scheduler Job Collection %q (Resource Group %q): %+v", name, resourceGroup, err)
}

//ensure collection actually exists and we have the correct ID
collection, err = client.Get(ctx, resourceGroup, name)
if err != nil {
return fmt.Errorf("Error reading Scheduler Job Collection %q after create/update (Resource Group %q): %+v", name, resourceGroup, err)
}

d.SetId(*collection.ID)

return resourceArmSchedulerJobCollectionPopulate(d, resourceGroup, &collection)
}

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

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

name := id.Path["jobCollections"]
resourceGroup := id.ResourceGroup

log.Printf("[DEBUG] Reading Scheduler Job Collection %q (resource group %q)", name, resourceGroup)

collection, err := client.Get(ctx, resourceGroup, name)
if err != nil {
if utils.ResponseWasNotFound(collection.Response) {
d.SetId("")
return nil
}

return fmt.Errorf("Error making Read request on Scheduler Job Collection %q (Resource Group %q): %+v", name, resourceGroup, err)
}

return resourceArmSchedulerJobCollectionPopulate(d, resourceGroup, &collection)
}

func resourceArmSchedulerJobCollectionPopulate(d *schema.ResourceData, resourceGroup string, collection *scheduler.JobCollectionDefinition) error {

//standard properties
d.Set("name", collection.Name)
d.Set("location", azureRMNormalizeLocation(*collection.Location))
d.Set("resource_group_name", resourceGroup)
flattenAndSetTags(d, collection.Tags)

//resource specific
if properties := collection.Properties; properties != nil {
if sku := properties.Sku; sku != nil {
d.Set("sku", sku.Name)
}
d.Set("state", string(properties.State))

if err := d.Set("quota", flattenAzureArmSchedulerJobCollectionQuota(properties.Quota)); err != nil {
return fmt.Errorf("Error flattening quota for Job Collection %q (Resource Group %q): %+v", collection.Name, resourceGroup, err)
}
}

return nil
}

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

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

name := id.Path["jobCollections"]
resourceGroup := id.ResourceGroup

log.Printf("[DEBUG] Deleting Scheduler Job Collection %q (resource group %q)", name, resourceGroup)

future, err := client.Delete(ctx, resourceGroup, name)
if err != nil {
if !response.WasNotFound(future.Response()) {
return fmt.Errorf("Error issuing delete request for Scheduler Job Collection %q (Resource Group %q): %+v", name, resourceGroup, err)
}
}

err = future.WaitForCompletion(ctx, client.Client)
if err != nil {
if !response.WasNotFound(future.Response()) {
return fmt.Errorf("Error waiting for deletion of Scheduler Job Collection %q (Resource Group %q): %+v", name, resourceGroup, err)
}
}

return nil
}

func expandAzureArmSchedulerJobCollectionQuota(d *schema.ResourceData) *scheduler.JobCollectionQuota {
if qb, ok := d.Get("quota").([]interface{}); ok && len(qb) > 0 {
quota := scheduler.JobCollectionQuota{
MaxRecurrence: &scheduler.JobMaxRecurrence{},
}

quotaBlock := qb[0].(map[string]interface{})

if v, ok := quotaBlock["max_job_count"].(int); ok {
quota.MaxJobCount = utils.Int32(int32(v))
}
if v, ok := quotaBlock["max_recurrence_frequency"].(string); ok {
quota.MaxRecurrence.Frequency = scheduler.RecurrenceFrequency(v)
}
if v, ok := quotaBlock["max_retry_interval"].(int); ok {
quota.MaxRecurrence.Interval = utils.Int32(int32(v))
}

return &quota
}

return nil
}

func flattenAzureArmSchedulerJobCollectionQuota(quota *scheduler.JobCollectionQuota) []interface{} {

if quota == nil {
return nil
}

quotaBlock := make(map[string]interface{})

if v := quota.MaxJobCount; v != nil {
quotaBlock["max_job_count"] = *v
}
if recurrence := quota.MaxRecurrence; recurrence != nil {
if v := recurrence.Interval; v != nil {
quotaBlock["max_retry_interval"] = *v
}

quotaBlock["max_recurrence_frequency"] = string(recurrence.Frequency)
}

return []interface{}{quotaBlock}
}
Loading

0 comments on commit 21929db

Please sign in to comment.