Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Passing In Variables At Runtime #437

Closed
AdminTurnedDevOps opened this issue Jan 30, 2024 · 2 comments
Closed

Passing In Variables At Runtime #437

AdminTurnedDevOps opened this issue Jan 30, 2024 · 2 comments

Comments

@AdminTurnedDevOps
Copy link

Hey All,

Trying to figure out how to pass in variables at runtime. For example:

terraform apply --auto-approve -var name="value" -var location="value"

I set up a Variables interface to pass in the values (setting up the values of the variables by passing them in at runtime. Already have that covered).

		variables := map[string]interface{}{
			"name":                name,
			"resource_group_name": resourceGroupName,
			"location":            location,
			"node_count":          nodeCount,
			"k8s_version":         k8sVersion,
		}

		err = tf.Apply(context.Background())
@doyleish
Copy link

doyleish commented Dec 6, 2024

tfVarTempFile, _ := os.CreateTemp(os.TempDir(), "tempvars-*.tfvars.json")
defer os.Remove(tfVarTempFile.Name())
configBytes, _ := json.Marshal(variables)
tfVarTempFile.Write(configBytes)
tfVarTempFile.Close()
tf.Apply(context.TODO(), tfexec.VarFile(tfVarTempFile.Name()))

This is how I did it. Not amazing but not a ton of work either.
You could also do tfexec.Var("k=v") for all pairs in your map

@radeksimko
Copy link
Member

There is a couple of ways you can pass variables in. Assuming you wish to keep the map and the map is in practice map[string]string (i.e. values are convertible to string).

	var varOpts []tfexec.ApplyOption
	for k, v := range variables {
		varOpts = append(varOpts, tfexec.Var(k+"="+v))
	}
	err = tf.Apply(ctx, varOpts...)

or you can hard code these, e.g.

	opts := []tfexec.ApplyOption{
		tfexec.Var("name=" + name),
		tfexec.Var("resource_group_name=" + resourceGroupName),
		tfexec.Var("location=" + location),
		tfexec.Var("node_count=" + nodeCount),
		tfexec.Var("k8s_version=" + k8sVersion),
	}

	err = tf.Apply(ctx, opts...)

In either case keep in mind that this is passed in as CLI flag with all the same restrictions that shell may come with. i.e. This should work fine for variables of primitive types (number, string, bool) as long as you format it or cast it correctly to string. Complex types will be better handled through tfvars files, as mentioned by @doyleish.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants