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

Add resource azurerm_automation_job_schedule #3386

Merged
merged 23 commits into from
Oct 28, 2019
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
32 changes: 32 additions & 0 deletions azurerm/helpers/azure/automation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package azure

import (
"regexp"

"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)

// ValidateAutomationAccountName validates Automation Account names
func ValidateAutomationAccountName() schema.SchemaValidateFunc {
return validation.StringMatch(
regexp.MustCompile(`^[0-9a-zA-Z][-0-9a-zA-Z]{4,48}[0-9a-zA-Z]$`),
`The account name must start with a letter or number. The account name can contain letters, numbers, and dashes. The final character must be a letter or a number. The account name length must be from 6 to 50 characters.`,
)
}

// ValidateAutomationRunbookName validates Automation Account Runbook names
func ValidateAutomationRunbookName() schema.SchemaValidateFunc {
return validation.StringMatch(
regexp.MustCompile(`^[0-9a-zA-Z][-_0-9a-zA-Z]{0,62}$`),
`The name can contain only letters, numbers, underscores and dashes. The name must begin with a letter. The name must be less than 64 characters.`,
)
}

// ValidateAutomationScheduleName validates Automation Account Schedule names
func ValidateAutomationScheduleName() schema.SchemaValidateFunc {
return validation.StringMatch(
regexp.MustCompile(`^[^<>*%&:\\?.+\/]{0,127}[^<>*%&:\\?.+\/\s]$`),
`The name length must be from 1 to 128 characters. The name cannot contain special characters < > * % & : \ ? . + / and cannot end with a whitespace character.`,
)
}
5 changes: 5 additions & 0 deletions azurerm/internal/services/automation/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ type Client struct {
CredentialClient *automation.CredentialClient
DscConfigurationClient *automation.DscConfigurationClient
DscNodeConfigurationClient *automation.DscNodeConfigurationClient
JobScheduleClient *automation.JobScheduleClient
ModuleClient *automation.ModuleClient
RunbookClient *automation.RunbookClient
RunbookDraftClient *automation.RunbookDraftClient
Expand All @@ -34,6 +35,9 @@ func BuildClient(o *common.ClientOptions) *Client {
DscNodeConfigurationClient := automation.NewDscNodeConfigurationClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId)
o.ConfigureClient(&DscNodeConfigurationClient.Client, o.ResourceManagerAuthorizer)

JobScheduleClient := automation.NewJobScheduleClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId)
o.ConfigureClient(&JobScheduleClient.Client, o.ResourceManagerAuthorizer)

ModuleClient := automation.NewModuleClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId)
o.ConfigureClient(&ModuleClient.Client, o.ResourceManagerAuthorizer)

Expand All @@ -55,6 +59,7 @@ func BuildClient(o *common.ClientOptions) *Client {
CredentialClient: &CredentialClient,
DscConfigurationClient: &DscConfigurationClient,
DscNodeConfigurationClient: &DscNodeConfigurationClient,
JobScheduleClient: &JobScheduleClient,
ModuleClient: &ModuleClient,
RunbookClient: &RunbookClient,
RunbookDraftClient: &RunbookDraftClient,
Expand Down
1 change: 1 addition & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ func Provider() terraform.ResourceProvider {
"azurerm_automation_credential": resourceArmAutomationCredential(),
"azurerm_automation_dsc_configuration": resourceArmAutomationDscConfiguration(),
"azurerm_automation_dsc_nodeconfiguration": resourceArmAutomationDscNodeConfiguration(),
"azurerm_automation_job_schedule": resourceArmAutomationJobSchedule(),
"azurerm_automation_module": resourceArmAutomationModule(),
"azurerm_automation_runbook": resourceArmAutomationRunbook(),
"azurerm_automation_schedule": resourceArmAutomationSchedule(),
Expand Down
236 changes: 236 additions & 0 deletions azurerm/resource_arm_automation_job_schedule.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
package azurerm

import (
"fmt"
"log"
"strings"
"time"

"github.com/Azure/azure-sdk-for-go/services/automation/mgmt/2015-10-31/automation"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
uuid "github.com/satori/go.uuid"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func resourceArmAutomationJobSchedule() *schema.Resource {
return &schema.Resource{
Create: resourceArmAutomationJobScheduleCreate,
Read: resourceArmAutomationJobScheduleRead,
Delete: resourceArmAutomationJobScheduleDelete,

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

Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Read: schema.DefaultTimeout(5 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(30 * time.Minute),
},

Schema: map[string]*schema.Schema{

"resource_group_name": azure.SchemaResourceGroupName(),

"automation_account_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: azure.ValidateAutomationAccountName(),
},
draggeta marked this conversation as resolved.
Show resolved Hide resolved

"runbook_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: azure.ValidateAutomationRunbookName(),
},
draggeta marked this conversation as resolved.
Show resolved Hide resolved

"schedule_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: azure.ValidateAutomationScheduleName(),
},
draggeta marked this conversation as resolved.
Show resolved Hide resolved

"parameters": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
ValidateFunc: func(v interface{}, _ string) (warnings []string, errors []error) {
m := v.(map[string]interface{})

for k := range m {
if k != strings.ToLower(k) {
errors = append(errors, fmt.Errorf("Due to a bug in the implementation of Runbooks in Azure, the parameter names need to be specified in lowercase only. See: \"https://github.com/Azure/azure-sdk-for-go/issues/4780\" for more information."))
}
}

return warnings, errors
},
},

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

"job_schedule_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
}
}

func resourceArmAutomationJobScheduleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).Automation.JobScheduleClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*ArmClient).StopContext, d)
defer cancel()

log.Printf("[INFO] preparing arguments for AzureRM Automation Job Schedule creation.")

jobScheduleUUID := uuid.NewV4()
resGroup := d.Get("resource_group_name").(string)
accountName := d.Get("automation_account_name").(string)

runbookName := d.Get("runbook_name").(string)
scheduleName := d.Get("schedule_name").(string)

if requireResourcesToBeImported && d.IsNewResource() {
existing, err := client.Get(ctx, resGroup, accountName, jobScheduleUUID)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("Error checking for presence of existing Automation Job Schedule %q (Account %q / Resource Group %q): %s", jobScheduleUUID, accountName, resGroup, err)
}
}

if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_automation_job_schedule", *existing.ID)
}
}

parameters := automation.JobScheduleCreateParameters{
JobScheduleCreateProperties: &automation.JobScheduleCreateProperties{
Schedule: &automation.ScheduleAssociationProperty{
Name: &scheduleName,
},
Runbook: &automation.RunbookAssociationProperty{
Name: &runbookName,
},
},
}
properties := parameters.JobScheduleCreateProperties

// parameters to be passed into the runbook
if v, ok := d.GetOk("parameters"); ok {
jsParameters := make(map[string]*string)
for k, v := range v.(map[string]interface{}) {
value := v.(string)
jsParameters[k] = &value
}
properties.Parameters = jsParameters
}

if v, ok := d.GetOk("run_on"); ok {
value := v.(string)
properties.RunOn = &value
}

if _, err := client.Create(ctx, resGroup, accountName, jobScheduleUUID, parameters); err != nil {
return err
}

read, err := client.Get(ctx, resGroup, accountName, jobScheduleUUID)
if err != nil {
return err
}

if read.ID == nil {
return fmt.Errorf("Cannot read Automation Job Schedule '%s' (Account %q / Resource Group %s) ID", jobScheduleUUID, accountName, resGroup)
}

d.SetId(*read.ID)

return resourceArmAutomationJobScheduleRead(d, meta)
}

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

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

jobScheduleID := id.Path["jobSchedules"]
jobScheduleUUID := uuid.FromStringOrNil(jobScheduleID)
resGroup := id.ResourceGroup
accountName := id.Path["automationAccounts"]

resp, err := client.Get(ctx, resGroup, accountName, jobScheduleUUID)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
d.SetId("")
return nil
}

return fmt.Errorf("Error making Read request on AzureRM Automation Job Schedule '%s': %+v", jobScheduleUUID, err)
}

d.Set("job_schedule_id", resp.JobScheduleID)
d.Set("resource_group_name", resGroup)
d.Set("automation_account_name", accountName)
d.Set("runbook_name", resp.JobScheduleProperties.Runbook.Name)
d.Set("schedule_name", resp.JobScheduleProperties.Schedule.Name)

if v := resp.JobScheduleProperties.RunOn; v != nil {
d.Set("run_on", v)
}

if v := resp.JobScheduleProperties.Parameters; v != nil {
jsParameters := make(map[string]interface{})
for key, value := range v {
jsParameters[strings.ToLower(key)] = value
}
d.Set("parameters", jsParameters)
}

return nil
}

func resourceArmAutomationJobScheduleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).Automation.JobScheduleClient
ctx, cancel := timeouts.ForDelete(meta.(*ArmClient).StopContext, d)
defer cancel()

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

jobScheduleID := id.Path["jobSchedules"]
jobScheduleUUID := uuid.FromStringOrNil(jobScheduleID)
resGroup := id.ResourceGroup
accountName := id.Path["automationAccounts"]

resp, err := client.Delete(ctx, resGroup, accountName, jobScheduleUUID)
if err != nil {
if !utils.ResponseWasNotFound(resp) {
return fmt.Errorf("Error issuing AzureRM delete request for Automation Job Schedule '%s': %+v", jobScheduleUUID, err)
}
}

return nil
}
Loading