-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathTerraform.txt
More file actions
1702 lines (1364 loc) · 40.7 KB
/
Terraform.txt
File metadata and controls
1702 lines (1364 loc) · 40.7 KB
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
# TERRAFORM - Infrastructure as Code Reference - by Richard Rembert
# Terraform is an open-source Infrastructure as Code (IaC) tool for building, changing, and versioning infrastructure
# Supports multiple cloud providers (AWS, Azure, GCP, etc.) and services through providers
# INSTALLATION AND SETUP
# Install Terraform (Ubuntu/Debian)
curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -
sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
sudo apt-get update && sudo apt-get install terraform
# Install Terraform (macOS)
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
# or
brew install terraform
# Install Terraform (Windows)
# Download from https://www.terraform.io/downloads
# Or use Chocolatey: choco install terraform
# Or use Scoop: scoop install terraform
# Install specific version with tfenv (version manager)
git clone https://github.com/tfutils/tfenv.git ~/.tfenv
echo 'export PATH="$HOME/.tfenv/bin:$PATH"' >> ~/.bashrc
tfenv install 1.6.0
tfenv use 1.6.0
# Verify installation
terraform --version
terraform -help
# Enable tab completion
terraform -install-autocomplete
# Set up environment
export TF_LOG=INFO # Enable logging (TRACE, DEBUG, INFO, WARN, ERROR)
export TF_LOG_PATH="./terraform.log" # Log to file
export TF_DATA_DIR=".terraform" # Terraform working directory
export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache" # Plugin cache
# Create plugin cache directory
mkdir -p $HOME/.terraform.d/plugin-cache
# TERRAFORM BASICS AND CONCEPTS
# Core Concepts:
# - Provider: Plugin that manages resources for a specific service (AWS, Azure, etc.)
# - Resource: Infrastructure component (EC2 instance, S3 bucket, etc.)
# - Data Source: Read-only information from existing infrastructure
# - Variable: Input parameters for configurations
# - Output: Return values from configurations
# - Module: Reusable Terraform configurations
# - State: Mapping between configuration and real-world resources
# File Structure:
# main.tf - Primary configuration
# variables.tf - Variable definitions
# outputs.tf - Output definitions
# terraform.tfvars - Variable values
# versions.tf - Provider version constraints
# locals.tf - Local values
# BASIC TERRAFORM WORKFLOW
# 1. Initialize Terraform (downloads providers, sets up backend)
terraform init # Initialize current directory
terraform init -upgrade # Upgrade providers to latest allowed version
terraform init -reconfigure # Reconfigure backend
terraform init -migrate-state # Migrate state to new backend
# 2. Planning (preview changes)
terraform plan # Show planned changes
terraform plan -out=tfplan # Save plan to file
terraform plan -target=aws_instance.web # Plan specific resource
terraform plan -var="environment=production" # Override variable
terraform plan -var-file="prod.tfvars" # Use variable file
terraform plan -destroy # Plan destruction
# 3. Applying changes
terraform apply # Apply changes (with confirmation)
terraform apply -auto-approve # Apply without confirmation
terraform apply tfplan # Apply saved plan
terraform apply -target=aws_instance.web # Apply specific resource
terraform apply -var="instance_type=t3.small" # Override variable
# 4. Destroying infrastructure
terraform destroy # Destroy all resources (with confirmation)
terraform destroy -auto-approve # Destroy without confirmation
terraform destroy -target=aws_instance.web # Destroy specific resource
# Validation and formatting
terraform validate # Validate configuration syntax
terraform fmt # Format configuration files
terraform fmt -check # Check if files are formatted
terraform fmt -recursive # Format files recursively
# BASIC TERRAFORM CONFIGURATION
# Basic main.tf example
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
random = {
source = "hashicorp/random"
version = "~> 3.1"
}
}
}
# Provider configuration
provider "aws" {
region = var.aws_region
default_tags {
tags = {
Environment = var.environment
Project = var.project_name
ManagedBy = "Terraform"
}
}
}
# Simple resource example
resource "aws_instance" "web" {
ami = "ami-0c02fb55956c7d316" # Amazon Linux 2
instance_type = "t3.micro"
tags = {
Name = "web-server"
}
}
# Data sources
data "aws_availability_zones" "available" {
state = "available"
}
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-22.04-amd64-server-*"]
}
}
# VARIABLES AND OUTPUTS
# variables.tf - Input variables
variable "aws_region" {
description = "AWS region for resources"
type = string
default = "us-west-2"
validation {
condition = can(regex("^[a-z]{2}-[a-z]+-[0-9]+$", var.aws_region))
error_message = "The aws_region value must be a valid AWS region format."
}
}
variable "environment" {
description = "Environment name"
type = string
default = "development"
validation {
condition = contains([
"development",
"staging",
"production"
], var.environment)
error_message = "Environment must be development, staging, or production."
}
}
variable "project_name" {
description = "Name of the project"
type = string
default = "myapp"
}
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t3.micro"
}
variable "allowed_cidr_blocks" {
description = "CIDR blocks allowed to access resources"
type = list(string)
default = ["0.0.0.0/0"]
}
variable "enable_monitoring" {
description = "Whether to enable monitoring"
type = bool
default = true
}
variable "database_config" {
description = "Database configuration"
type = object({
engine = string
engine_version = string
instance_class = string
allocated_storage = number
})
default = {
engine = "postgres"
engine_version = "15.4"
instance_class = "db.t3.micro"
allocated_storage = 20
}
}
variable "tags" {
description = "Additional tags to apply to resources"
type = map(string)
default = {}
}
# Sensitive variables
variable "db_password" {
description = "Database password"
type = string
sensitive = true
default = ""
}
# outputs.tf - Return values
output "instance_id" {
description = "ID of the EC2 instance"
value = aws_instance.web.id
}
output "instance_public_ip" {
description = "Public IP address of the instance"
value = aws_instance.web.public_ip
}
output "availability_zones" {
description = "Available availability zones"
value = data.aws_availability_zones.available.names
}
# Complex outputs
output "instance_details" {
description = "Detailed instance information"
value = {
id = aws_instance.web.id
public_ip = aws_instance.web.public_ip
private_ip = aws_instance.web.private_ip
availability_zone = aws_instance.web.availability_zone
instance_type = aws_instance.web.instance_type
}
}
# Using variables
resource "aws_instance" "web_with_vars" {
ami = data.aws_ami.ubuntu.id
instance_type = var.instance_type
tags = merge(var.tags, {
Name = "${var.project_name}-web"
Environment = var.environment
})
}
# LOCAL VALUES
# locals.tf - Computed values
locals {
# Common tags used across resources
common_tags = {
Environment = var.environment
Project = var.project_name
Owner = "DevOps Team"
ManagedBy = "Terraform"
CreatedAt = formatdate("YYYY-MM-DD", timestamp())
}
# Environment-specific configuration
environment_config = {
development = {
instance_type = "t3.micro"
min_size = 1
max_size = 2
}
staging = {
instance_type = "t3.small"
min_size = 1
max_size = 3
}
production = {
instance_type = "t3.medium"
min_size = 2
max_size = 10
}
}
current_config = local.environment_config[var.environment]
# Computed values
name_prefix = "${var.project_name}-${var.environment}"
vpc_cidr = "10.0.0.0/16"
availability_zones = slice(data.aws_availability_zones.available.names, 0, 3)
public_subnet_cidrs = [
"10.0.1.0/24",
"10.0.2.0/24",
"10.0.3.0/24"
]
}
# Using locals in resources
resource "aws_instance" "web_with_locals" {
ami = data.aws_ami.ubuntu.id
instance_type = local.current_config.instance_type
tags = merge(local.common_tags, {
Name = "${local.name_prefix}-web"
})
}
# RESOURCE CONFIGURATION
# Basic resource syntax
resource "resource_type" "resource_name" {
argument1 = "value1"
argument2 = "value2"
# Nested block
block_name {
nested_argument = "value"
}
# Multiple blocks of same type
block_name {
nested_argument = "another_value"
}
}
# VPC and Networking Resources
resource "aws_vpc" "main" {
cidr_block = local.vpc_cidr
enable_dns_hostnames = true
enable_dns_support = true
tags = merge(local.common_tags, {
Name = "${local.name_prefix}-vpc"
})
}
resource "aws_internet_gateway" "main" {
vpc_id = aws_vpc.main.id
tags = merge(local.common_tags, {
Name = "${local.name_prefix}-igw"
})
}
# Public subnets using count
resource "aws_subnet" "public" {
count = length(local.public_subnet_cidrs)
vpc_id = aws_vpc.main.id
cidr_block = local.public_subnet_cidrs[count.index]
availability_zone = local.availability_zones[count.index]
map_public_ip_on_launch = true
tags = merge(local.common_tags, {
Name = "${local.name_prefix}-public-${count.index + 1}"
Type = "Public"
})
}
# Route table
resource "aws_route_table" "public" {
vpc_id = aws_vpc.main.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.main.id
}
tags = merge(local.common_tags, {
Name = "${local.name_prefix}-public-rt"
})
}
# Route table associations
resource "aws_route_table_association" "public" {
count = length(aws_subnet.public)
subnet_id = aws_subnet.public[count.index].id
route_table_id = aws_route_table.public.id
}
# Security Groups
resource "aws_security_group" "web" {
name = "${local.name_prefix}-web-sg"
description = "Security group for web servers"
vpc_id = aws_vpc.main.id
# HTTP
ingress {
description = "HTTP"
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = var.allowed_cidr_blocks
}
# HTTPS
ingress {
description = "HTTPS"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = var.allowed_cidr_blocks
}
# SSH
ingress {
description = "SSH"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = var.allowed_cidr_blocks
}
# All outbound traffic
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = merge(local.common_tags, {
Name = "${local.name_prefix}-web-sg"
})
}
# EC2 Instances
resource "aws_instance" "web" {
count = var.environment == "production" ? 3 : 1
ami = data.aws_ami.ubuntu.id
instance_type = local.current_config.instance_type
vpc_security_group_ids = [aws_security_group.web.id]
subnet_id = aws_subnet.public[count.index % length(aws_subnet.public)].id
user_data = base64encode(<<-EOF
#!/bin/bash
apt-get update
apt-get install -y nginx
systemctl start nginx
systemctl enable nginx
echo "<h1>Web Server ${count.index + 1}</h1>" > /var/www/html/index.html
EOF
)
tags = merge(local.common_tags, {
Name = "${local.name_prefix}-web-${count.index + 1}"
Type = "WebServer"
})
}
# TERRAFORM FUNCTIONS AND EXPRESSIONS
# String functions
locals {
# String manipulation
project_upper = upper(var.project_name)
project_title = title(var.project_name)
project_snake = replace(var.project_name, "-", "_")
# String formatting
resource_name = format("%s-%s-resource", var.project_name, var.environment)
padded_name = format("%04s", var.project_name)
# String interpolation
description = "Project: ${var.project_name}, Environment: ${var.environment}"
# String conditionals
environment_short = var.environment == "production" ? "prod" : var.environment == "staging" ? "stg" : "dev"
}
# Collection functions
locals {
# List operations
availability_zones_selected = slice(data.aws_availability_zones.available.names, 0, 3)
subnet_count = length(local.public_subnet_cidrs)
first_az = element(data.aws_availability_zones.available.names, 0)
# Map operations
current_config = local.environment_config[var.environment]
# Set operations
unique_azs = toset(data.aws_availability_zones.available.names)
}
# Conditional expressions
locals {
# Ternary operator
instance_count = var.environment == "production" ? 3 : 1
storage_size = var.environment == "production" ? 100 : 20
# Multiple conditions
backup_retention = (
var.environment == "production" ? 30 :
var.environment == "staging" ? 7 :
1
)
# Complex conditionals
monitoring_enabled = var.environment == "production" || var.environment == "staging"
}
# For expressions
locals {
# Transform list to map
subnet_map = {
for idx, subnet in aws_subnet.public :
subnet.availability_zone => subnet.id
}
# Filter and transform
large_configs = {
for name, config in local.environment_config :
name => config
if config.max_size > 5
}
}
# DYNAMIC BLOCKS
# Dynamic ingress rules
variable "ingress_rules" {
description = "List of ingress rules"
type = list(object({
description = string
from_port = number
to_port = number
protocol = string
cidr_blocks = list(string)
}))
default = [
{
description = "HTTP"
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
},
{
description = "HTTPS"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
]
}
resource "aws_security_group" "dynamic_example" {
name_prefix = "${local.name_prefix}-dynamic-"
vpc_id = aws_vpc.main.id
# Dynamic ingress rules
dynamic "ingress" {
for_each = var.ingress_rules
content {
description = ingress.value.description
from_port = ingress.value.from_port
to_port = ingress.value.to_port
protocol = ingress.value.protocol
cidr_blocks = ingress.value.cidr_blocks
}
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = local.common_tags
}
# STATE MANAGEMENT
# State commands
terraform state list # List resources in state
terraform state show aws_instance.web # Show specific resource
terraform state pull # Download state file
terraform state push terraform.tfstate # Upload state file
terraform state mv aws_instance.web aws_instance.web_server # Rename resource
terraform state rm aws_instance.web # Remove resource from state
# Import existing resources
terraform import aws_instance.web i-1234567890abcdef0
# Refresh state
terraform refresh # Update state with real infrastructure
# Backend configuration for remote state
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "infrastructure/terraform.tfstate"
region = "us-west-2"
# State locking
dynamodb_table = "terraform-locks"
encrypt = true
}
}
# Using remote state
data "terraform_remote_state" "network" {
backend = "s3"
config = {
bucket = "my-terraform-state"
key = "network/terraform.tfstate"
region = "us-west-2"
}
}
# Reference remote state outputs
resource "aws_instance" "app" {
ami = data.aws_ami.ubuntu.id
subnet_id = data.terraform_remote_state.network.outputs.public_subnet_ids[0]
}
# MODULES
# Module definition directory structure:
# modules/
# └── vpc/
# ├── main.tf
# ├── variables.tf
# ├── outputs.tf
# └── README.md
# Module usage
module "vpc" {
source = "./modules/vpc"
# Required variables
project_name = var.project_name
environment = var.environment
# VPC configuration
vpc_cidr = "10.0.0.0/16"
availability_zones = slice(data.aws_availability_zones.available.names, 0, 3)
public_subnet_cidrs = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
# Tags
tags = local.common_tags
}
# Use module outputs
resource "aws_instance" "app" {
ami = data.aws_ami.ubuntu.id
instance_type = var.instance_type
subnet_id = module.vpc.public_subnet_ids[0]
vpc_security_group_ids = [module.vpc.web_security_group_id]
tags = merge(local.common_tags, {
Name = "${local.name_prefix}-app"
})
}
# Module with for_each
module "environments" {
source = "./modules/environment"
for_each = toset(["development", "staging", "production"])
environment = each.key
project_name = var.project_name
instance_type = local.environment_config[each.key].instance_type
tags = {
Environment = each.key
Project = var.project_name
}
}
# Remote module from Terraform Registry
module "s3_bucket" {
source = "terraform-aws-modules/s3-bucket/aws"
version = "~> 3.0"
bucket = "${var.project_name}-${var.environment}-storage"
versioning = {
enabled = true
}
server_side_encryption_configuration = {
rule = {
apply_server_side_encryption_by_default = {
sse_algorithm = "AES256"
}
}
}
tags = local.common_tags
}
# WORKSPACES
# Workspace commands
terraform workspace list # List workspaces
terraform workspace new prod # Create new workspace
terraform workspace select prod # Switch to workspace
terraform workspace delete dev # Delete workspace
terraform workspace show # Show current workspace
# Workspace-specific configuration
locals {
workspace_config = {
development = {
instance_type = "t3.micro"
min_size = 1
max_size = 2
}
staging = {
instance_type = "t3.small"
min_size = 1
max_size = 3
}
production = {
instance_type = "t3.medium"
min_size = 2
max_size = 10
}
}
current_workspace_config = local.workspace_config[terraform.workspace]
# Workspace-specific naming
resource_prefix = "${var.project_name}-${terraform.workspace}"
}
# Use workspace configuration
resource "aws_instance" "workspace_example" {
ami = data.aws_ami.ubuntu.id
instance_type = local.current_workspace_config.instance_type
tags = {
Name = "${local.resource_prefix}-example"
Workspace = terraform.workspace
}
}
# DATA SOURCES
# AWS data sources
data "aws_caller_identity" "current" {}
data "aws_region" "current" {}
data "aws_availability_zones" "available" {
state = "available"
filter {
name = "zone-type"
values = ["availability-zone"]
}
}
data "aws_ami" "amazon_linux" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-gp2"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
}
data "aws_vpc" "existing" {
count = var.use_existing_vpc ? 1 : 0
filter {
name = "tag:Name"
values = ["${var.project_name}-vpc"]
}
}
data "aws_route53_zone" "domain" {
count = var.domain_name != "" ? 1 : 0
name = var.domain_name
private_zone = false
}
# External data source
data "external" "git_info" {
program = ["bash", "${path.module}/scripts/get_git_info.sh"]
}
# HTTP data source
data "http" "myip" {
url = "https://ipv4.icanhazip.com"
}
# Template file
data "template_file" "user_data" {
template = file("${path.module}/templates/user_data.tpl")
vars = {
project_name = var.project_name
environment = var.environment
region = data.aws_region.current.name
}
}
# PROVISIONERS
# File provisioner
resource "aws_instance" "bastion" {
count = var.create_bastion ? 1 : 0
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
key_name = var.key_pair_name
subnet_id = aws_subnet.public[0].id
vpc_security_group_ids = [aws_security_group.web.id]
# File provisioner
provisioner "file" {
source = "${path.module}/scripts/setup.sh"
destination = "/tmp/setup.sh"
connection {
type = "ssh"
user = "ubuntu"
private_key = file(var.ssh_private_key_path)
host = self.public_ip
}
}
# Remote-exec provisioner
provisioner "remote-exec" {
inline = [
"chmod +x /tmp/setup.sh",
"sudo /tmp/setup.sh"
]
connection {
type = "ssh"
user = "ubuntu"
private_key = file(var.ssh_private_key_path)
host = self.public_ip
}
}
tags = merge(local.common_tags, {
Name = "${local.name_prefix}-bastion"
})
}
# Local-exec provisioner
resource "null_resource" "local_command" {
triggers = {
instance_id = aws_instance.web[0].id
}
provisioner "local-exec" {
command = "echo 'Instance ${aws_instance.web[0].id} created'"
}
}
# RESOURCE LIFECYCLE
resource "aws_instance" "lifecycle_example" {
ami = data.aws_ami.ubuntu.id
instance_type = var.instance_type
lifecycle {
# Prevent destruction
prevent_destroy = var.environment == "production"
# Create before destroy
create_before_destroy = true
# Ignore changes to specific attributes
ignore_changes = [
ami,
user_data
]
}
tags = merge(local.common_tags, {
Name = "${local.name_prefix}-lifecycle-example"
})
}
# VALIDATION AND TESTING
# Input validation
variable "validated_email" {
description = "Email address with validation"
type = string
validation {
condition = can(regex("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$", var.validated_email))
error_message = "Please provide a valid email address."
}
}
# Precondition and postcondition checks
resource "aws_instance" "validated" {
ami = data.aws_ami.ubuntu.id
instance_type = var.instance_type
lifecycle {
# Precondition
precondition {
condition = data.aws_ami.ubuntu.architecture == "x86_64"
error_message = "The selected AMI must be for the x86_64 architecture."
}
# Postcondition
postcondition {
condition = self.public_dns != ""
error_message = "Instance must have a public DNS name."
}
}
tags = {
Name = "validated-instance"
}
}
# ERROR HANDLING
# Try function for safe operations
locals {
# Safe navigation
instance_type_safe = try(var.custom_config.instance_type, var.instance_type)
# Error handling with can()
is_valid_cidr = can(cidrhost(var.vpc_cidr, 0))
# Conditional with error handling
subnet_count = try(length(var.subnet_cidrs), 3)
}
# Resource with error handling
resource "aws_instance" "error_handling" {
count = var.create_instances ? try(length(var.instance_configs), 0) : 0
ami = try(var.instance_configs[count.index].ami, data.aws_ami.ubuntu.id)
instance_type = try(var.instance_configs[count.index].instance_type, var.instance_type)
tags = merge(local.common_tags, {
Name = "error-handling-${count.index + 1}"
})
}