Get name of the variable with method #1220
              
                
                  
                  
                    Answered
                  
                  by
                    bioball
                  
              
          
                  
                    
                      dshatokhin
                    
                  
                
                  asked this question in
                Q&A
              
            -
| 
         Hi! I'm trying to define a method for outputting the the variable name with as a string, with some additions: class Variable {
  type: String?
  default: String?
  function format(): String = "something here"
}
vm_size = new Variable {
  type = "string"
  default = "1xCPU-1GB"
}
formatted_variable_name = vm_size.format()
// formatted_variable_name == "${var.vm_size}"Reading the package docs for   | 
  
Beta Was this translation helpful? Give feedback.
      
      
          Answered by
          
            bioball
          
      
      
        Sep 29, 2025 
      
    
    Replies: 1 comment 1 reply
-
| 
         You'd have to pass the name in somehow to class  The simplest approach with the least amount of magic is to pass it in explicitly: class Variable {
  type: String?
  default: String?
  name: String
  function format(): String = "${var.\(name)}"
}
vm_size = new Variable {
  type = "string"
  default = "1xCPU-1GB"
  name = "vm_size"
}
formatted_variable_name = vm_size.format()
// formatted_variable_name == "${var.vm_size}"However, there's definitely ways to add some "magic" to fill this in. For example, here's an approach that uses  class Variable {
  type: String?
  default: String?
  name: String
  function formatted() = "${var.\(name)}"
}
vm_size: Variable = new {
  type = "string"
  default = "1xCPU-1GB"
}
// create a version of this module where all `Variable` values have a `name` filled in based
// on the propertyy name.
local hydratedVars: module = 
  module
    .toMap()
    .mapValues((key, value) ->
      if (value is Variable) (value) { name = key }
      else value
    )
  .toTyped(module.getClass())
output {
  // set the module's output to the hydrated module
  value = hydratedVars
} | 
  
Beta Was this translation helpful? Give feedback.
                  
                    1 reply
                  
                
            
      Answer selected by
        dshatokhin
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
        
    
You'd have to pass the name in somehow to class
Variable.The simplest approach with the least amount of magic is to pass it in explicitly:
However, there's definitely ways to add some "magic" to fill this in. For example, here's an approach that uses
toMap():