Can we parse a terraform "variables.tf" file in Java? If so how to implement the same

Viewed 836

Please find the Sample snippet of Variable.tf file, I want to fetch only the subscription_id, plan_id, user_id. I don't want to fetch location, since it already have default value set.

variable "subscription_id" {
description = "My subscription id"
}

variable "plan_id" {
description = "My tenant id"
}

variable "user_id" {
description = "My user id"
}

variable "location" {
type="string"
default="Sydney"
description="The name of the location in which your account is 
created. "
} 

2 Answers

In case someone wants to use just one line and get only the default value if its available. Here is what I did.

pattern_string = "(?:variable.*\\\"(\\w+)\\\"(?:.*\\s)*?(?:\\s*default\\s*=\\s*(\\S*)|}))";

Pattern pattern = Pattern.compile(pattern_string);
Matcher matcher = pattern.matcher(tfFile);

while (matcher.find()) {
   String variable_name = matcher.group(1);
   String default_value = matcher.group(2);
   if (default_value == null) {
     // do stuff
   }
}

You can find a break down of the regex here https://regex101.com/r/Ec3ykt

You could use a Regex to find the various variables, then parse the found variables using another Regex. One way to do this would be the following

Map<String, Map<String,String>> parse(String input){
    HashMap<String, Map<String, String>> variables = new HashMap<>();
    Matcher variableMatcher = Pattern.compile("variable \"(\\S+?)\"\\s*\\{\\s*((?:.|\\n)+?)\\s*}").matcher(input);
    Pattern bodyElementPattern = Pattern.compile("(\\S+)\\s*=\\s*\"(.+)\"");
    while (variableMatcher.find()){
        HashMap<String, String> bodyElements = new HashMap<>();
        Matcher bodyElementMatcher = bodyElementPattern.matcher(variableMatcher.group(2));
        while (bodyElementMatcher.find()){
            bodyElements.put(bodyElementMatcher.group(1),bodyElementMatcher.group(2));
        }
        variables.put(variableMatcher.group(1),bodyElements);
    }
    return variables;
}

Here you are going to get a map of variable name to variable contents, where the variable Contents are represented as another map of the components' names and values.

Related