Skip to main content

Applying Infrastructure Changes

1. Applying Configuration

Command Description Flags
terraform apply Applies the configuration to create or update infrastructure -auto-approve, -backup, -lock
terraform apply -auto-approve Automatically approves the plan without user interaction -auto-approve
terraform apply -backup Specifies the path to save the backup state file -backup=<path>

Example: Applying Configuration

terraform apply -auto-approve
Note: Always review the plan before applying to ensure changes align with expectations.

2. Auto-Approving Changes

Option Values Description
auto_approve false Whether to automatically approve changes when running terraform apply
auto_approve true Automatically approves changes without user interaction

Example: Enabling Auto-Approve in CI/CD

terraform apply -auto-approve
Note: Use with caution in production environments as it bypasses manual review.

3. Applying Saved Plans

Command Description Notes
terraform apply <plan-file> Applies the changes described in a saved plan file Plan file is typically named plan.out
terraform apply -auto-approve <plan-file> Applies the plan without interactive approval Useful in CI/CD pipelines or automation scripts

Example: Applying a Saved Plan

terraform apply my-infrastructure.plan
Note: The plan file must be generated with terraform plan -out=my-infrastructure.plan before applying.
Warning: Applying a saved plan can be destructive. Ensure the plan matches your intended changes before applying.

4. Targeting Specific Resources

Resource Target Syntax Description
module module.name Targets a specific module instance
resource resource.type.name Targets a specific resource instance
data data.type.name Targets a specific data source instance

Example: Targeting a Specific Resource

terraform apply -target=aws_instance.web_server

Example: Targeting a Module

terraform apply -target=module.database
Note: Using -target limits the scope of the operation but does not remove resources from state that are not targeted.

5. Replacing Resources

When Terraform determines that a resource must be replaced rather than updated in-place, it will destroy the existing resource and create a new one with the updated configuration. This is typically triggered by changes to arguments that cannot be updated in-place, such as changing the type of a resource or modifying a parameter that requires recreation.

Argument Description Notes
lifecycle Controls lifecycle behaviors for resources Used to define replacement behavior via create_before_destroy and prevent_destroy
create_before_destroy Ensures new resource is created before destroying old one Defaults to false. Set to true for safer replacements
prevent_destroy Prevents resource destruction Defaults to false. Set to true to protect critical resources

Example: Replacing a Resource Safely

resource "aws_instance" "web" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"

  lifecycle {
    create_before_destroy = true
  }
}
Note: When create_before_destroy = true, Terraform will create the new resource before destroying the old one, minimizing downtime in some cases.
Warning: Replacing resources can lead to data loss if not handled carefully. Ensure backups or migration steps are in place.

6. Using Parallelism

Terraform allows you to control how many resources are created or updated in parallel during an apply operation. This can help optimize performance and manage resource usage.

Option Values Description
-parallelism=N N Limit the number of concurrent operations. Set to a positive integer.

Example: Limiting Parallelism

terraform apply -parallelism=5
Note: Setting -parallelism to a low value may increase the total time required to apply changes, especially when dealing with many resources. Conversely, setting it too high can lead to resource contention or API throttling.

7. Applying with Variable Files

Variable File Description Usage
terraform.tfvars Default variable file for Terraform terraform apply
*.auto.tfvars Auto-loaded variable files (no need to specify) terraform apply
-var-file=<filename> Explicitly specify a variable file terraform apply -var-file=prod.tfvars

Example: Using Variable Files

resource "aws_instance" "web" {
  ami           = var.ami_id
  instance_type = var.instance_type
}

Example: Variable File Content

ami_id        = "ami-12345678"
instance_type = "t3.micro"
Note: Variable files are loaded in order of precedence, with terraform.tfvars having the lowest priority.

8. Handling Apply Errors

Error Type Description Resolution Steps
Resource Dependency Error Occurs when a resource depends on another that hasn't been created or updated yet.
  1. Review the dependency chain in your configuration
  2. Use depends_on to explicitly define dependencies
  3. Rerun terraform apply
Permission Denied Applied when Terraform lacks necessary permissions to modify resources.
  1. Verify IAM roles or access keys
  2. Ensure correct credentials are set in environment variables
  3. Re-run apply with proper permissions
Provider Configuration Error Occurs due to misconfigured or missing provider settings.
  1. Check provider blocks for correct configuration
  2. Validate required parameters like region, token
  3. Re-run apply after fixing config
State Locking Failure When Terraform cannot acquire a lock on the state file (e.g., concurrent operations).
  1. Check for other Terraform processes running
  2. Delete stale lock files if safe to do so
  3. Retry apply once state is unlocked

Example: Resource Dependency Error

resource "aws_instance" "web" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}

resource "aws_security_group" "web_sg" {
  name        = "web-sg"
  description = "Allow HTTP traffic"

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  # This will cause a dependency error if web instance is not created first
  depends_on = [aws_instance.web]
}
Note: Always review Terraform's error logs for specific details about what went wrong during the apply phase.

9. Using Compact Warnings

Option Values Notes
compact-warnings false Default behavior showing full warning messages
compact-warnings true Enables compact warning format

Example: Enabling Compact Warnings

terraform apply -compact-warnings
Note: The compact warning format reduces verbosity by truncating some warning details, useful for reducing log noise in automated environments.

10. Limiting Input Prompts

Example: Using -auto-approve flag

terraform apply -auto-approve
Flag Description Usage
-auto-approve Skips interactive approval prompts for changes Use in CI/CD or automated environments
Note: Using -auto-approve bypasses the confirmation step and should be used carefully in production environments.

Was this article helpful?