Skip to content

Commit

Permalink
Auto generate backend key based on component name for azurerm (#95)
Browse files Browse the repository at this point in the history
* Auto generate backend key based on component name for azurerm

* Add example of azurerm backend
  • Loading branch information
lukeorellana committed Dec 22, 2021
1 parent 89a2ad0 commit 2369939
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
8 changes: 7 additions & 1 deletion examples/complete/stacks/globals/globals.yaml
Expand Up @@ -4,7 +4,7 @@ vars:
terraform:
vars: {}

backend_type: s3 # s3, remote, vault, static, etc.
backend_type: s3 # s3, remote, vault, static, azurerm, etc.
backend:
s3:
encrypt: true
Expand All @@ -14,6 +14,12 @@ terraform:
acl: "bucket-owner-full-control"
region: "us-east-2"
role_arn: null
azurerm:
subscription_id: 88888-8888-8888-8888-8888888888
resource_group_name: rg-terraform-state
storage_account_name: staterraformstate
container_name: dev-tfstate
key: dev.atmos
remote:
vault:

Expand Down
33 changes: 28 additions & 5 deletions pkg/stack/stack_processor.go
Expand Up @@ -2,17 +2,18 @@ package stack

import (
"fmt"
"path"
"path/filepath"
"sort"
"strings"
"sync"

c "github.com/cloudposse/atmos/pkg/convert"
g "github.com/cloudposse/atmos/pkg/globals"
m "github.com/cloudposse/atmos/pkg/merge"
"github.com/cloudposse/atmos/pkg/utils"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
"path"
"path/filepath"
"sort"
"strings"
"sync"
)

var (
Expand Down Expand Up @@ -478,6 +479,28 @@ func ProcessConfig(
}
}

// Check if component `backend` section has `key` for `azurerm` backend type
// If it does not, use the component name instead and format it with the global backend key name to auto generate a unique tf state key
// The backend state file will be formated like so: {global key name}/{component name}.terraform.tfstate
if finalComponentBackendType == "azurerm" {
if azurerm, ok2 := componentBackendSection["azurerm"].(map[interface{}]interface{}); !ok2 {
if _, ok2 := azurerm["key"].(string); !ok2 {
azureKeyPrefixComponent := component
baseKeyName := ""
if baseComponentName != "" {
azureKeyPrefixComponent = baseComponentName
}
if azurerm, ok2 := globalBackendSection["azurerm"].(map[interface{}]interface{}); ok2 {
baseKeyName = azurerm["key"].(string)
}
componentKeyName := strings.Replace(azureKeyPrefixComponent, "/", "-", -1)
finalComponentBackend["key"] = fmt.Sprintf("%s/%s.terraform.tfstate", baseKeyName, componentKeyName)

}
}

}

// Final remote state backend
finalComponentRemoteStateBackendType := finalComponentBackendType
if len(globalRemoteStateBackendType) > 0 {
Expand Down

0 comments on commit 2369939

Please sign in to comment.