| 1 |
export TF_LOG=TRACE |
| 2 |
|
| 3 |
# An AMI |
| 4 |
variable "ami" { |
| 5 |
description = "the AMI to use" |
| 6 |
} |
| 7 |
|
| 8 |
/* A multi |
| 9 |
line comment. */ |
| 10 |
resource "aws_instance" "web" { |
| 11 |
ami = "${var.ami}" |
| 12 |
count = 2 |
| 13 |
source_dest_check = false |
| 14 |
|
| 15 |
connection { |
| 16 |
user = "root" |
| 17 |
} |
| 18 |
} |
| 19 |
|
| 20 |
resource "aws_instance" "web" { |
| 21 |
subnet = "${var.env == "production" ? var.prod_subnet : var.dev_subnet}" |
| 22 |
} |
| 23 |
|
| 24 |
variable "count" { |
| 25 |
default = 2 |
| 26 |
} |
| 27 |
|
| 28 |
variable "hostnames" { |
| 29 |
default = { |
| 30 |
"0" = "example1.org" |
| 31 |
"1" = "example2.net" |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
data "template_file" "web_init" { |
| 36 |
# Render the template once for each instance |
| 37 |
count = "${length(var.hostnames)}" |
| 38 |
template = "${file("templates/web_init.tpl")}" |
| 39 |
vars { |
| 40 |
# count.index tells us the index of the instance we are rendering |
| 41 |
hostname = "${var.hostnames[count.index]}" |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
resource "aws_instance" "web" { |
| 46 |
# Create one instance for each hostname |
| 47 |
count = "${length(var.hostnames)}" |
| 48 |
|
| 49 |
# Pass each instance its corresponding template_file |
| 50 |
user_data = "${data.template_file.web_init.*.rendered[count.index]}" |
| 51 |
} |
| 52 |
|
| 53 |
variable "count" { |
| 54 |
default = 2 |
| 55 |
} |
| 56 |
|
| 57 |
# Define the common tags for all resources |
| 58 |
locals { |
| 59 |
common_tags = { |
| 60 |
Component = "awesome-app" |
| 61 |
Environment = "production" |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
# Create a resource that blends the common tags with instance-specific tags. |
| 66 |
resource "aws_instance" "server" { |
| 67 |
ami = "ami-123456" |
| 68 |
instance_type = "t2.micro" |
| 69 |
|
| 70 |
tags = "${merge( |
| 71 |
local.common_tags, |
| 72 |
map( |
| 73 |
"Name", "awesome-app-server", |
| 74 |
"Role", "server" |
| 75 |
) |
| 76 |
)}" |
| 77 |
} |
| 78 |
|
| 79 |
$ terraform apply -var foo=bar -var foo=baz |
| 80 |
$ terraform apply -var 'foo={quux="bar"}' -var 'foo={bar="baz"}' |
| 81 |
|
| 82 |
$ terraform apply -var-file=foo.tfvars -var-file=bar.tfvars |
| 83 |
$ TF_VAR_somemap='{foo = "bar", baz = "qux"}' terraform plan |
| 84 |
|
| 85 |
resource "aws_instance" "web" { |
| 86 |
# ... |
| 87 |
|
| 88 |
count = "${var.count}" |
| 89 |
|
| 90 |
# Tag the instance with a counter starting at 1, ie. web-001 |
| 91 |
tags { |
| 92 |
Name = "${format("web-%03d", count.index + 1)}" |
| 93 |
} |
| 94 |
} |