-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelp-terraform.txt
340 lines (239 loc) · 9.58 KB
/
help-terraform.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
Terraform
---------
Terraform is open source, created by HashiCorp.
Terraform code is written in HashiCorp Configuration Language (HCL).
Terraform language: https://www.terraform.io/docs/language/index.html
Terraform providers: https://www.terraform.io/docs/language/providers/index.html
Terraform registry: https://registry.terraform.io/browse/providers
https://registry.terraform.io/providers/hashicorp/aws/latest/docs
Terraform AWS git: https://github.com/hashicorp/terraform-provider-aws
Book
----
Terraform: Up and Running, Second Edition by Yevgeniy Brikman (O’Reilly).
Copyright 2019, Yevgeniy Brikman, 978-1-492-04690-5.
Errata: https://www.oreilly.com/catalog/errata.csp?isbn=0636920225010
Code: https://github.com/brikis98/terraform-up-and-running-code
Installation
------------
Install terraform extensions in Visual Studio Code:
Select extensions.
Search for Terraform and install.
You must perform a terraform init to get up-to-date provider schemas !!
(ensure that valid dummy tf file is present, otherwise terraform init fails).
Trigger IntelliSense (code completion/assist) in any editor window by typing Ctrl+Space.
Install terraform (v1.0.11), 10 December 2021:
Via Pamac package manager (Linux Manjaro)
Check Terraform version:
terraform -v
Note: When using AWS, create an IAM user with the right (managed) policies attached, for example:
- AmazonEC2FullAccess
- AmazonS3FullAccess
- AmazonDynamoDBFullAccess
- AmazonRDSFullAccess
- CloudWatchFullAccess
- IAMFullAccess
Terraform needs the AWS credentials for the IAM user. Do this
- by exporting environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.
- or by using the credentials in $HOME/.aws/credentials
NOTE: STORING CREDENTIALS IN HOME DIRECTORY IS A SECURITY RISK!
DON'T DO THIS!
Style and Syntax
----------------
Style Conventions:
- Indent two spaces for each nesting level.
- You can enforce these conventions automatically by running terraform fmt.
- Automatic source code formatting tools apply these conventions automatically.
Terraform language comments:
- # begins a single-line comment (default comment style)
- // also begins a single-line comment
- /* and */ are start and end delimiters for multi-line comments
General syntax for creating a resource in Terraform is:
resource "<PROVIDER>_<TYPE>" "<NAME>" {
[CONFIG ...]
}
Terraform types
---------------
string: a sequence of Unicode characters, like "hi".
number: a numeric value, either a whole number like 15 or fractional like 3.14.
bool: a boolean value, either true or false
list (or tuple): a sequence of values, like ["a", 15, true]. Index of list starts with zero.
map (or object): a group of values identified by named labels.
Key/value pairs can be separated by either a comma or a line break.
The keys in a map must be strings; they can be left unquoted if they are a valid identifier,
but must be quoted otherwise.
{name = "Marry", age = 34}.
{
name = "Peter"
age = 45
}
null: a special value that has no type; a value that represents absence or omission.
Terraform automatically converts number and bool values to strings when needed.
It also converts strings to numbers or bools.
Providers
---------
Terraform uses plugins called "providers" to interact with cloud and SaaS providers.
The first step is to configure the provider(s) you want to use.
For example create a file called main.tf or providers.tf.
Configure the AWS Provider
Terraform 0.13 and later:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
Configure the AWS Provider
Terraform 0.12 and earlier:
provider "aws" {
version = "~> 3.0" # will be deprecated
region = "us-east-1"
}
resource "aws_instance" "app" {
instance_type = "t2.micro"
availability_zone = "us-east-1"
ami = "ami-a0cfeed8"
user_data = <<-EOF
#!/bin/bash
sudo service apache2 start
EOF
}
Input variables
---------------
Define variables in e.g. variables.tf
variable "instance_name_tag" {
description = "Value of the Name tag for the EC2 instance"
type = string
default = "AppServerInstance"
}
Reference variable in resource definition:
resource "aws_instance" "app_server" {
ami = "ami-08d70e59c07c61a3a"
instance_type = "t2.micro"
tags = {
Name = var.instance_name_tag
}
}
Variables can also be provided via CLI either via tf-file or via variable name
#TODO examples
Variables can also be locally defined:
locals {
instance_type = "t3.micro"
}
And then referenced:
resource "aws_instance" "my_web1" {
ami = "ami-a0cfeed8"
instance_type = local.instance_type
tags = {
name = "web server"
zone = "presentation"
}
}
Output variables
----------------
Output values are similar to return values in programming languages. They can be used on the command line or in other Terraform configurations.
output "instance_ip_addr" {
value = aws_instance.server.private_ip
description = "The private IP address of the main server instance."
}
In a parent module, outputs of child modules are available as module.<MODULE NAME>.<OUTPUT NAME>:
For example, for a child module named web_server:
module.web_server.instance_ip_addr.
Sensitive values can be hidden in terraform plan and terraform apply messages:
output "db_password" {
value = aws_db_instance.db.password
description = "The password for logging in to the database."
sensitive = true
}
To print all the output:
terraform output
Interpolation
-------------
A ${ ... } sequence is an interpolation, which evaluates the expression given between the markers,
converts the result to a string if necessary, and then inserts it into the final string:
variable "name" {
type = string
default = "Terraform user"
}
"Hello, ${var.name}!"
produces:
"Hello, Terraform user!".
Conditional Expression
----------------------
condition ? true_val : false_val
If condition is true then the result is true_val.
If condition is false then the result is false_val.
For example, if var.a is an empty string then the result is "default-a", but otherwise it is the actual value of var.a.
var.a != "" ? var.a : "default-a"
or
var.a = "" ? : "default-a" : var.a
Loops - with the for_each Meta-Argument
---------------------------------------
for_each is a meta-argument. It can be used with modules and with every resource type.
for_each accepts a map or a set of strings, and creates an instance for each item in that map or set.
each.key The map key (or set member) corresponding to this instance.
each.value The map value corresponding to this instance. (If a set was provided, this is the same as each.key.)
resource "aws_iam_user" "accounts" {
for_each = toset( ["Jan", "Thomas", "Pete"] )
name = each.key
}
#TODO dynamic blocks
Loops - for Expressions
-----------------------
[for s in var.list : upper(s)]
[for k, v in var.map : length(k) + length(v)]
[for i, v in var.list : "${i} is ${v}"]
The type of brackets around the for expression decide what type of result it produces.
- [ and ] produces a list/tuple.
- { and } produces a map/object and you must provide two result expressions that are separated by the => symbol
{for s in var.list : s => upper(s)}
{
foo = "FOO"
bar = "BAR"
bah = "BAH"
}
Terraform files
---------------
Terraform files have extension .tf
main.tf
providers.tf
variables.tf
Terraform commands
------------------
# Terraform help
terraform
terraform -h
terraform --help
# Main Terraform cyclus:
terraform init
terraform plan
terraform apply
# Main Terraform commands:
terraform init Prepare your working directory for other commands
terraform validate Check whether the configuration is valid
terraform plan Show changes required by the current configuration
terraform apply Create or update infrastructure
terraform destroy Destroy previously-created infrastructure
# Other Terraform commands:
terraform console Try Terraform expressions at an interactive command prompt
terraform fmt Reformat your configuration in the standard style
terraform force-unlock Release a stuck lock on the current workspace
terraform get Install or upgrade remote Terraform modules
terraform graph Generate a Graphviz graph of the steps in an operation
terraform import Associate existing infrastructure with a Terraform resource
terraform login Obtain and save credentials for a remote host
terraform logout Remove locally-stored credentials for a remote host
terraform output Show output values from your root module
terraform providers Show the providers required for this configuration
terraform refresh Update the state to match remote systems
terraform show Show the current state or a saved plan
terraform state Advanced state management
terraform taint Mark a resource instance as not fully functional
terraform test Experimental support for module integration testing
terraform untaint Remove the 'tainted' state from a resource instance
terraform version Show the current Terraform version
terraform workspace Workspace management