Setting a Variable on the Command Line

Learn to set variables in Terraform using the command line.

Project example#

Let’s continue working with the project we created in the last lesson. We are now going to learn how we can change the value of bucket_suffix.

Click the terminal to run the terraform init command:

This code requires the following environment variables to execute:
access_key_id
Not Specified...
secret_access_key
Not Specified...
Terminal 1
Terminal

Click to Connect...

Setting a variable using command line#

The first way we can set a value for bucket_suffix is by providing it on the command line. Run the following command:

Setting bucket_suffix using terraform apply command

Terraform will ask you for a value for bucket_name since you haven’t given it one and it does not have a default. When the project runs, Terraform will create a bucket with whatever name you gave it, like hello, on end.

-var flag#

To set the value of a variable on the command line use the -var flag followed by the variable name and the value you wish to use. If we want to set both of the variables on the command line then we can do that with the following command:

Setting bucket_name and bucket_suffix using terraform apply command

In this command, we are giving a value to both the bucket_name and bucket_suffix. If you run the project with the above command to set both variables, then Terraform will not stop to request a value of the bucket_name. This is because you have now provided one. Terraform will stop and ask for a value of any defined variable that does not have a default value or other set value.

📝Note: Once you are done with the project, do not forget to run terraform destroy and then confirm with “yes” to delete all of the resources in this project.

Variable Defaults
Setting a Variable Using an Environment Variable
Mark as Completed
Report an Issue