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 & Datasources: azurerm_automation_variable_[bool|datetime|string|int] #3310

Merged
merged 31 commits into from
May 10, 2019
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
63f2150
Register automation variable client.
Feb 18, 2019
bab63c4
Implement common parse value function for AutoVar
Apr 25, 2019
8406774
Updates to string variable
WodansSon Apr 25, 2019
4351476
Updated error msgs
WodansSon Apr 25, 2019
7438635
Fix build break
WodansSon Apr 25, 2019
5524afc
Persist RG name and AA name to state file
WodansSon Apr 25, 2019
0c7c1ed
Fix time skew issue
WodansSon Apr 25, 2019
3758c93
Add null variable resource
WodansSon Apr 25, 2019
8305a48
Added bool variable
WodansSon Apr 26, 2019
4468f36
Added azurerm_automation_int_variable
WodansSon Apr 26, 2019
9823ecb
Added datetime variable
WodansSon Apr 27, 2019
49ef0b0
Update azurerm/helpers/azure/automation_variable.go
katbyte Apr 29, 2019
3b6bfe8
Update website/docs/r/automation_bool_variable.html.markdown
katbyte Apr 29, 2019
972720b
Changes per PR comments
WodansSon May 1, 2019
e256005
Changes requested per PR comments
WodansSon May 2, 2019
223ef2a
Changes requested in PR
WodansSon May 7, 2019
f8fd819
Fix test cases
WodansSon May 8, 2019
4a61e04
Add support for data sources
WodansSon May 9, 2019
491e86c
Merge branch 'master' into resource_automation_variable
WodansSon May 9, 2019
8980a5c
Resolve conficts
WodansSon May 9, 2019
aac306e
addressed minor PR comment
katbyte May 10, 2019
e39b34c
put var type at the end of all names
katbyte May 10, 2019
e15f577
missed some file renames
katbyte May 10, 2019
23c1364
fixed tests
katbyte May 10, 2019
3bcc130
fixed test names to conform to new format
katbyte May 10, 2019
c12c1c4
Update azurerm/automation_variable.go
WodansSon May 10, 2019
86cda18
Update azurerm/helpers/azure/automation_variable.go
WodansSon May 10, 2019
b49b77e
Update azurerm/automation_variable.go
WodansSon May 10, 2019
d8dc65c
Update azurerm/helpers/azure/automation_variable.go
WodansSon May 10, 2019
3afaddc
fixed datasource doc file names and TOC
katbyte May 10, 2019
a44be20
Merge branch 'resource_automation_variable' of github.com:terraform-p…
katbyte May 10, 2019
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 @@ -102,6 +102,7 @@ type ArmClient struct {
automationRunbookClient automation.RunbookClient
automationRunbookDraftClient automation.RunbookDraftClient
automationScheduleClient automation.ScheduleClient
automationVariableClient automation.VariableClient

dnsClient dns.RecordSetsClient
zonesClient dns.ZonesClient
Expand Down Expand Up @@ -531,6 +532,10 @@ func (c *ArmClient) registerAutomationClients(endpoint, subscriptionId string, a
runbookDraftClient := automation.NewRunbookDraftClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&runbookDraftClient.Client, auth)
c.automationRunbookDraftClient = runbookDraftClient

variableClient := automation.NewVariableClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&variableClient.Client, auth)
c.automationVariableClient = variableClient
}

func (c *ArmClient) registerAuthentication(endpoint, graphEndpoint, subscriptionId, tenantId string, auth, graphAuth autorest.Authorizer) {
Expand Down
41 changes: 41 additions & 0 deletions azurerm/helpers/azure/automation_variable.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package azure

import (
"fmt"
"regexp"
"strconv"
"time"
)

func ParseAzureRmAutomationVariableValue(resource string, input *string) (interface{}, error) {
if input == nil {
if resource != "azurerm_automation_null_variable" {
WodansSon marked this conversation as resolved.
Show resolved Hide resolved
return nil, fmt.Errorf("Expected value \"nil\" to be %q, actual type is \"azurerm_automation_null_variable\"", resource)
WodansSon marked this conversation as resolved.
Show resolved Hide resolved
}
return nil, nil
}

var value interface{}
var err error
actualResource := "Unknown"
datePattern := regexp.MustCompile(`"\\/Date\((-?[0-9]+)\)\\/"`)
matches := datePattern.FindStringSubmatch(*input)
if len(matches) == 2 && matches[0] == *input {
WodansSon marked this conversation as resolved.
Show resolved Hide resolved
if ticks, err := strconv.ParseInt(matches[1], 10, 64); err == nil {
value = time.Unix(ticks/1000, ticks%1000*1000000).In(time.UTC)
actualResource = "azurerm_automation_datetime_variable"
}
} else if value, err = strconv.Unquote(*input); err == nil {
actualResource = "azurerm_automation_string_variable"
} else if value, err = strconv.ParseBool(*input); err == nil {
actualResource = "azurerm_automation_bool_variable"
} else if value, err = strconv.ParseInt(*input, 10, 32); err == nil {
value = int32(value.(int64))
actualResource = "azurerm_automation_int_variable"
}

if actualResource != resource {
return nil, fmt.Errorf("Expected value %q to be %q, actual type is %q", *input, resource, actualResource)
}
return value, nil
}
83 changes: 83 additions & 0 deletions azurerm/helpers/azure/automation_variable_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package azure

import (
"testing"
"time"
)

func TestParseAzureRmAutomationVariableValue(t *testing.T) {
type ExpectFunc func(interface{}) bool
cases := []struct {
Name string
Resource string
IsNil bool
Value string
HasError bool
ExpectValue interface{}
Expect ExpectFunc
}{
{
Name: "null variable",
Resource: "azurerm_automation_null_variable",
IsNil: true,
Value: "<nil>",
HasError: false,
ExpectValue: nil,
Expect: func(v interface{}) bool { return v == nil },
},
{
Name: "string variable",
Resource: "azurerm_automation_string_variable",
Value: "\"Test String\"",
HasError: false,
ExpectValue: "Test String",
Expect: func(v interface{}) bool { return v.(string) == "Test String" },
},
{
Name: "integer variable",
Resource: "azurerm_automation_int_variable",
Value: "135",
HasError: false,
ExpectValue: 135,
Expect: func(v interface{}) bool { return v.(int32) == 135 },
},
{
Name: "boolean variable",
Resource: "azurerm_automation_bool_variable",
Value: "true",
HasError: false,
ExpectValue: true,
Expect: func(v interface{}) bool { return v.(bool) == true },
},
{
Name: "datetime variable",
Resource: "azurerm_automation_datetime_variable",
Value: "\"\\/Date(1556142054074)\\/\"",
HasError: false,
ExpectValue: time.Date(2019, time.April, 24, 21, 40, 54, 74000000, time.UTC),
Expect: func(v interface{}) bool {
return v.(time.Time) == time.Date(2019, time.April, 24, 21, 40, 54, 74000000, time.UTC)
},
},
}

for _, tc := range cases {
t.Run(tc.Name, func(t *testing.T) {
value := &tc.Value
if tc.IsNil {
value = nil
}
actual, err := ParseAzureRmAutomationVariableValue(tc.Resource, value)
if tc.HasError && err == nil {
t.Fatalf("Expect parseAzureRmAutomationVariableValue to return error for resource %q and value %s", tc.Resource, tc.Value)
}
if !tc.HasError {
if err != nil {
t.Fatalf("Expect parseAzureRmAutomationVariableValue to return no error for resource %q and value %s, err: %+v", tc.Resource, tc.Value, err)
} else if !tc.Expect(actual) {
t.Fatalf("Expect parseAzureRmAutomationVariableValue to return %v instead of %v for resource %q and value %s", tc.ExpectValue, actual, tc.Resource, tc.Value)
}
}
})
}
}
5 changes: 5 additions & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,11 @@ func Provider() terraform.ResourceProvider {
"azurerm_automation_module": resourceArmAutomationModule(),
"azurerm_automation_runbook": resourceArmAutomationRunbook(),
"azurerm_automation_schedule": resourceArmAutomationSchedule(),
"azurerm_automation_bool_variable": resourceArmAutomationBoolVariable(),
"azurerm_automation_datetime_variable": resourceArmAutomationDatetimeVariable(),
"azurerm_automation_int_variable": resourceArmAutomationIntVariable(),
"azurerm_automation_null_variable": resourceArmAutomationNullVariable(),
"azurerm_automation_string_variable": resourceArmAutomationStringVariable(),
"azurerm_autoscale_setting": resourceArmAutoScaleSetting(),
"azurerm_availability_set": resourceArmAvailabilitySet(),
"azurerm_azuread_application": resourceArmActiveDirectoryApplication(),
Expand Down
169 changes: 169 additions & 0 deletions azurerm/resource_arm_automation_bool_variable.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
package azurerm

import (
"fmt"
"log"
"strconv"

"github.com/Azure/azure-sdk-for-go/services/automation/mgmt/2015-10-31/automation"
"github.com/hashicorp/terraform/helper/schema"
"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/helpers/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func resourceArmAutomationBoolVariable() *schema.Resource {
return &schema.Resource{
Create: resourceArmAutomationBoolVariableCreateUpdate,
Read: resourceArmAutomationBoolVariableRead,
Update: resourceArmAutomationBoolVariableCreateUpdate,
Delete: resourceArmAutomationBoolVariableDelete,

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

Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.NoEmptyStrings,
WodansSon marked this conversation as resolved.
Show resolved Hide resolved
},

"resource_group_name": resourceGroupNameSchema(),
WodansSon marked this conversation as resolved.
Show resolved Hide resolved

"automation_account_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.NoEmptyStrings,
WodansSon marked this conversation as resolved.
Show resolved Hide resolved
},

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

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

"value": {
katbyte marked this conversation as resolved.
Show resolved Hide resolved
Type: schema.TypeBool,
Optional: true,
WodansSon marked this conversation as resolved.
Show resolved Hide resolved
},
},
}
}

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

name := d.Get("name").(string)
resourceGroup := d.Get("resource_group_name").(string)
accountName := d.Get("automation_account_name").(string)

if requireResourcesToBeImported {
resp, err := client.Get(ctx, resourceGroup, accountName, name)
if err != nil {
if !utils.ResponseWasNotFound(resp.Response) {
return fmt.Errorf("Error checking for present of existing Automation Bool Variable %q (Automation Account Name %q / Resource Group %q): %+v", name, accountName, resourceGroup, err)
}
}
if !utils.ResponseWasNotFound(resp.Response) {
return tf.ImportAsExistsError("azurerm_automation_bool_variable", *resp.ID)
}
}

description := d.Get("description").(string)
encrypted := d.Get("encrypted").(bool)
value := strconv.FormatBool(d.Get("value").(bool))

parameters := automation.VariableCreateOrUpdateParameters{
Name: utils.String(name),
VariableCreateOrUpdateProperties: &automation.VariableCreateOrUpdateProperties{
Description: utils.String(description),
IsEncrypted: utils.Bool(encrypted),
Value: utils.String(value),
},
}

if _, err := client.CreateOrUpdate(ctx, resourceGroup, accountName, name, parameters); err != nil {
return fmt.Errorf("Error creating Automation Bool Variable %q (Automation Account Name %q / Resource Group %q): %+v", name, accountName, resourceGroup, err)
}

resp, err := client.Get(ctx, resourceGroup, accountName, name)
if err != nil {
return fmt.Errorf("Error retrieving Automation Bool Variable %q (Automation Account Name %q / Resource Group %q): %+v", name, accountName, resourceGroup, err)
}
if resp.ID == nil {
return fmt.Errorf("Cannot read Automation Bool Variable %q (Automation Account Name %q / Resource Group %q) ID", name, accountName, resourceGroup)
}
d.SetId(*resp.ID)

return resourceArmAutomationBoolVariableRead(d, meta)
}

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

id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
accountName := id.Path["automationAccounts"]
name := id.Path["variables"]

resp, err := client.Get(ctx, resourceGroup, accountName, name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[INFO] Automation Bool Variable %q does not exist - removing from state", d.Id())
d.SetId("")
return nil
}
return fmt.Errorf("Error reading Automation Bool Variable %q (Automation Account Name %q / Resource Group %q): %+v", name, accountName, resourceGroup, err)
}

d.Set("name", resp.Name)
d.Set("resource_group_name", resourceGroup)
d.Set("automation_account_name", accountName)
if properties := resp.VariableProperties; properties != nil {
d.Set("description", properties.Description)
d.Set("encrypted", properties.IsEncrypted)
if !d.Get("encrypted").(bool) {
value, err := azure.ParseAzureRmAutomationVariableValue("azurerm_automation_bool_variable", properties.Value)
if err != nil {
return err
}
d.Set("value", value)
}
}

return nil
}

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

id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
accountName := id.Path["automationAccounts"]
name := id.Path["variables"]

if _, err := client.Delete(ctx, resourceGroup, accountName, name); err != nil {
return fmt.Errorf("Error deleting Automation Bool Variable %q (Automation Account Name %q / Resource Group %q): %+v", name, accountName, resourceGroup, err)
}

return nil
}
Loading