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 managed identity in azurerm_automation_account resource #15072

Merged
merged 6 commits into from
Feb 4, 2022
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
183 changes: 134 additions & 49 deletions internal/services/automation/automation_account_resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import (
"log"
"time"

"github.com/Azure/azure-sdk-for-go/services/preview/automation/mgmt/2018-06-30-preview/automation"
"github.com/hashicorp/terraform-provider-azurerm/helpers/azure"
"github.com/Azure/azure-sdk-for-go/services/preview/automation/mgmt/2020-01-13-preview/automation"
"github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema"
"github.com/hashicorp/go-azure-helpers/resourcemanager/identity"
"github.com/hashicorp/go-azure-helpers/resourcemanager/location"
"github.com/hashicorp/terraform-provider-azurerm/helpers/tf"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/automation/parse"
Expand All @@ -20,9 +22,9 @@ import (

func resourceAutomationAccount() *pluginsdk.Resource {
return &pluginsdk.Resource{
Create: resourceAutomationAccountCreateUpdate,
Create: resourceAutomationAccountCreate,
Read: resourceAutomationAccountRead,
Update: resourceAutomationAccountCreateUpdate,
Update: resourceAutomationAccountUpdate,
Delete: resourceAutomationAccountDelete,
Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error {
_, err := parse.AutomationAccountID(id)
Expand All @@ -44,19 +46,21 @@ func resourceAutomationAccount() *pluginsdk.Resource {
ValidateFunc: validate.AutomationAccount(),
},

"location": azure.SchemaLocation(),
"location": commonschema.Location(),

"resource_group_name": azure.SchemaResourceGroupName(),
"resource_group_name": commonschema.ResourceGroupName(),

"sku_name": {
Type: pluginsdk.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
string(automation.Basic),
string(automation.Free),
string(automation.SkuNameEnumBasic),
string(automation.SkuNameEnumFree),
}, false),
},

"identity": commonschema.SystemAssignedUserAssignedIdentityOptional(),

"tags": tags.Schema(),

"dsc_server_endpoint": {
Expand All @@ -75,48 +79,74 @@ func resourceAutomationAccount() *pluginsdk.Resource {
}
}

func resourceAutomationAccountCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
func resourceAutomationAccountCreate(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Automation.AccountClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d)
defer cancel()

sku := automation.Sku{
Name: automation.SkuNameEnum(d.Get("sku_name").(string)),
}

log.Printf("[INFO] preparing arguments for Automation Account create/update.")

id := parse.NewAutomationAccountID(client.SubscriptionID, d.Get("resource_group_name").(string), d.Get("name").(string))

if d.IsNewResource() {
existing, err := client.Get(ctx, id.ResourceGroup, id.Name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("checking for presence of existing %s: %s", id, err)
}
}

id := parse.NewAutomationAccountID(subscriptionId, d.Get("resource_group_name").(string), d.Get("name").(string))
existing, err := client.Get(ctx, id.ResourceGroup, id.Name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return tf.ImportAsExistsError("azurerm_automation_account", id.ID())
return fmt.Errorf("checking for presence of existing %s: %+v", id, err)
}
}

location := azure.NormalizeLocation(d.Get("location").(string))
t := d.Get("tags").(map[string]interface{})
if !utils.ResponseWasNotFound(existing.Response) {
return tf.ImportAsExistsError("azurerm_automation_account", id.ID())
}

identity, err := expandAutomationAccountIdentity(d.Get("identity").([]interface{}), true)
if err != nil {
return fmt.Errorf("expanding `identity`: %+v", err)
}
parameters := automation.AccountCreateOrUpdateParameters{
AccountCreateOrUpdateProperties: &automation.AccountCreateOrUpdateProperties{
Sku: &sku,
Sku: &automation.Sku{
Name: automation.SkuNameEnum(d.Get("sku_name").(string)),
},
},
Location: utils.String(location),
Tags: tags.Expand(t),
Location: utils.String(location.Normalize(d.Get("location").(string))),
Identity: identity,
Tags: tags.Expand(d.Get("tags").(map[string]interface{})),
}

if _, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.Name, parameters); err != nil {
return fmt.Errorf("creating/updating %s: %+v", id, err)
return fmt.Errorf("creating %s: %+v", id, err)
}

d.SetId(id.ID())
return resourceAutomationAccountRead(d, meta)
}

func resourceAutomationAccountUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Automation.AccountClient
ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()

id, err := parse.AutomationAccountID(d.Id())
if err != nil {
return err
}
identity, err := expandAutomationAccountIdentity(d.Get("identity").([]interface{}), false)
if err != nil {
return fmt.Errorf("expanding `identity`: %+v", err)
}
parameters := automation.AccountUpdateParameters{
AccountUpdateProperties: &automation.AccountUpdateProperties{
Sku: &automation.Sku{
Name: automation.SkuNameEnum(d.Get("sku_name").(string)),
},
},
Location: utils.String(location.Normalize(d.Get("location").(string))),
Identity: identity,
Tags: tags.Expand(d.Get("tags").(map[string]interface{})),
}

if _, err := client.Update(ctx, id.ResourceGroup, id.Name, parameters); err != nil {
return fmt.Errorf("updating %s: %+v", *id, err)
}

return resourceAutomationAccountRead(d, meta)
}
Expand All @@ -135,50 +165,50 @@ func resourceAutomationAccountRead(d *pluginsdk.ResourceData, meta interface{})
resp, err := client.Get(ctx, id.ResourceGroup, id.Name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[DEBUG] Automation Account %q was not found in Resource Group %q - removing from state!", id.Name, id.ResourceGroup)
log.Printf("[DEBUG] %s was not found - removing from state!", *id)
d.SetId("")
return nil
}

return fmt.Errorf("making Read request on Automation Account %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
return fmt.Errorf("retrieving %s: %+v", *id, err)
}

keysResp, err := registrationClient.Get(ctx, id.ResourceGroup, id.Name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[DEBUG] Agent Registration Info for Automation Account %q was not found in Resource Group %q - removing from state!", id.Name, id.ResourceGroup)
log.Printf("[DEBUG] Agent Registration Info for %s was not found - removing from state!", *id)
d.SetId("")
return nil
}

return fmt.Errorf("making Read request for Agent Registration Info for Automation Account %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
return fmt.Errorf("retrieving Registration Info for %s: %+v", *id, err)
}

d.Set("name", id.Name)
d.Set("resource_group_name", id.ResourceGroup)
if location := resp.Location; location != nil {
d.Set("location", azure.NormalizeLocation(*location))
}
d.Set("location", location.NormalizeNilable(resp.Location))

skuName := ""
if sku := resp.Sku; sku != nil {
if err := d.Set("sku_name", string(sku.Name)); err != nil {
return fmt.Errorf("setting 'sku_name': %+v", err)
}
} else {
return fmt.Errorf("making Read request on Automation Account %q (Resource Group %q): Unable to retrieve 'sku' value", id.Name, id.ResourceGroup)
skuName = string(resp.Sku.Name)
}
d.Set("sku_name", skuName)

d.Set("dsc_server_endpoint", keysResp.Endpoint)
if keys := keysResp.Keys; keys != nil {
d.Set("dsc_primary_access_key", keys.Primary)
d.Set("dsc_secondary_access_key", keys.Secondary)
}

if t := resp.Tags; t != nil {
return tags.FlattenAndSet(d, t)
identity, err := flattenAutomationAccountIdentity(resp.Identity)
if err != nil {
return fmt.Errorf("flattening `identity`: %+v", err)
}
if err := d.Set("identity", identity); err != nil {
return fmt.Errorf("setting `identity`: %+v", err)
}

return nil
return tags.FlattenAndSet(d, resp.Tags)
}

func resourceAutomationAccountDelete(d *pluginsdk.ResourceData, meta interface{}) error {
Expand All @@ -197,8 +227,63 @@ func resourceAutomationAccountDelete(d *pluginsdk.ResourceData, meta interface{}
return nil
}

return fmt.Errorf("issuing AzureRM delete request for Automation Account '%s': %+v", id.Name, err)
return fmt.Errorf("deleting %s: %+v", *id, err)
}

return nil
}

func expandAutomationAccountIdentity(input []interface{}, newResource bool) (*automation.Identity, error) {
expanded, err := identity.ExpandSystemAndUserAssignedMap(input)
if err != nil {
return nil, err
}

if newResource && expanded.Type == identity.TypeNone {
return nil, nil
}

out := automation.Identity{
Type: automation.ResourceIdentityType(string(expanded.Type)),
}

if len(expanded.IdentityIds) > 0 {
ids := make(map[string]*automation.IdentityUserAssignedIdentitiesValue)

for k := range expanded.IdentityIds {
ids[k] = &automation.IdentityUserAssignedIdentitiesValue{
// intentionally empty
}
}

out.UserAssignedIdentities = ids
}

return &out, nil
}

func flattenAutomationAccountIdentity(input *automation.Identity) (*[]interface{}, error) {
var transformed *identity.SystemAndUserAssignedMap
if input != nil {
transformed = &identity.SystemAndUserAssignedMap{
Type: identity.Type(string(input.Type)),
IdentityIds: make(map[string]identity.UserAssignedIdentityDetails),
}
if input.PrincipalID != nil {
transformed.PrincipalId = *input.PrincipalID
}
if input.TenantID != nil {
transformed.TenantId = *input.TenantID
}
if input.UserAssignedIdentities != nil {
for k, v := range input.UserAssignedIdentities {
transformed.IdentityIds[k] = identity.UserAssignedIdentityDetails{
ClientId: v.ClientID,
PrincipalId: v.PrincipalID,
}
}
}
}

return identity.FlattenSystemAndUserAssignedMap(transformed)
}
Loading