Terraform variables vs data

In our last blog post we looked at data vs resources with Terraform and talked about static vs dynamic characteristics of data when compared to resources. In this blog we are going to look at using variables to declare structures rather than using data declarations. We will also cover a third option to use Local Values rather than variables and where they might be useful. It is important to note that there is no right or wrong answer with the use of local, variables, or data since they effectively perform the same functions and do not destroy structures as resources do when you execute the destroy option with terraform.

First, let’s look at Local Values. Declaring a local value allows you to insert a relatively static label into a variable stream. They are typically used for structures like tags or common_tags rather than static constructs. It is an easy way to declare something like a version or group that manages and maintains the resource in question.

locals {
  service_name = "forum"
  owner        = "Community Team"
locals {
  # Common tags to be assigned to all resources
  common_tags = {
    Service = local.service_name
    Owner   = local.owner
resource "aws_instance" "example" {
  # ...

  tags = local.common_tags

Note that the initial declaration is a name associated with a string. The second declaration aggregates references to these tags into another tag with the local.<name> reference. This name can then be accessed with the local.common_tags reference in main code and not have to replicate the service or owner tag information. Unfortunately, defining associations in a locals declaration does not allow for values to be passed in from the command line as is done with variables.

Input Variables allow you to define a string relationship similar to locals but also allows you to pass in values from other files or the command line. Input variables serve as parameters for a module and allow for customization and differentiation between two environments. For vSphere, for example, given that you can not have two vSphere providers or datacenters in the same code defining a datacenter for development and one for production can be done with variables and reference a common code base in another directory.

variable "image_id" {
  type = string

variable "availability_zone_names" {
  type    = list(string)
  default = ["us-west-1a"]

variable "docker_ports" {
  type = list(object({
    internal = number
    external = number
    protocol = string
  default = [
      internal = 8300
      external = 8300
      protocol = "tcp"

A variable definition has an identifier associated with it and typically a type that can be a string, number, or boolean and can be combined for more complex relationships like lists, sets, objects, or touples. Variables are typically defined in a file called .tfvars rather than a .tf file or can be passed in with the -var=”label=value” command line parameter. Alternately, variables can be defined as environment variables from the command line and the terraform command line understands how to read these values. Typically user credentials like username and password or public and private keys are defined in an environment variable rather than in a file. For a vSphere provider you can define the following environment variables and hide the connection detains to a server

  • VSPHERE_USER (var.user)
  • VSPHERE_PASSWORD (var.password)
  • VSPHERE_SERVER (var.vsphere_server)
  • VSPHERE_ALLOW_UNVERIFIED_SSL (var.allow_unverified_ssl)

Defining any of these variables on the command line get passed into the terraform control files without having to define them in a .tf or .tfvars file or having to pass them in with the -var command line extension. The var.<name> extension shown above are the constructs used to reference each of the parameters in the terraform control files. The three parameters required for a connection to a vSphere server are the var.user, var.password, and var.vsphere_server with the var.allow_unverified_ssl as an optional parameter.

provider "vsphere" {
  user           = var.vsphere_user
  password       = var.vsphere_password
  vsphere_server = var.vsphere_server

  # If you have a self-signed cert
  allow_unverified_ssl = true

Typically this is all the code that is needed to connect to a vSphere server. You could define the user, password, and vsphere_server as locals and reference them as local.user but that implies that one of your .tf or .tfvars files contains a password definition that becomes a security issue with file management and version control. Putting the user and password in an environment variable allows for dynamic changing of roles and credentials from the VMware side of the house without having to change your .tf or .tfvars files. Having the vspher_server defined with environment variables allows management of development, production, and disaster recovery using a common foundation file and not having to define a main.tf for each environment.

We could have just as easily defined our user, password and server with a Data Source definition rather than a variable definition. A data declaration is similar to a local declaration but can be more complex than a string comparison.

data "aws_ami" "example" {
  most_recent = true

  owners = ["self"]
  tags = {
    Name   = "app-server"
    Tested = "true"

Declaring a username and password with a data definition is not the most secure and safe way of defining this data. Using a variable declaration and environment variable pulls this information out of source code control and security concerns. Defining a datastore or a template with a data declaration makes more sense given that structures like datacenter, datastore, folder structures, and templates hopefully do not change significantly over time. Templates might change based on new operating system releases but managing this change with a new declaration can be a good thing.

Hopefully, this post helps understand the key difference between variable and data declarations. Both have a purpose. Both can be used. There are some technical reasons to use one over the other. There are some security concerns where one might be a better selection. The real answer is to look at how your organization uses the different constructs and have a meaningful conversation on why one is used and why another is used instead. This is one of the grey areas where there is not one way of solving the problem.

157 thoughts on “Terraform variables vs data”

  1. It’s a pity you don’t have a donate button! I’d most certainly donate to this fantastic blog! I suppose for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to brand new updates and will talk about this site with my Facebook group. Chat soon!

  2. Throughout the great scheme of things you actually receive an A with regard to hard work. Exactly where you actually lost me was on your particulars. You know, they say, the devil is in the details… And that could not be much more true at this point. Having said that, allow me tell you what exactly did give good results. Your authoring is certainly quite convincing which is possibly why I am making the effort to opine. I do not really make it a regular habit of doing that. Secondly, although I can see the jumps in logic you come up with, I am not really certain of how you seem to unite your ideas which help to make the actual conclusion. For right now I will, no doubt subscribe to your point however wish in the future you actually link the dots better.

  3. There are certainly plenty of details like that to take into consideration. That is a great level to convey up. I provide the ideas above as normal inspiration but clearly there are questions like the one you bring up the place a very powerful thing will be working in honest good faith. I don?t know if best practices have emerged round issues like that, but I’m certain that your job is clearly identified as a good game. Both girls and boys really feel the impact of just a moment抯 pleasure, for the rest of their lives.

  4. Thanks for making me to obtain new concepts about pc’s. I also contain the belief that one of the best ways to help keep your notebook computer in perfect condition has been a hard plastic-type material case, or even shell, that fits over the top of your computer. A majority of these protective gear are usually model targeted since they are manufactured to fit perfectly above the natural housing. You can buy them directly from the owner, or through third party sources if they are available for your notebook, however only a few laptop may have a covering on the market. Just as before, thanks for your ideas.

  5. I抎 should examine with you here. Which isn’t something I often do! I get pleasure from studying a publish that will make individuals think. Also, thanks for permitting me to remark!

  6. In these days of austerity and also relative panic about having debt, most people balk resistant to the idea of employing a credit card to make purchase of merchandise or pay for a trip, preferring, instead to rely on the tried as well as trusted approach to making repayment – raw cash. However, if you possess cash available to make the purchase 100 , then, paradoxically, that is the best time just to be able to use the card for several good reasons.

  7. My wife and i ended up being quite lucky when Raymond could complete his studies through the entire precious recommendations he discovered out of your web site. It’s not at all simplistic to simply find yourself giving for free key points that many some others may have been selling. And we also do understand we have the website owner to thank for that. The type of explanations you’ve made, the easy website menu, the relationships your site help promote – it’s got many superb, and it’s really letting our son and us feel that this subject matter is cool, and that is exceptionally important. Thank you for all the pieces!

  8. I must convey my admiration for your generosity for men who actually need help with the concept. Your very own dedication to getting the message up and down became pretty useful and has usually allowed people like me to achieve their desired goals. Your entire invaluable report entails a great deal to me and somewhat more to my peers. With thanks; from all of us.

  9. I have to get across my affection for your generosity for those individuals that require guidance on in this content. Your personal dedication to getting the solution up and down appears to be surprisingly functional and have usually encouraged employees much like me to arrive at their desired goals. Your important recommendations signifies so much to me and additionally to my mates. Thanks a ton; from each one of us.

  10. My spouse and i were absolutely lucky Albert could finish off his studies by way of the precious recommendations he came across from your own web pages. It is now and again perplexing to simply be giving freely hints which a number of people have been selling. And we also take into account we have got you to be grateful to for this. The most important illustrations you have made, the straightforward website menu, the friendships you will assist to instill – it is everything fabulous, and it’s helping our son and our family believe that the situation is satisfying, which is exceedingly essential. Many thanks for the whole lot!

  11. I want to convey my passion for your generosity giving support to people who really want guidance on this concept. Your very own dedication to getting the message all-around had become certainly informative and have really empowered guys like me to attain their targets. Your own warm and helpful facts means much to me and especially to my peers. Warm regards; from all of us.

  12. временная регистрация

    Наша общество предлагает комплексные услуги по юридическому сопровождению в процессе оформления временной регистрации в Москве. В штате только профильные юристы, которые гарантируют успешное получение ВР в любом регионе для нужный вам срок.

    временная регистрация

  13. Thanks so much for providing individuals with an extraordinarily breathtaking chance to read critical reviews from this web site. It is always so lovely and as well , stuffed with fun for me personally and my office mates to visit the blog particularly thrice weekly to learn the fresh tips you have got. And indeed, I am always fulfilled considering the extraordinary creative ideas you serve. Selected 2 points in this article are indeed the simplest I have ever had.

  14. I wish to express some appreciation to the writer just for rescuing me from this particular issue. As a result of browsing throughout the the net and finding principles which were not powerful, I thought my entire life was well over. Existing devoid of the answers to the issues you have resolved through the blog post is a serious case, as well as ones that could have in a wrong way damaged my entire career if I hadn’t noticed your web page. Your personal understanding and kindness in taking care of every item was tremendous. I am not sure what I would have done if I had not encountered such a point like this. I can also now look ahead to my future. Thanks for your time very much for the high quality and result oriented guide. I won’t think twice to endorse your web blog to any person who wants and needs direction on this issue.

  15. I just wanted to make a small comment to express gratitude to you for those fabulous instructions you are placing on this site. My long internet investigation has at the end of the day been rewarded with awesome insight to share with my close friends. I ‘d suppose that we site visitors actually are definitely fortunate to exist in a perfect place with very many outstanding individuals with helpful methods. I feel truly blessed to have seen your entire site and look forward to really more amazing times reading here. Thank you once again for a lot of things.

  16. I must express my admiration for your kind-heartedness giving support to individuals that have the need for assistance with this important situation. Your special commitment to passing the message all-around came to be astonishingly useful and has allowed others just like me to attain their aims. Your own valuable help means so much a person like me and much more to my colleagues. With thanks; from everyone of us.

  17. Thanks a lot for giving everyone an extraordinarily memorable possiblity to read from here. It’s usually very sweet and as well , jam-packed with fun for me and my office mates to search your blog on the least thrice in a week to see the fresh issues you will have. Of course, we’re at all times fulfilled with your effective secrets you serve. Some 3 ideas in this post are honestly the most beneficial I have had.

  18. I actually wanted to develop a brief word in order to thank you for all of the nice concepts you are showing at this site. My long internet investigation has at the end been rewarded with high-quality points to go over with my two friends. I ‘d state that that we visitors actually are unequivocally lucky to exist in a wonderful network with very many outstanding individuals with good pointers. I feel truly privileged to have encountered the weblog and look forward to really more entertaining moments reading here. Thank you once more for everything.

  19. I wish to voice my love for your kindness in support of folks that have the need for help with the area. Your very own commitment to passing the solution along turned out to be wonderfully powerful and have consistently made those like me to get to their endeavors. Your entire informative guidelines means a great deal to me and far more to my office workers. Thanks a ton; from everyone of us.

  20. I not to mention my buddies were actually studying the best guidelines on your web site while suddenly got an awful feeling I never expressed respect to the website owner for them. These young men are actually so stimulated to see all of them and have really been taking pleasure in these things. Thank you for getting indeed considerate as well as for finding such helpful issues millions of individuals are really needing to learn about. My sincere regret for not expressing gratitude to you earlier.

  21. Thanks so much for giving everyone an exceptionally breathtaking possiblity to read critical reviews from this website. It really is very ideal and also jam-packed with a lot of fun for me personally and my office fellow workers to visit your website at least thrice in 7 days to read through the newest stuff you have. And of course, I’m always impressed with your mind-blowing hints you serve. Some 2 points in this post are definitely the best we’ve ever had.

  22. I needed to post you this little word to say thanks a lot as before for all the great pointers you have shared in this article. It’s really incredibly generous with you to make unhampered all that most of us could have made available as an electronic book to generate some profit on their own, principally considering that you could possibly have done it if you decided. Those tips also worked to be a great way to be sure that many people have the identical zeal just like my personal own to find out a lot more with respect to this matter. I know there are numerous more pleasant situations in the future for many who take a look at your website.

  23. I must get across my appreciation for your generosity in support of men who really need guidance on in this subject matter. Your real commitment to passing the message all around came to be really helpful and have regularly made ladies much like me to achieve their aims. Your own warm and helpful help denotes much to me and especially to my mates. With thanks; from each one of us.

  24. I simply had to say thanks yet again. I’m not certain the things that I would’ve handled without those information provided by you on such a situation. It has been a scary scenario in my position, however , spending time with a new skilled approach you dealt with the issue made me to cry over contentment. Now i’m grateful for your work and as well , pray you are aware of a great job you have been accomplishing teaching some other people through a site. Most likely you’ve never encountered any of us.

  25. I simply wanted to make a comment to be able to say thanks to you for those fantastic ideas you are giving out on this website. My rather long internet investigation has at the end been compensated with reliable points to share with my co-workers. I would point out that most of us website visitors actually are truly endowed to dwell in a fabulous site with very many wonderful professionals with good techniques. I feel very lucky to have discovered the webpage and look forward to tons of more fun times reading here. Thanks again for everything.

  26. I wanted to post you one bit of remark just to say thank you yet again on your pretty principles you have provided in this case. This is certainly incredibly open-handed of you to offer easily what numerous people would’ve distributed for an electronic book in order to make some cash for themselves, mostly given that you might have done it if you wanted. Those concepts likewise served like a easy way to recognize that the rest have a similar passion the same as my very own to learn many more with regard to this condition. Certainly there are some more pleasant moments up front for those who looked at your website.

  27. I intended to post you this very small observation to help say thank you the moment again for those magnificent concepts you’ve discussed in this case. It has been simply wonderfully generous with people like you to supply without restraint all most of us might have supplied for an electronic book to help make some cash on their own, chiefly since you could have tried it in case you desired. Those techniques as well served to be the easy way to be certain that other individuals have the same keenness just like my own to learn very much more with reference to this matter. Certainly there are lots of more pleasurable occasions ahead for people who looked over your site.

  28. I simply wished to appreciate you yet again. I am not sure the things I would’ve handled without the tips and hints contributed by you regarding that situation. Entirely was the frustrating crisis for me, but noticing this expert tactic you managed the issue forced me to cry over joy. Now i am grateful for your support and expect you recognize what a great job that you are carrying out instructing the mediocre ones through the use of your webpage. More than likely you’ve never come across any of us.

  29. I happen to be writing to let you know what a cool experience our child found viewing the blog. She came to understand a wide variety of pieces, including how it is like to possess a marvelous coaching character to get others completely learn about specific specialized topics. You truly did more than people’s desires. I appreciate you for giving the valuable, safe, revealing and also fun tips on this topic to Ethel.

  30. I precisely wished to say thanks yet again. I’m not certain what I might have taken care of without the entire secrets discussed by you directly on that area of interest. It absolutely was the hard issue for me personally, but finding out the well-written manner you handled that took me to leap over delight. Now i am grateful for your service and then trust you comprehend what a powerful job that you’re putting in teaching the others via your websites. I’m certain you have never got to know all of us.

  31. I am writing to make you understand of the cool encounter my princess found going through your blog. She picked up a wide variety of things, which include what it’s like to have an incredible teaching style to let the rest clearly grasp chosen tortuous issues. You undoubtedly did more than people’s desires. Thank you for showing those necessary, trustworthy, explanatory and also fun tips about that topic to Gloria.

  32. Thanks for your entire work on this web page. Ellie really loves making time for investigations and it is easy to understand why. We all learn all of the lively mode you provide priceless things by means of the blog and therefore attract contribution from the others on the point while our own princess is without question studying a whole lot. Take advantage of the rest of the new year. You’re doing a good job.

  33. Thanks for all your valuable labor on this web site. Gloria enjoys going through investigation and it’s really easy to understand why. A number of us know all relating to the powerful method you deliver invaluable techniques by means of your web blog and therefore encourage response from other ones on the issue then my princess is without a doubt learning a lot. Have fun with the remaining portion of the year. You’re doing a useful job.

  34. I wish to show my admiration for your kind-heartedness in support of women who require guidance on this particular area. Your personal commitment to passing the message all through had been unbelievably advantageous and have always made many people just like me to achieve their targets. Your amazing interesting guidelines implies a great deal to me and even more to my office colleagues. Warm regards; from each one of us.

  35. I simply wanted to say thanks once more. I’m not certain what I would’ve sorted out in the absence of the actual opinions contributed by you on my concern. It actually was a real troublesome problem in my position, but being able to view your specialised style you treated the issue forced me to weep with happiness. Now i am happier for the assistance and even have high hopes you really know what a great job you happen to be carrying out training men and women through your webpage. I am certain you haven’t met all of us.

  36. I am glad for writing to let you understand of the awesome encounter our princess gained reading through your blog. She mastered several details, which include what it’s like to have a very effective teaching character to make other individuals effortlessly learn about chosen extremely tough matters. You really did more than people’s desires. Thanks for delivering these valuable, trusted, explanatory and fun tips about the topic to Kate.

  37. I would like to express appreciation to this writer for rescuing me from this type of circumstance. Right after scouting through the the net and finding notions which were not pleasant, I thought my life was well over. Living without the approaches to the difficulties you’ve solved through the review is a critical case, and the kind that could have in a negative way damaged my career if I hadn’t discovered your blog. Your good ability and kindness in handling the whole lot was very useful. I am not sure what I would have done if I had not encountered such a solution like this. I can also now look ahead to my future. Thanks a lot so much for the professional and amazing guide. I won’t think twice to recommend the sites to anybody who would need guidance on this area.

  38. A lot of thanks for your own labor on this blog. My aunt takes pleasure in setting aside time for internet research and it is easy to see why. We all notice all regarding the compelling manner you deliver practical things by means of the blog and as well as foster participation from other people on the subject matter then our own daughter is certainly starting to learn a great deal. Take pleasure in the remaining portion of the new year. You’re performing a good job.

  39. I have to express some thanks to you for bailing me out of this instance. Because of exploring through the world-wide-web and coming across methods that were not productive, I assumed my entire life was gone. Being alive devoid of the solutions to the difficulties you’ve resolved by means of your main short article is a critical case, as well as those which may have adversely affected my career if I had not noticed your website. Your main competence and kindness in playing with every aspect was vital. I’m not sure what I would have done if I hadn’t come upon such a stuff like this. It’s possible to now relish my future. Thank you so much for your high quality and result oriented help. I will not think twice to refer your site to any person who needs to have tips about this problem.

  40. I as well as my buddies came looking through the good tips and tricks found on your web page and so the sudden came up with a horrible suspicion I had not expressed respect to the web site owner for those techniques. Those women came absolutely very interested to study them and now have very much been taking advantage of those things. Appreciate your really being quite accommodating as well as for deciding on this kind of helpful guides most people are really eager to learn about. My sincere regret for not saying thanks to sooner.

  41. I am also writing to make you be aware of what a excellent discovery our daughter had viewing the blog. She figured out a lot of pieces, which included how it is like to possess an amazing teaching heart to have folks effortlessly know specified problematic subject areas. You truly did more than people’s expectations. Many thanks for giving the interesting, healthy, edifying and easy tips on that topic to Lizeth.

  42. My spouse and i were so cheerful Louis could round up his homework using the precious recommendations he had from your very own web pages. It’s not at all simplistic to just always be releasing ideas that many most people might have been selling. And now we realize we have got the blog owner to be grateful to for that. The most important explanations you’ve made, the straightforward site menu, the friendships you will assist to promote – it is many sensational, and it is making our son in addition to the family feel that this article is enjoyable, which is wonderfully serious. Many thanks for the whole thing!

  43. I precisely had to appreciate you once again. I’m not certain the things I would’ve undertaken without the actual hints contributed by you relating to this industry. It had become a very difficult setting in my circumstances, however , finding out the expert mode you treated it took me to weep over delight. Extremely happy for your work as well as believe you recognize what a powerful job you are always providing educating people today through the use of your blog. Most likely you haven’t come across all of us.

  44. I would like to show appreciation to the writer just for bailing me out of this condition. Because of looking throughout the the web and coming across strategies that were not productive, I was thinking my life was over. Existing devoid of the strategies to the difficulties you’ve sorted out through your good article content is a crucial case, and the kind that would have negatively affected my career if I had not encountered your blog. The natural talent and kindness in controlling every aspect was precious. I’m not sure what I would’ve done if I hadn’t encountered such a thing like this. I can also now relish my future. Thanks a lot very much for the reliable and amazing help. I won’t think twice to refer the blog to anybody who needs and wants guide about this problem.

  45. I am also writing to let you be aware of what a helpful discovery our girl developed viewing your web site. She mastered lots of issues, which include what it’s like to have an incredible giving character to make folks without problems thoroughly grasp a number of problematic topics. You really exceeded people’s expected results. Thanks for producing such great, trustworthy, edifying and also unique guidance on that topic to Janet.

  46. Thanks for every one of your hard work on this website. My mom enjoys managing investigations and it’s simple to grasp why. Most people learn all relating to the lively medium you deliver precious guides through the blog and in addition attract response from others on this theme and my child is always becoming educated a lot of things. Take pleasure in the rest of the year. You are always conducting a wonderful job.

  47. My spouse and i got now joyous when Raymond could do his investigation using the precious recommendations he acquired from your very own weblog. It is now and again perplexing to just continually be giving away concepts which often other people may have been selling. And we also understand we have the writer to be grateful to for this. The specific illustrations you’ve made, the easy blog menu, the friendships your site assist to foster – it is mostly incredible, and it is helping our son and the family recognize that that content is amusing, and that’s extremely fundamental. Thank you for everything!

  48. I not to mention my friends have been reviewing the excellent tactics from the website and then before long I had an awful suspicion I had not thanked the web site owner for those tips. All the boys are already totally happy to see all of them and have in actuality been enjoying those things. Thanks for really being simply thoughtful as well as for utilizing certain impressive guides millions of individuals are really desirous to learn about. My honest apologies for not saying thanks to you earlier.

  49. I intended to post you a little observation to be able to thank you so much again about the amazing ideas you’ve featured above. It’s quite shockingly generous with people like you giving freely precisely what many of us might have offered for an e book to generate some profit on their own, mostly given that you could have done it if you ever considered necessary. These creative ideas in addition worked to become easy way to fully grasp other people have the same eagerness like my personal own to understand much more when it comes to this matter. I believe there are several more pleasurable sessions up front for individuals that read carefully your blog post.

  50. I am also commenting to make you know of the fantastic experience our daughter encountered viewing your blog. She realized many issues, not to mention what it is like to possess an incredible helping spirit to make many others clearly thoroughly grasp selected complicated things. You undoubtedly did more than people’s desires. I appreciate you for presenting the necessary, dependable, revealing and also easy guidance on that topic to Tanya.

  51. Ремонт кондиционеров

    Наша компания предоставляет полный спектр монтажных услуг, работ по сервисному обслуживанию, а также ремонту кондиционеров.Доступен и срочный ремонт кондиционеров Aerotek, Ballu, Daikin, Dantex, Electrolux, Fuji Electric, Gree, Haier, LG, Mitsubishi Electric, Mitsubishi Heavy, Panasonic, Sakura, Samsung, Toshiba.

    Ремонт кондиционеров

Leave a Reply

Your email address will not be published. Required fields are marked *