Skip to content

Commit

Permalink
✨ : generate tfvar files for complex variable types
Browse files Browse the repository at this point in the history
  • Loading branch information
juwit committed Apr 12, 2021
1 parent 70a5ba0 commit aa9dcf7
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/main/java/io/gaia_app/stacks/bo/Stack.java
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,10 @@ public void setCredentialsId(String credentialsId) {
* @return a string with the content of the tfvars file
*/
public String tfvars() {
var varLine = "%s = \"%s\"\n";
// strings are quoted, other variable types are not
var stringVariableLine = "%s = \"%s\"\n";
var variableLine = "%s = %s\n";

var variablesBuilder = new StringBuilder();

module.getVariables().forEach(terraformVariable -> {
Expand All @@ -198,7 +201,13 @@ public String tfvars() {
if (this.variableValues.containsKey(variableName)) {
variableValue = this.variableValues.get(variableName);
}
variablesBuilder.append(String.format(varLine, variableName, variableValue));

if( "string".equals(terraformVariable.getType())){
variablesBuilder.append(String.format(stringVariableLine, variableName, variableValue));
}
else {
variablesBuilder.append(String.format(variableLine, variableName, variableValue));
}
});
return variablesBuilder.toString();
}
Expand Down
44 changes: 44 additions & 0 deletions src/test/java/io/gaia_app/stacks/bo/StackTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,48 @@ internal class StackTest {
.contains("variableWithDefault = \"myValue\"\n")
.contains("mandatoryVariable = \"myOtherValue\"\n")
}

@Test
fun tfvars_shouldGenerateTfvarContents_forComplexTypes() {
// given
val listOfNumbers = Variable("listOfNumbers", "list(number)", "a list variable")

val module = TerraformModule()
module.variables = listOf(listOfNumbers)

val stack = Stack()
stack.module = module
stack.variableValues = mapOf("listOfNumbers" to "[1,2]")

// then
Assertions.assertThat(stack.tfvars())
.contains("listOfNumbers = [1,2]\n")
}

@Test
fun tfvars_shouldGenerateTfvarContents_forComplexTypesOnMultilineStrings() {
// given
val mapVariable = Variable("mapVariable", "map", "a map variable")

val module = TerraformModule()
module.variables = listOf(mapVariable)

val stack = Stack()
stack.module = module
stack.variableValues = mapOf("mapVariable" to """
{
name = "Anakin"
age = 45
}
""".trimIndent())

// then
Assertions.assertThat(stack.tfvars())
.contains("""
mapVariable = {
name = "Anakin"
age = 45
}
""".trimIndent())
}
}

0 comments on commit aa9dcf7

Please sign in to comment.