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

Support for Azure Batch - Account #2428

Merged
merged 13 commits into from
Dec 14, 2018
11 changes: 11 additions & 0 deletions azurerm/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/Azure/azure-sdk-for-go/profiles/2017-03-09/resources/mgmt/resources"
appinsights "github.com/Azure/azure-sdk-for-go/services/appinsights/mgmt/2015-05-01/insights"
"github.com/Azure/azure-sdk-for-go/services/automation/mgmt/2015-10-31/automation"
"github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch"
"github.com/Azure/azure-sdk-for-go/services/cdn/mgmt/2017-10-12/cdn"
"github.com/Azure/azure-sdk-for-go/services/cognitiveservices/mgmt/2017-04-18/cognitiveservices"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-06-01/compute"
Expand Down Expand Up @@ -133,6 +134,9 @@ type ArmClient struct {
// Autoscale Settings
autoscaleSettingsClient insights.AutoscaleSettingsClient

// Batch
batchAccountClient batch.AccountClient

// CDN
cdnCustomDomainsClient cdn.CustomDomainsClient
cdnEndpointsClient cdn.EndpointsClient
Expand Down Expand Up @@ -415,6 +419,7 @@ func getArmClient(c *authentication.Config, skipProviderRegistration bool) (*Arm
client.registerAppInsightsClients(endpoint, c.SubscriptionID, auth)
client.registerAutomationClients(endpoint, c.SubscriptionID, auth)
client.registerAuthentication(endpoint, graphEndpoint, c.SubscriptionID, c.TenantID, auth, graphAuth)
client.registerBatchClients(endpoint, c.SubscriptionID, auth)
client.registerCDNClients(endpoint, c.SubscriptionID, auth)
client.registerCognitiveServiceClients(endpoint, c.SubscriptionID, auth)
client.registerComputeClients(endpoint, c.SubscriptionID, auth)
Expand Down Expand Up @@ -523,6 +528,12 @@ func (c *ArmClient) registerAuthentication(endpoint, graphEndpoint, subscription
c.servicePrincipalsClient = servicePrincipalsClient
}

func (c *ArmClient) registerBatchClients(endpoint, subscriptionId string, auth autorest.Authorizer) {
batchAccount := batch.NewAccountClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&batchAccount.Client, auth)
c.batchAccountClient = batchAccount
}

func (c *ArmClient) registerCDNClients(endpoint, subscriptionId string, auth autorest.Authorizer) {
customDomainsClient := cdn.NewCustomDomainsClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&customDomainsClient.Client, auth)
Expand Down
74 changes: 74 additions & 0 deletions azurerm/data_source_batch_account.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package azurerm

import (
"fmt"

"github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch"

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

func dataSourceArmBatchAccount() *schema.Resource {
return &schema.Resource{
Read: dataSourceArmBatchAccountRead,

Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateAzureRMBatchAccountName,
},
"resource_group_name": resourceGroupNameDiffSuppressSchema(),
tombuildsstuff marked this conversation as resolved.
Show resolved Hide resolved
"location": locationForDataSourceSchema(),
"storage_account_id": {
Type: schema.TypeString,
Computed: true,
},
"pool_allocation_mode": {
Type: schema.TypeString,
Optional: true,
Default: string(batch.BatchService),
DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
ValidateFunc: validation.StringInSlice([]string{
string(batch.BatchService),
string(batch.UserSubscription),
}, true),
Copy link
Contributor

Choose a reason for hiding this comment

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

I think this field should just have Type+Computed?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Hmm, I am not sure to understand why this field should be marked as Computed? It should be specified in the configuration.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ok sorry, I was looking on the resource, not the datasource :-)

Copy link
Contributor

Choose a reason for hiding this comment

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

so this is specific to the Data Source where whilst this information will be returned it can't be set (since we only obtain the Batch Account using the Name & Resource Group - the other fields are outputs)

},
"tags": tagsForDataSourceSchema(),
},
}
}

func dataSourceArmBatchAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).batchAccountClient

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

ctx := meta.(*ArmClient).StopContext
resp, err := client.Get(ctx, resourceGroup, name)

if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
return fmt.Errorf("Error: Batch account %q (Resource Group %q) was not found", name, resourceGroup)
}
return fmt.Errorf("Error making Read request on AzureRM Batch account %q: %+v", name, err)
}

// todo : fetch properties

d.SetId(*resp.ID)

d.Set("name", name)
d.Set("resource_group_name", resourceGroup)
if location := resp.Location; location != nil {
d.Set("location", azureRMNormalizeLocation(*location))
}

flattenAndSetTags(d, resp.Tags)

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

import (
"fmt"
"testing"

"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)

func TestAccDataSourceAzureRMBatchAccount_basic(t *testing.T) {
katbyte marked this conversation as resolved.
Show resolved Hide resolved
dataSourceName := "data.azurerm_batch_account.test"
ri := acctest.RandInt()
name := fmt.Sprintf("acctestbatchaccount%d", ri)
location := testLocation()
config := testAccDataSourceAzureRMBatchAccount_basic(name, location)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: config,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(dataSourceName, "name", name),
resource.TestCheckResourceAttr(dataSourceName, "location", azureRMNormalizeLocation(location)),
resource.TestCheckResourceAttr(dataSourceName, "tags.%", "1"),
resource.TestCheckResourceAttr(dataSourceName, "tags.env", "test"),
),
},
},
})
}

func testAccDataSourceAzureRMBatchAccount_basic(name string, location string) string {
return fmt.Sprintf(`
resource "azurerm_batch_account" "test" {
name = "%s"
location = "%s"
tombuildsstuff marked this conversation as resolved.
Show resolved Hide resolved

tags {
env = "test"
}
}

data "azurerm_batch_account" "test" {
name = "${azurerm_batch_account.test.name}"
}
tombuildsstuff marked this conversation as resolved.
Show resolved Hide resolved
`, name, location)
}
2 changes: 2 additions & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ func Provider() terraform.ResourceProvider {
"azurerm_application_security_group": dataSourceArmApplicationSecurityGroup(),
"azurerm_app_service": dataSourceArmAppService(),
"azurerm_app_service_plan": dataSourceAppServicePlan(),
"azurerm_batch_account": dataSourceArmBatchAccount(),
"azurerm_builtin_role_definition": dataSourceArmBuiltInRoleDefinition(),
"azurerm_cdn_profile": dataSourceArmCdnProfile(),
"azurerm_client_config": dataSourceArmClientConfig(),
Expand Down Expand Up @@ -147,6 +148,7 @@ func Provider() terraform.ResourceProvider {
"azurerm_automation_schedule": resourceArmAutomationSchedule(),
"azurerm_autoscale_setting": resourceArmAutoScaleSetting(),
"azurerm_availability_set": resourceArmAvailabilitySet(),
"azurerm_batch_account": resourceArmBatchAccount(),
"azurerm_cdn_endpoint": resourceArmCdnEndpoint(),
"azurerm_cdn_profile": resourceArmCdnProfile(),
"azurerm_cognitive_account": resourceArmCognitiveAccount(),
Expand Down
175 changes: 175 additions & 0 deletions azurerm/resource_arm_batch_account.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
package azurerm

import (
"fmt"
"regexp"

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

func resourceArmBatchAccount() *schema.Resource {
return &schema.Resource{
Create: resourceArmBatchAccountCreate,
Read: resourceArmBatchAccountRead,
Update: resourceArmBatchAccountUpdate,
Delete: resourceArmBatchAccountDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateAzureRMBatchAccountName,
},
"resource_group_name": resourceGroupNameDiffSuppressSchema(),
tombuildsstuff marked this conversation as resolved.
Show resolved Hide resolved
"location": locationSchema(),
"storage_account_id": {
Type: schema.TypeString,
Optional: true,
jcorioland marked this conversation as resolved.
Show resolved Hide resolved
},
"pool_allocation_mode": {
Type: schema.TypeString,
Optional: true,
Default: string(batch.BatchService),
DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
ValidateFunc: validation.StringInSlice([]string{
string(batch.BatchService),
string(batch.UserSubscription),
}, true),
jcorioland marked this conversation as resolved.
Show resolved Hide resolved
},
"tags": tagsSchema(),
},
}
}

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

resourceGroupName := d.Get("resource_group_name").(string)
name := d.Get("name").(string)
location := azureRMNormalizeLocation(d.Get("location").(string))
storageAccountId := d.Get("storage_account_id").(string)
poolAllocationMode := d.Get("pool_allocation_mode").(string)
tags := d.Get("tags").(map[string]interface{})

parameters := batch.AccountCreateParameters{
Location: &location,
AccountCreateProperties: &batch.AccountCreateProperties{
AutoStorage: &batch.AutoStorageBaseProperties{
StorageAccountID: &storageAccountId,
},
PoolAllocationMode: batch.PoolAllocationMode(poolAllocationMode),
},
Tags: expandTags(tags),
}

future, err := client.Create(ctx, resourceGroupName, name, parameters)
if err != nil {
return fmt.Errorf("Error creating Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err)
}

err = future.WaitForCompletionRef(ctx, client.Client)
if err != nil {
tombuildsstuff marked this conversation as resolved.
Show resolved Hide resolved
return fmt.Errorf("Error waiting for creation of Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err)
}

read, err := client.Get(ctx, resourceGroupName, name)
if err != nil {
return fmt.Errorf("Error retrieving Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err)
}

if read.ID == nil {
return fmt.Errorf("Cannot read Batch account %q (resource group %q) ID", name, resourceGroupName)
}

d.SetId(*read.ID)

return resourceArmBatchAccountRead(d, meta)
}

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

id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
name := id.Path["batchAccounts"]
resourceGroupName := id.ResourceGroup

resp, err := client.Get(ctx, resourceGroupName, name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
d.SetId("")
jcorioland marked this conversation as resolved.
Show resolved Hide resolved
jcorioland marked this conversation as resolved.
Show resolved Hide resolved
return nil
}
return fmt.Errorf("Error reading the state of Batch account %q: %+v", name, err)
}

d.Set("name", resp.Name)
d.Set("resource_group_name", resourceGroupName)
d.Set("location", resp.Location)
jcorioland marked this conversation as resolved.
Show resolved Hide resolved
d.Set("pool_allocation_mode", resp.PoolAllocationMode)

if resp.AutoStorage != nil {
d.Set("storage_acount_id", resp.AutoStorage.StorageAccountID)
}
katbyte marked this conversation as resolved.
Show resolved Hide resolved

flattenAndSetTags(d, resp.Tags)

return nil
}

func resourceArmBatchAccountUpdate(d *schema.ResourceData, meta interface{}) error {
return nil
}

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

id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
name := id.Path["batchAccounts"]
resourceGroupName := id.ResourceGroup

future, err := client.Delete(ctx, resourceGroupName, name)
if err != nil {
return fmt.Errorf("Error deleting Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err)
}

err = future.WaitForCompletionRef(ctx, client.Client)
if err != nil {
return fmt.Errorf("Error waiting for deletion of Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err)
}

return nil
}

func validateAzureRMBatchAccountName(v interface{}, k string) (warnings []string, errors []error) {
value := v.(string)
if !regexp.MustCompile(`^[a-z0-9]+$`).MatchString(value) {
errors = append(errors, fmt.Errorf(
"lowercase letters and numbers only are allowed in %q: %q", k, value))
tombuildsstuff marked this conversation as resolved.
Show resolved Hide resolved
}

if 3 > len(value) {
errors = append(errors, fmt.Errorf("%q cannot be less than 3 characters: %q", k, value))
}

if len(value) > 24 {
errors = append(errors, fmt.Errorf("%q cannot be longer than 24 characters: %q %d", k, value, len(value)))
}

return warnings, errors
}
Loading