Skip to content

Instantly share code, notes, and snippets.

@carljavier
Last active November 16, 2022 20:15
Show Gist options
  • Save carljavier/02438d8c3aa4f98d18e326e523407e29 to your computer and use it in GitHub Desktop.
Save carljavier/02438d8c3aa4f98d18e326e523407e29 to your computer and use it in GitHub Desktop.
Viper Configs in HCL

Using HCL configurations with Viper

Example HCL config file

name="blah"
foo="bar"

profile "site1" {
    api_url    = "https://api.site1.com/client"
    api_key    = "key"
    secret_key = "secret"
}

profile "site2" {
    api_url    = "https://api.site2.com/client"
    api_key    = "key"
    secret_key = "secret"
}

"list" = ["item1", "item2", "item3"]
"map" = {
  "key" = "value"
}


"nested_map" "map" {
  "key" = "value"
  "list" = ["item1", "item2", "item3"]
}

Hacky way

The following is probably a hacky way of doing it..I do think there is a cleaner way to get these values by using structs and the viper.unmarshal() function(TBD).

Get Key Value Pair

hclKeyValue := viper.Get("foo")
fmt.Println("\n\nhclKeyValue is: ", hclKeyValue)

Get List

hclList := viper.Get("list")
fmt.Printf("hclList is: %T\n\n", hclList.([]interface{})[2])

Get Map

hclMap := viper.Get("map")
fmt.Println("\n\nhclMap is: ", hclMap.([]map[string]interface{})[0]["key"])

Get Nested Map

hclNestedMap := viper.Get("nested_map")
fmt.Println("\n\nhclNestedMap is Key: ", hclNestedMap.([]map[string]interface{})[0]["key"])
fmt.Println("\n\nhclNestedMap is List: ", hclNestedMap.([]map[string]interface{})[0]["list"])

Get Profile Map

hclProfiles := viper.Get("profile")
fmt.Println("\n\nhclProfiles are: ", hclProfiles.([]map[string]interface{}))
fmt.Println("\n\nhclProfiles first slice: ", hclProfiles.([]map[string]interface{})[0])
fmt.Println("\n\nhclProfiles first slice/value: ", hclProfiles.([]map[string]interface{})[0]["site1"].([]map[string]interface{})[0]["api_url"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment