ResolveTemplate resolves a template to a string using the given data.
(tmpl string, data TemplateData, errOnMissingTemplKeys bool)
| 212 | |
| 213 | // ResolveTemplate resolves a template to a string using the given data. |
| 214 | func ResolveTemplate(tmpl string, data TemplateData, errOnMissingTemplKeys bool) (string, error) { |
| 215 | // Base func map |
| 216 | funcMap := newFuncMap(data.Environment, data.State) |
| 217 | |
| 218 | // Add no-ops |
| 219 | funcMap["configure"] = func(parts ...string) error { return nil } |
| 220 | funcMap["dependency"] = func(parts ...string) error { return nil } |
| 221 | |
| 222 | // Add extra funcs |
| 223 | for k, v := range data.ExtraFuncs { |
| 224 | funcMap[k] = v |
| 225 | } |
| 226 | |
| 227 | // Add func to resolve a "ref" |
| 228 | funcMap["ref"] = func(parts ...string) (string, error) { |
| 229 | // Parse the resource name |
| 230 | name, err := resourceNameFromArgs(parts...) |
| 231 | if err != nil { |
| 232 | return "", fmt.Errorf(`invalid "ref" input: %w`, err) |
| 233 | } |
| 234 | |
| 235 | // Resolve the ref |
| 236 | ref, err := data.Resolve(name) |
| 237 | if err != nil { |
| 238 | return "", fmt.Errorf(`function "ref" failed: %w`, err) |
| 239 | } |
| 240 | |
| 241 | // Return formatted as a map |
| 242 | return ref, nil |
| 243 | } |
| 244 | |
| 245 | // Add func to lookup another resource |
| 246 | funcMap["lookup"] = func(parts ...string) (map[string]any, error) { |
| 247 | // Support is optional |
| 248 | if data.Lookup == nil { |
| 249 | return nil, fmt.Errorf(`function "lookup" is not supported in this context`) |
| 250 | } |
| 251 | |
| 252 | // Parse the resource name |
| 253 | name, err := resourceNameFromArgs(parts...) |
| 254 | if err != nil { |
| 255 | return nil, fmt.Errorf(`invalid "lookup" input: %w`, err) |
| 256 | } |
| 257 | |
| 258 | // Lookup the resource |
| 259 | resource, err := data.Lookup(name) |
| 260 | if err != nil { |
| 261 | return nil, fmt.Errorf(`function "lookup" failed: %w`, err) |
| 262 | } |
| 263 | |
| 264 | // Return formatted as a map |
| 265 | return map[string]any{ |
| 266 | "meta": resource.Meta, |
| 267 | "spec": resource.Spec, |
| 268 | "state": resource.State, |
| 269 | }, nil |
| 270 | } |
| 271 |