forked from LevelUpEducation/terraform-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Notes.txt
1402 lines (1068 loc) · 51.7 KB
/
Notes.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Create high quality terraform content
-------------------
Infrastructure as Code (IaC)
Process of managing and provisioning the complete IT infrastructure
(comprises both physical and virtual machines)
using machine-readable definition files.
Automate environment provisioning process.
Ease maintenance of the environment.
Manage the source code of it in SCM.
Challenges with Infrastructure as Code :
Need to learn to code
Don’t know the change impact.
Need to revert the change
Can’t track changes
Can’t automate a resource
Multiple environments for infrastructure
Terraform has been created to solve these challenges.
Terraform introduction
----------------------
What is Terraform?
Open-source infrastructure as Code
Developed by HashiCorp.
Used to define and provision the complete infrastructure
Declarative language.
Infrastructure provisioning tool
Cloud infrastructure setup as codes.
Similar to tools like CloudFormation
However provider independent.
Adv. of Terraform
Does orchestration, not just configuration management
Supports multiple providers such as AWS, Azure, GCP, DigitalOcean and many more
Provide immutable infrastructure where configuration changes smoothly
Uses easy to understand language, HCL (HashiCorp configuration language)
Easily portable to any other provider
Supports Client only architecture, so no need for additional configuration management on a server
References: D:\PraiseTheLord\HSBGInfotech\DevOps\Terraform\TerraformTOC.txt
Understanding terraform
Terraform Providers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
https://github.com/vilasvarghese/terraform-tutorial/blob/master/2e_Providers/providers.tf
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Core Terraform Workflow
The core Terraform workflow has three steps:
Write - Author infrastructure as code.
Plan - Preview changes before applying.
Apply - Provision reproducible infrastructure.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Terraform core commands
terraform init
terraform validate
terraform plan
terraform apply
terraform destroy
init
Initialize a working directory
First command in workflow
Downloads plugins specific to the provider
validate
Verifies the
syntax
consistency
of the configuration.
plan
Creates execution plan
Performs a refresh and determines what action to performance
Compare .tfstate to current state
compare your changes with current state and above state
create the plan (order of execution)
display all the delta to us.
apply
Again executes the plan (unless we have persisted)
CRUD of infrastructure
destroy
Destroy infrastructure.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
How Terraform Works With Plugins
https://www.terraform.io/docs/extend/how-terraform-works.html
Terraform
tool for building, changing, and versioning infrastructure
safely and efficiently.
built on a plugin-based architecture
enable capabilities using plugins.
Terraform
logically split into two main parts:
Terraform Core and
Terraform Plugins.
Terraform Core
The primary responsibilities of Terraform Core :
Infrastructure as code:
reading and interpolating configuration files and modules
Resource state management
Construction of the Resource Graph
Plan execution
Communication with plugins over RPC
offers multiple ways to discover and load plugins
high-level framework that abstracts plugin discovery and RPC communication
Includes statically-compiled binary CLI
written in Go
entrypoint for anyone using Terraform.
open source code
github.com/hashicorp/terraform.
Terraform Plugins
expose an implementation for a specific
service provider e.g. AWS, or
provisioner e.g. bash.
written in Go
executable binaries invoked by Terraform Core over RPC.
Each plugin exposes an implementation for a specific
service e.g. AWS, or
provisioner, e.g. bash.
All Providers and Provisioners used in Terraform configurations are plugins.
Provider:
Actual service with which we want to provision resources
e.g. create ec2 instance
Provisioners:
execute scripts on a local or remote machine as part of resource creation
e.g. install java on an ec2 instance
Executed as a separate process
communicate with the main Terraform binary over an RPC interface.
Terraform has several Provisioners built-in
Providers are discovered dynamically as needed
so developers do not need to manage either.
»The primary responsibilities of Provider Plugins are:
Initialization of any included libraries used to make API calls
Authentication with the Infrastructure Provider
Define Resources that map to specific Services
Terraform Lifecycle
-------------------
Terraform lifecycle consists of –
#validate: validates the syntax
init,
plan,
apply
destroy.
Terraform init
initializes the working directory which consists of all the configuration files
Terraform plan
creates an execution plan to reach a desired state of the infrastructure. Changes in the configuration files are done in order to achieve the desired state.
This is optional
Terraform apply
Makes the changes in the infrastructure as defined in the plan, and the infrastructure comes to the desired state.
Terraform destroy
delete all the old infrastructure resources, which are marked tainted after the apply phase.
Terraform Core
---------------
Terraform core
uses two input sources to do its job.
first input source
User configured Terraform configuration
define what needs to be created or provisioned.
second input source
state where terraform keeps the current state.
Utility which can calculate the delta between the current state and the desired state -
make/apply these changes on the infrastructure.
terraform core
takes the input
figures out the plan of what needs to be done.
Compares current
state and configuration
with
desired state and configuration
Figures out plan to get to that desired state.
i.e. what needs to be
created
updated
deleted
to provision the infrastructure.
CRUD: create, read, update and delete
Providers
---------
Second component of the architecture
could be cloud providers like
AWS,
Azure,
GCP
other infrastructure as service platform.
It is also a provider for more high-level components like Kubernetes or other platform-as-a-service tools, even some software as a self-service tool.
Supports
For example –
create an AWS infrastructure
deploy Kubernetes on top of it
create services/components inside that Kubernetes cluster.
Terraform has
over a hundred providers
different technologies
each provider then gives terraform user access to its resources.
For e.g. AWS provider
gives access to hundreds of AWS resources
like EC2 instances
AWS users, etc.
With Kubernetes provider
access to commodities resources like services and deployments and namespaces, etc.
Further reference: https://geekflare.com/terraform-for-beginners/
HCL
---
Low-level syntax of Terraform language
defined in HCL (HashiCorp configuration language)
also used by configuration languages in other applications
particular other HashiCorp products.
Full definition of HCL syntax can be seen in https://github.com/hashicorp/hcl/blob/hcl2/hclsyntax/spec.md
Includes
Arguments
Blocks
Identifiers
Comments
Arguments
---------
An argument assigns a value to a particular name:
image_id = "abc123"
Syntax is like
argument name / identifier = argument's value.
Terraform uses the word "attribute" instead of "argument".
Blocks
------
A block is a container for other content:
}
Syntax
<block type> <parameters> {
key1 = value1
key2 = value2
}
Block
-----
Block options
resource
provider
terraform
settings
input variables - variable
output - output
data sources - data
ect.
Types of block
Top level
Block inside block
Defined in curly braces.
Has key value pair
Defines
an infrastructure platform
a set of resources with in that we want to create/manage
e.g. we want to create a file
mkdir temp
cd temp
Identifiers
----------
In key = value
key - identifier
value - argument value
Arguments
Mandatory arguments
Optional arguments
Meta arguments
Comments
Character Encoding and Line Endings
Comments
--------
//single line
/*
multi-line comment
*/
-------------------------------------
Terraform Resources
vi local.tf
<block type> "<block label>" "Block Name" {
#Block body
<Identifier> = <Expression> #Argument
}
resource "local_file" "vilas"{
filename = "/root/vilas.txt"
content = "My name is Vilas"
}
-------------------------------------
This is a standard terraform block because the look and curly braces.
type of block : resource
defined by terraform
local_file: resource type
fixed value
depends on the provider
provides two information
seperated by "_"
first: provider
second: type of resource
"vilas": resource name. variable name - other syntax
Logical name
Can be named anything.
{Arguments}
Specific to type of resource we are creating.
Here specific to local_file.
filename: absolute path to the location where we want to create file.
content: content which should be in the file.
arguments vary based on the resource type.
We should follow the standard defined by the resource type.
-------------------------------------
resource "aws_instance" "example" {
ami = "abc123"
network_interface {
# ...
}
}
type: resource
provider: aws
require: EC2 instance
example: name
ami: ami of the instance
network_interface: network interface for the instance
-------------------------------------
Update local.tf
vi local.tf
resource "local_file" "vilas"{
filename = "/root/vilas.txt"
content = "My name is Vilas!!"
file_permission = "0700"
}
-------------------------------------
terraform apply
terraform will delete and create a new file.
-------------------------------------
terraform init
executed from a directory with terraform configurations
terraform downloads and installs plugins for provider used in the configuration.
shows the version of the plugin installed
more on plugins latter
Providers
---------
can be
cloud providers
aws
azure
gcp ect.
local providers
ect.
Distributed by HashiCorp
Publicly available in the Terraform registry
registry.terraform.io
3 tiers of providers
1. Owned and maintained by HashiCorp
e.g.
aws
azure
gcp .
local providers
regirsty.hashicorp.io
2. Verified provider
Owned and maintained by 3rd party provider company
Company in partnership with HashiCorp
e.g.
bigip provider from FI network
heroku
digitalocean
3. Community providers
Published and maintained by individual community providers of HashiCorp community.
activedirectory
ucloud
netapp-gcp
Terraform uses a plugins based architecture
to work with 100's of infrastructure platforms
Plugins
-------
Terraform init downloads and installs plugins
Provider specific.
Installed into a <directory>/.terraform/
<directory>
directory where terraform configuration files are present.
Generate terraform init is executed being here.
plugin name : source address
e.g. hashicorp/local
can be seen while executing terraform init.
indentifier to locate and download pluigns
hashicorp: organizational namespace
local: type - provider name
can be
aws
azure
rm
plugin name can have a host name
registy.terraform.io/hashicorp/local
--------------------------------------------------------------------------------------------
Configuration Directory
-----------------------
Directory can have any number of configuration files.
Any file with .tf extension will participate in CRUD of the infrastructure components.
One file may have any number of configuraiton blocks.
Common naming convention: main.tf, terraform.tfvars, providers.tf, output.tf and variables.tf
Common other files found
main.tf - main configuration
variables.tf - variables delclaration
outputs.tf - outputs from resources.
providers.tf - define providers
can be .tf.json also - but commonly used.
Multiple Providers
------------------
Terraform supports working with multiple providers
e.g. random
can produce
random_id
random_password
random_int
random_string
ect.
Further reference: https://www.youtube.com/watch?v=YcJ9IeukJL8
Find
az account list-locations -o table
Core concepts/terminologies used in Terraform:
---------------------------------------------
Variables
Input-variables
like function arguments
Output variables
like function return values
Local values
like a function's temporary local variables.
Input-variables:
Also called
Variables
Terraform variables
key-value pair
used by Terraform modules to allow customization.
Serve as parameters for a Terraform module
module can be customized without altering the module's own source code
modules can be reused between different configurations.
While declaring variables in the root module of your configuration
you can set their values using CLI options and environment variables.
While declaring variables in child modules
the calling module should pass values in the module block.
Output Variables
id of a resource
Module:
Folder with Terraform templates
all the Terraform configurations are defined here
Similar to function definitions in traditional languages
State:
Consists of cached information about the infrastructure managed by Terraform and the related configurations.
Resources:
It refers to a block of one or more infrastructure objects
compute instances
virtual networks, etc.
used in configuring and managing the infrastructure.
Data Source:
Implemented by providers to return information on external objects to terraform.
We can define our own data sources - which reads data from existing resources and returns it to us for use in terraform.
e.g. get ami id in aws.
Output Values:
Return values of a terraform module that can be used by other configurations.
Plan:
One of the stages
Determines what needs to be
created,
updated, or
destroyed to move from
real/current state of the infrastructure --> desired state.
Apply:
One of the stages
Applies the changes real/current state of the infrastructure in order to move to the desired state.
Destroy
Removes all configurations applied as defined in the module
Variables
---------
Declaring an Input Variable
Each input variable accepted by a module must be declared using a variable block:
------------------------------------------------------
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"
}
]
}
------------------------------------------------------
The label
after the variable keyword
like a variable in the function.
name for the variable (image_id e.g.)
must be unique among all variables with in a module.
name used to
assign a value to the variable from outside
reference the variable's value from within the module.
can be any valid identifier except the following:
source,
version,
providers,
count,
for_each,
lifecycle,
depends_on,
locals.
These names are reserved for meta-arguments in module configuration blocks
cannot be declared as variable names.
Like other blocks, variable also supports attributes
Following optional arguments for variable declarations:
default -
default value
If present, the variable is considered to be optional
default value will be used if no value is set
Should be a literal value
cannot reference other objects in the configuration.
type -
define type of variable.
allows you to restrict the type of value
type constraints are optional
recommend specifying them
If no type constraint is set
then a value of any type is accepted.
Advantages
helpful reminders for users
Terraform can return a helpful error message if the wrong type is used.
e.g. Supported type keywords (value) are:
string
number
bool
any
keyword any
indicate that any type is acceptable.
The type constructors allow you to specify complex types such as collections:
list(<TYPE>)
set(<TYPE>)
map(<TYPE>)
object({<ATTR NAME> = <TYPE>, ... })
tuple([<TYPE>, ...])
If both the type and default arguments are specified,
the given default value must be convertible to the specified type.
description -
description.
Input Variable Documentation
variable "image_id" {
type = string
description = "The id of the machine image (AMI) to use for the server."
}
Concisely explain the
purpose of the variable
what kind of value is expected.
Might be included in documentation
writte from the perspective of the user and not dev.
validation -
A block
define validation rules
usually in addition to type constraints.
Custom Validation Rules
Feature introduced in Terraform CLI v0.13.0.
Module author can specify custom validation rules
use validation block nested within the corresponding variable block:
--------------------------------------------------------------------------------------
variable "image_id" {
type = string
description = "The id of the machine image (AMI) to use for the server."
validation {
condition = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-"
error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"."
}
}
--------------------------------------------------------------------------------------
condition argument
expression must use the value of the variable to return
true if the value is valid
false if it is invalid.
expression can refer only to the variable that the condition applies to
expression must not produce errors.
If the failure of an expression is the basis of the validation decision,
use the can function to detect such errors. For example:
variable "image_id" {
type = string
description = "The id of the machine image (AMI) to use for the server."
validation {
# regex(...) fails if it cannot find a match
condition = can(regex("^ami-", var.image_id))
error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"."
}
}
If condition evaluates to false
Terraform will produce an error message
includes the sentences given in error_message.
The error message string should be at least one full sentence explaining the constraint that failed
---------------------------
sensitive -
Limits Terraform UI output when the variable is used in configuration.
»
Suppressing Values in CLI Output
--------------------------------
Feature was introduced in Terraform v0.14.0.
Hands-on: Try the Protect Sensitive Input Variables tutorial on HashiCorp Learn.
Setting a variable as sensitive prevents Terraform from showing its value in the plan or apply output
when you use that variable elsewhere in your configuration.
Terraform will still record sensitive values in the state
anyone who can access the state data will have access to the sensitive values in cleartext.
Declare a variable as sensitive by setting the sensitive argument to true:
variable "user_information" {
type = object({
name = string
address = string
})
sensitive = true
}
resource "some_resource" "a" {
name = var.user_information.name
address = var.user_information.address
}
Any expressions whose result depends on the sensitive variable will be treated as sensitive
so in the above example
"some_resource" "a" will also be hidden in the plan output:
Terraform will perform the following actions:
# some_resource.a will be created
+ resource "some_resource" "a" {
+ name = (sensitive)
+ address = (sensitive)
}
Plan: 1 to add, 0 to change, 0 to destroy.
In some cases where you use a sensitive variable inside a nested block, Terraform may treat the entire block as redacted. This happens for resource types where all of the blocks of a particular type are required to be unique, and so disclosing the content of one block might imply the content of a sibling block.
# some_resource.a will be updated in-place
~ resource "some_resource" "a" {
~ nested_block {
# At least one attribute in this block is (or was) sensitive,
# so its contents will not be displayed.
}
}
A provider can also declare an attribute as sensitive, which will cause Terraform to hide it from regular output regardless of how you assign it a value. For more information, see Sensitive Resource Attributes.
If you use a sensitive value from as part of an output value then Terraform will require you to also mark the output value itself as sensitive, to confirm that you intended to export it.
»
Cases where Terraform may disclose a sensitive variable
A sensitive variable is a configuration-centered concept, and values are sent to providers without any obfuscation. A provider error could disclose a value if that value is included in the error message. For example, a provider might return the following error even if "foo" is a sensitive value: "Invalid value 'foo' for field"
If a resource attribute is used as, or part of, the provider-defined resource id, an apply will disclose the value. In the example below, the prefix attribute has been set to a sensitive variable, but then that value ("jae") is later disclosed as part of the resource id:
# random_pet.animal will be created
+ resource "random_pet" "animal" {
+ id = (known after apply)
+ length = 2
+ prefix = (sensitive)
+ separator = "-"
}
Plan: 1 to add, 0 to change, 0 to destroy.
...
random_pet.animal: Creating...
random_pet.animal: Creation complete after 0s [id=jae-known-mongoose]
»
Using Input Variable Values
Within the module that declared a variable, its value can be accessed from within expressions as var.<NAME>, where <NAME> matches the label given in the declaration block:
Note: Input variables are created by a variable block, but you reference them as attributes on an object named var.
resource "aws_instance" "example" {
instance_type = "t2.micro"
ami = var.image_id
}
The value assigned to a variable can only be accessed in expressions within the module where it was declared.
»
Assigning Values to Root Module Variables
When variables are declared in the root module of your configuration, they can be set in a number of ways:
In a Terraform Cloud workspace.
Individually, with the -var command line option.
In variable definitions (.tfvars) files, either specified on the command line or automatically loaded.
As environment variables.
The following sections describe these options in more detail. This section does not apply to child modules, where values for input variables are instead assigned in the configuration of their parent module, as described in Modules.
»
Variables on the Command Line
To specify individual variables on the command line, use the -var option when running the terraform plan and terraform apply commands:
terraform apply -var="image_id=ami-abc123"
terraform apply -var='image_id_list=["ami-abc123","ami-def456"]' -var="instance_type=t2.micro"
terraform apply -var='image_id_map={"us-east-1":"ami-abc123","us-east-2":"ami-def456"}'
The above examples show appropriate syntax for Unix-style shells, such as on Linux or macOS. For more information on shell quoting, including additional examples for Windows Command Prompt, see Input Variables on the Command Line.
You can use the -var option multiple times in a single command to set several different variables.
»
Variable Definitions (.tfvars) Files
To set lots of variables, it is more convenient to specify their values in a variable definitions file (with a filename ending in either .tfvars or .tfvars.json) and then specify that file on the command line with -var-file:
terraform apply -var-file="testing.tfvars"
Note: This is how Terraform Cloud passes workspace variables to Terraform.
A variable definitions file uses the same basic syntax as Terraform language files, but consists only of variable name assignments:
image_id = "ami-abc123"
availability_zone_names = [
"us-east-1a",
"us-west-1c",
]
Terraform also automatically loads a number of variable definitions files if they are present:
Files named exactly terraform.tfvars or terraform.tfvars.json.
Any files with names ending in .auto.tfvars or .auto.tfvars.json.
Files whose names end with .json are parsed instead as JSON objects, with the root object properties corresponding to variable names:
{
"image_id": "ami-abc123",
"availability_zone_names": ["us-west-1a", "us-west-1c"]
}
»
Environment Variables
As a fallback for the other ways of defining variables, Terraform searches the environment of its own process for environment variables named TF_VAR_ followed by the name of a declared variable.
This can be useful when running Terraform in automation, or when running a sequence of Terraform commands in succession with the same variables. For example, at a bash prompt on a Unix system:
$ export TF_VAR_image_id=ami-abc123
$ terraform plan
...
On operating systems where environment variable names are case-sensitive, Terraform matches the variable name exactly as given in configuration, and so the required environment variable name will usually have a mix of upper and lower case letters as in the above example.
»
Complex-typed Values
When variable values are provided in a variable definitions file, you can use Terraform's usual syntax for literal expressions to assign complex-typed values, like lists and maps.
Some special rules apply to the -var command line option and to environment variables. For convenience, Terraform defaults to interpreting -var and environment variable values as literal strings, which need only shell quoting, and no special quoting for Terraform. For example, in a Unix-style shell:
$ export TF_VAR_image_id='ami-abc123'
However, if a root module variable uses a type constraint to require a complex value (list, set, map, object, or tuple), Terraform will instead attempt to parse its value using the same syntax used within variable definitions files, which requires careful attention to the string escaping rules in your shell:
$ export TF_VAR_availability_zone_names='["us-west-1b","us-west-1d"]'
For readability, and to avoid the need to worry about shell escaping, we recommend always setting complex variable values via variable definitions files. For more information on quoting and escaping for -var arguments, see Input Variables on the Command Line.
»
Values for Undeclared Variables
If you have defined a variable value, but not its corresponding variable {} definition, you may get an error or warning depending on how you have provided that value.
If you provide values for undeclared variables defined as environment variables you will not get an error or warning. This is because environment variables may be declared but not used in all configurations that might be run.
If you provide values for undeclared variables defined in a file you will get a warning. This is to help in cases where you have provided a variable value meant for a variable declaration, but perhaps there is a mistake in the value definition. For example, the following configuration:
variable "moose" {
type = string
}
And the following .tfvars file:
mosse = "Moose"
Will cause Terraform to warn you that there is no variable declared "mosse", which can help you spot this mistake.
If you use .tfvars files across multiple configurations and expect to continue to see this warning, you can use the -compact-warnings option to simplify your output.
If you provide values for undeclared variables on the command line, Terraform will error. To avoid this error, either declare a variable block for the value, or remove the variable value from your Terraform call.
»
Variable Definition Precedence
The above mechanisms for setting variables can be used together in any combination. If the same variable is assigned multiple values, Terraform uses the last value it finds, overriding any previous values. Note that the same variable cannot be assigned multiple values within a single source.
Terraform loads variables in the following order, with later sources taking precedence over earlier ones:
Environment variables
The terraform.tfvars file, if present.
The terraform.tfvars.json file, if present.
Any *.auto.tfvars or *.auto.tfvars.json files, processed in lexical order of their filenames.
Any -var and -var-file options on the command line, in the order they are provided. (This includes variables set by a Terraform Cloud workspace.)
Important: In Terraform 0.12 and later, variables with map and object values behave the same way as other variables: the last value found overrides the previous values. This is a change from previous versions of Terraform, which would merge map values instead of overriding them.
---------------------------------------------------------------------------------------------------------------------------------------------------------
Skipping
Install VSCode Editor, VS Code Terraform Plugin and AWS CLI
Windows: Install Terraform & AWS CLI on Windows
Step-03: Configure AWS CLI
Linux: Install Terraform Windows
---------------------------------------------------------------------------------------------------------------------------------------------------------
Terraform Workflow
using Terraform Commands
AMI ID and Region
Terraform core commands
Terraform Configuration Syntax
Terraform Arguments, Meta-Arguments and Attributes
Blocks in Terraform
Terraform Top Level Blocks
Terraform fundamental block
Terraform Settings Block Introduction
required_version in Terraform Block
required_providers in Terraform Block
Terraform Providers
Understand about Provider Block
Create VPC Resource, Test and Clean-Up
Terraform Multiple Providers and clean up
Terraform Provider Dependency Lock File
Create S3 bucket with existing Lock File AWS provider version
Upgrade AWS Provider, Test, Fix S3 Bucket Issues and Clean-Up
Resources
Terraform Resources Syntax Introduction
Terraform Resources Behavior Part-1
Terraform State
terraform.tfstate file
Terraform Resource
Update In Place
Destroy and Recreate and Destroy
Terraform Desired & Current State
Clean-Up
Resources Meta-Arguments
depends_on
Create Key Pair terraform-key and also review c1-versions.tf
Create VPC
Create EC2 Instance