Terraform Basics: Input Variables

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
terraform variables what even are they and how do you use them that's what we're going to be covering in this episode of terraform tuesday terraform [Music] basics [Music] hey everybody it's ned belvance ned1313 on twitter and welcome to terraform tuesday and this is another edition of terraform basics that's right we're going to get down to the nitty-gritty the fundamentals of terraform and the reason behind that is because i get a lot of questions about fundamental things in terraform and i thought hey wouldn't it be great if there was just a video series i could point someone out and go you wanted to know more about this basic concept in terraform here you go here's a nice video that lays it all out for you today we're going to be covering variables specifically input variables within terraform now before we get into that two quick things number one did you know i have a whole series of terraform courses on pluralsight those are a much more formal presentation of terraform they're more professionally polished and they've got really robust exercise files to go with them so if you're interested in getting started with terraform or some of the more advanced implementations of terraform check out those courses definitely worth your while the other thing that i want to mention real quick is that i have launched a new look and feel for my website nedinthecloud.com so go check it out and let me know what you think because it needs to be tweaked i think but i can't really get it where i need it to be without some input from you so you know check that out if you have time thank you very much for that and without further ado let's talk about terraform input variables before we get started on terraform input variables a little bit of disambiguation big word there about terraform variables and how we're going to use the term variables there are different kinds of variables in terraform specifically there's input variables and then there's things outside of terraform like environment variables and then variables has its own connotation within programming so unless i specifically reference one of those other things when i'm talking about variables in this video i'm talking about input variables now where are input variables used they're used inside of terraform configurations and should definitely check out my whole video on modules because i'm going to use some module terminology here but basically the configuration you're currently working in is the root module and any modules you invoke from that root module are the child modules and from those child modules they have a relationship with a parent module which is usually the root module so just a little bit of terminology there so you know where i'm coming from the variables that you create inside your root module is the way in which you get values into terraform at runtime now let's take a look at the syntax that's behind a variable when you establish a variable inside a terraform configuration so i'm going to throw an example up on the screen now this is a basic variable block and you'll notice there's no arguments inside the block you have the variable keyword that says hey i'm establishing a variable here then you have the name of the variable the name label we call it and then you have some curly braces now normally inside a block established by those curly braces you would have some arguments there and then values for those arguments a variable doesn't actually need any arguments at all to be created you can create a variable simply by doing variable name and curly braces and that's it everything else is going to be passed at runtime now you may want to provide a little more information to terraform about your variable and there are a few basic fields that get used within the variable block so let's explore those fields now all right to continue the conversation about variables i thought we'd go over to the demonstration area here's visual studio code as always the files for these videos are available in my github repository called terraform tuesday so go check that out if you want to look at the example files with me i also have a nice readme doc that i put together for this and it talks a little bit about the variable syntax which i already have up here so let's scroll down a little bit and take a look at that now i showed you you can just create a basic variable block without anything else but what if you want to add some more information in there well there are three arguments you can throw in there the first one is description the description really is for use in modules when you're invoking a child module the description helps tell you what the inputs are for that child module that's generally what the description for also if you happen to be reading the terraform configuration the description could help tell you what that variable is intended for but like i said the description is optional the next one is type again type is optional terraform will try to figure out the data type based off the information that you give it so if you give it a value of true it's going to say oh okay this variable is a boolean but it's not strongly typed by adding a type in here you can make it a little more strongly typed you can use one of the primitive data types something like string number or boolean or you can actually create a much more complex type an object or a list or a map you have a lot of options along with the type let's just stick with basic string for now and then the final value is the default value of the variable if a value is not specified in any other way and there are many ways to specify a value for a variable we're going to get into those a little bit later but these are the three basic arguments that you'll use okay so the next question that you might be asking yourself is once i have a variable in my terraform configuration how do i refer to the value or values that are stored inside of that variable the basic syntax for referring to a variable value is to use the var keyword dot and then the name label of the variable that you used so in our previous example it would be var.taco to get to the string that's stored inside of taco now what if you have a more complex object type for your variable well then standard terraform syntax pretty much applies here let's say your variable type is a list and you have a list of values stored in there well you would just use the standard syntax of var dot the name label of your variable and then a square bracket the number of the elements that you want from your list and then a closing square bracket and that's it so that's how you would refer to a specific element and of course you can also use all the terraform functions to manipulate that list maybe you only want two elements from that list in the middle or maybe you want to squash it down to a string or turn it into a map there's a lot of things you can do with the various functions inside terraform and all of those obviously apply to variables why don't we go back to the demonstration and i'll show you some examples of how you can refer to variables within the code all right back in visual studio code let's open up the referral example here and we've got a variables.tf file here so we're setting up three different variables in this the first one is a simple variable called protein of type string and i'm setting the default to chicken the variable in the second instance i have all three of the basic properties set so it's another string type the default is cheddar and i have a description for that and then lastly i'm creating a variable called toppings and that type is list instead of string and for the default i've given it a value that is a list of elements now if i wanted to use those variables in my configuration i could set up a local value so let's say i want to set up a local value called my underscore taco and it's of map type i can create a map based of based off the different values that are inside my variables so as you can see here for protein i'm using the syntax var.protein to refer to the value that's stored inside that variable the default is going to be chicken but i can change that at runtime by specifying a different value now if i specify var.toppings for the toppings key within my map now it's going to use the entire list the whole list is returned if i want a specific element out of that list you can see my topping equals var.toppings and then the square brackets and 0 will give me the first element out of my list so just to show that working in action let's go ahead and open up the terminal and we're going to go into the reference referral and then we'll do a terraform apply just to apply it real quick and there's really nothing being created here but now we can use uh terraform console and this lets us take a look at what's stored in different elements inside of our terraform configuration the element i'm interested in first is my underscore taco so i will just ask for local and then my underscore underscore taco there we go and it gives me what's the value currently stored in the local value my taco so we can see the whole list is there for toppings now let's take a look at what's stored inside of my topping so we'll do local my underscore topping there we go and we can see just lettuce is in my topping and that's the first element in my toppings list so if you want to refer to something inside of a variable that is the various syntaxes that are there for referring to variables the next thing to talk about is variable scoping where are variable values available and this gets back to the thing that i was talking about with root modules versus child modules the value of a variable is only available inside of its module and not beyond that module so if you have a variable that exists inside of a root module and you would like to pass that value to a child module the child module can't directly refer to the variable that's in the root module there's no way to do that in other programming languages there might be you can refer to a global scope let's say that doesn't exist with inside terraform the way that you would pass a value is you would create an input variable inside your child module and then you would pass that value when you invoke that module in your root module as one of the inputs and that's how you would pass that value now if you have a variable that is defined inside of a child module and you want to make that variable value available outside of the child module you could expose it as an output and i'm going to do a whole separate video on outputs but just to understand outputs are how you make values available outside of the scope of a module so that's how you can pass it back and forth but generally speaking specifically speaking the values stored inside a variable are only available within the scope of that module and not beyond it you'll have to use some other construct to pass values between different modules and out of those modules to external sources okay so hopefully that that clears up the whole scoping concern the next thing we're going to talk about is another argument that you can put inside of a variable block and that is variable validation when you're learning about programming one of the things you learn is you can't trust the input that users give you because they're going to do weird and stupid things so you want to validate the input that you're given by users and variable validation is no exception now this is something that you would probably use a lot when you're writing modules that will be used by others but it's also good for yourself because sometimes we make mistakes too variable validation is one or more blocks inside of a variable block these are nested blocks and each validation block is there to test a condition whether it's true or false if it's true then it passes that validation passes if it's false then there is an error message that terraform will emit and say hey it failed this validation check and it will stop there it's going to tell you it failed this validation check i'm not going to go any further so let's take a look at the actual syntax and then actually experiment with it just a little bit okay back in visual studio code i've opened up the variables.tf file that's inside the validation folder and you can see we've got a single variable here called protein and it's of type string so in a way type is already a way to constrain things if i tried to present the variable with a list or a map it would fail the validation of the type and prior to terraform 0.13 i think that was all the validation you got but now there's some additional validation here now you can see we've got two validation blocks let's take a look at each of them like i said the validation block is going to first have a condition that must test to true or false now that can be a very simple function that you're invoking if it's something that just needs to evaluate or not then you can use the can function to determine whether it evaluated successfully and that's for something like a regular expression that it doesn't resolve to true or false it more just did it actually find an element using the regex or did it not so again there are some tricks here but the first one we have is checking the condition of whether or not the value specified is within a list so we're using the contains function here to do the test and we're checking to see if the value submitted var dot protein and we're using the lower function to make it all lower case so we don't have to worry about case sensitivity here we're checking to see if the dot protein is in the list that's submitted here chicken beef or tofu and if it's not in that list then the error message simply says the protein must be in the approved list of proteins so if we fail that we fail that oh well then the next test in here has the condition of whether or not the protein was submitted in all lower case and maybe we have for reason that we need it to be all lower case i've certainly seen this with azure storage accounts which have to be all lower case and you can do the transformation yourself but you can also push back on the user and say hey this needs to be a lower case well you can see the condition here is we're going to set lower function on var.protein and then check to see if it's the same as var.protein meaning it's all lower case and if it's not we're going to go back to the user and say you can't have any capital letters in your protein so those are two validation messages and like i said before it's going to evaluate these in order so whichever one fails first is the error message you're going to see and once you fix that it might fail further down so let's take a test run here and try to run a terraform apply and specify a value for our variable so i'll go ahead and pull up the command prompt here we're in the validation for folder and i'll do a terraform apply and i'm going to use the dash var option and we'll get more into this a little bit later but dashbar is one way that you can specify a value for a variable our variable in this case is protein so i will say protein equals and let's let's have it actually work once let's do protein equals chicken and just you know make sure that at least it works okay no changes i didn't get any errors now let's change that value to a capital c and it tells us invalid value for variable why is it invalid well it's saying the protein must not have capital letters that's the error message we would expect and it tells us which validation rule failed and what line we can find it on that's that's pretty useful now what if we just specify something that we know is not in the list let's say fish for instance well in this case now it failed on a different check it failed on the first check letting us know that it needs to be in the list of approved proteins what if we add a capital letter here does it still does it tell us both failed or does it tell us that only one failed well it tells us both failed so it actually checks both rules and i think i said it only checks one but it actually checks all the validation rules then it will tell you in one big set of error messages each one that it did not pass for the check so that's good to know you can fix all your errors in one go so that's validation validation is pretty cool definitely recommend implementing it especially if you're writing modules for others now let's take a look at secret suppression how do you suppress values that you submit as a variable if they're sensitive data some of the values you want to submit as variables may have sensitive data in them and ideally you wouldn't submit them as variables you'd find another way to get those values inside your terraform configuration but oftentimes you might need a username and password combination you might need some sort of authentication information and the only way to do that is through a variable and you don't want that information displayed at the command line you don't want it displayed in your terraform logs because it's a sensitive piece of information well the good news is the final argument that's available inside the variable block is called sensitive so let's take a look at how the sensitive is implemented and what the impacts are when it comes to using it within your terraform configuration all right now we're looking at a variables.tf file that's located in the suppression directory and the reason i say suppression is because we're really just suppressing the output of the variable the sensitive value is still there now if we want to see how this is implemented if we look down at the variables i'll call your attention to the variable phone number and within the arguments there we've set sensitive equal to true so this is how we let terraform know that this variable is sensitive so anytime it's going to print this variable in the terminal output or in our log files it's going to suppress the actual value and not show it to us it also means that if we include this value in other resources within terraform it's going to attempt to continue treating that value as sensitive now the downside is if you're using this sensitive value with various resources and providers the providers don't necessarily need to respect the sensitivity that is being worked on but right now if you pass a password to a provider if you're setting up a database let's say and then later for whatever reason that provider plugin prints out that password as part of some separate log output that sensitive feature may not be honored by that provider providers are being updated to honor the sensitivity this was introduced in terraform 0.14 so it may be supported by by your provider but it may not so just bear that in mind when you're working with sensitive values now let's see how we're using this in our configuration here we can see i've added phone number to my my taco locals value and then i've also used a function called non-sensitive and stored the value in a separate local value called my number and then finally we have an output that's commented out right now we'll uncomment it in a moment but let's let's take this for a test drive first so i'm going to go ahead and bring the terminal back up and we'll do a terraform apply and then once that has completed we will do a terraform console so we can look at the value that's stored inside my local values and so the first one we're going to look at is my taco so let's do my underscore taco there we go and if you look at the phone number property of or the phone number key of my my taco map we can see it equals sensitive so terraform has blocked that out and if this was in a log somewhere it would do the same thing it would say sensitive it's not going to show you that value now let's take a look at the other value my underscore number so if you do need the value printed out for some reason let's do my underscore number you can see if you use the non-sensitive function now it will allow you to present that in plain text now the reason i had the output commented out here is if let's go ahead and uncomment that and save our file we'll exit out of the terraform console and we'll do another terraform apply you can see it's going to come up with an error here it's going to let us know that output of the var.phone number is a sensitive value it can't just give us this output in our root module because that would be presented to the terminal and that's a no-no so it's going to let us know if this is a root module and you want this output to be displayed in your terminal you're going to have to use that non-sensitive function if this was a child module it would be fine because the child module would make that output available to the root module for use but it wouldn't be printed at the terminal so that's why that error is there so hopefully now you have a good idea of how sensitivity works in terms of variables the last thing i want to talk about is how you get values into variables and all the different ways to do it and there are many when you want to supply a value to a terraform input variable there's a bunch of different ways to do it so i'm going to go over all of them very briefly and then we're going to dive into the order in which they are evaluated because that's very important to determine which value is actually submitted to terraform okay so the different ways that you can do it let's start at the command line you can use the dash var option and that allows you to specify a key value pair for a specific variable and you can do dash var as many times as you want in the command line to specify all the different variables that you want to set values for that's one now that can be a little cumbersome so why not put your variable values in a file you can do that and then you can specify dash var dash file as an option and just point it at wherever that variables file is now even that might be a little too cumbersome so there is two special file names that you can use that will automatically be evaluated by terraform one is terraform.tf vars and the other one is terraform.tfvars.js if terraform sees either of those files in the same directory as the root module it will evaluate the values that are inside of those files now what if you have other files that you want to evaluate well you can add a dot auto.tf vars to a file or dot auto.tfvars.json to a file and if it finds either of those files inside the working directory of your root module those will also be evaluated and then lastly you can submit variable values using environment variables and the way you do that is you name an environment variable tf underscore var underscore the name label of the variable you want to set the value for and terraform will just check that environment variable okay so that's all the different ways that you could submit a value for a variable plus there's also the default value of the variable itself now the order of evaluation is a bit of the inverse so here's how terraform evaluates the different variable values if you use multiple ways of providing input first it evaluates environment variables so if you set it through an environment variable that's the first one then it evaluates what's in the terraform.tf vars and the terraform.tfvars.json files if they exist then it's going to evaluate anything that's in a dot auto.tfvars file or dot auto.tfbrs.json file and then finally it's going to evaluate anything you specify at the command line with a dash var or dash var dash files dash var dash file so that's the order of operations of how it's going to evaluate the value so if you specify it in multiple multiple locations the last one evaluated wins which can get a little confusing so generally speaking try not to do this but if you do want to override a value that's stored say in your tf vars file then you can specify it at the command line using the dash var and that will override whatever is in the tf vars file for that particular run so let's go back over to the demonstration area and we'll walk through the evaluation of different values for the variables all right i have the file variables.tf open that's in the values directory and i also have a terraform.tf vars file in that directory as well as some commands because i might mistype something so i just wanted to get it right with the commands.txt file and that will help you follow along as well let's take a look at the variables we've defined we've got a protein that does have a default value of chicken so if we don't specify any other value for protein then it's going to use chicken our variable cheese has a default of cheddar our variable toppings has a default list value okay so that's what we have in our variables let's take a look at our terraform.tf vars file we have one value specified in here and it's protein equals beef so if our terraform.tf vars file is in the same directory as our root module which it is then that should override the default setting and instead of chicken we will have beef as our terraform dot as our value for the protein variable so let's go ahead and bring the terminal up and i'll open up my commands because i'm going to get this wrong now before we try anything let's go ahead and run terraform apply and see what we get so i'll go ahead and copy that command there we go so if i just run terraform apply and oh well some here's my outputs so this is just going to give us an output of all our variables in the my taco local value we can see that the protein right now is beef the cheese is cheddar because that is what is specified as the default value in my variable and same thing with the toppings okay pretty straightforward now let's go ahead and we're going to change some of the values using environment variables so i'm running on windows i'm going to use the windows commands but if you happen to be running on linux or mac you can use the export commands so go ahead and grab those two commands here and just paste them down here real quick okay now i've set my cheese to jack and i've set my protein to tofu now if we follow the order of operations the values specified in terraform.tf vars should override whatever i set as the environment variable so my protein should evaluate to beef and not tofu let's go ahead and run terraform apply and it should prompt me again there we go yes all right so we can see our cheese is now jack because it found that in our environment variable our protein is beef because terraform tf vars took precedence over our environment variable and the toppings list is the same now let's try one more command here we're going to run terraform apply and we're going to add dash var and set the protein equal to tofu and that should take precedence over what's specified in our terraform.tf vars file so go ahead and copy that here and paste it down below and it's going to prompt me to say yes again there we go and now we can see our cheese is jack from our environment variable our protein is tofu because of what we specified at the command line and our toppings has remained the same so i know like i said this can be a little bit confusing generally you want to avoid all this confusion whatever you can but it's good to know that when you're troubleshooting this is the order in which all these different values are evaluated all right the last thing i want to mention is passing sensitive values into those input variables and you can pass that sensitive value in the same way that you pass any other value but generally speaking you don't want sensitive values to be stored in a file somewhere or you know visible within the logs so how do you pass a sensitive value well ideally you wouldn't do it through an input variable at all instead you would have your sensitive values stored in a data source somewhere like azure key vault or kms on aws or something and then wherever terraform is running from has permissions to access that data source and get those values boom it's not in your variables anymore at all that would be ideal but sometimes that option is not available to us the best way to do it then is probably through environment variables and you can do that with the tf underscore var underscore variable name or if you have to override it at the command line you could use dash var and directly refer to whatever environment variable name you've stored that value inside then it's not logged at the command line or in your terraform logs but you're still specifying a sensitive value if in case you need to override something like you if you have the value set in tf vars or something like that so those are generally your options when you're dealing with sensitive values and that's going to do it for today's terraform tuesday terraform basics all about variables i hope you found the content informative and helpful maybe it cleared up some confusion you had about variables if you have suggestions for future terraform basics videos let me know i have my own list of things that i want to do but if there's something that jumps to the front of your mind you're like man i need to know more about this thing let me know on twitter it's ned1313 leave a comment down below or find me on linkedin any of those options are 100 approved let me know what you want to hear about my plan is to do these videos about once a month the terraform basics series once a month if you would like to support this show and the other things that i do you can find me on patreon and you can be one of the fine patrons that shows up in the list that's next to me right now if you want to see your name there you can find me on patreon and sign up for the big burrito or the empanada level and you get your name on there that's kind of nice if that's not your thing i get it or you know if it's not monetarily feasible also okay if you want to subscribe to the channel that is very much appreciated if you want to share it with a friend that is also very much appreciated until next time stay healthy stay safe out there bye for now [Music] you would think that i'm like super organized to get all the stuff out of the door that i do and i'm not i'm not organized at all i i try to get organized every once in a while but then i make the system too complicated and i don't do it uh right now i'm trying this it's just it's just a journal with a list of things i need to do today and i prioritize them by number and that's the order in which i try to accomplish those goals that's it it's not any more complicated than that and hopefully keeping it that simple will actually let me do it so i'll let you know how that goes bye
Info
Channel: Ned in the Cloud
Views: 6,439
Rating: undefined out of 5
Keywords: HashiCorp Terraform, Terraform tutorials, Terraform Getting Started, Terraform Input Variables
Id: 2f65JhfYmIo
Channel Id: undefined
Length: 33min 53sec (2033 seconds)
Published: Tue Jul 13 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.