Inline attribute changes won’t work in terraform for remote-exec

Terraform Trigger for Inline Command Changes

Terraform Trigger for Inline Command Changes

The user_data_replace_on_change attribute in Terraform is typically used in the context of AWS EC2 instances to trigger instance replacement when there is a change in the user_data attribute. This ensures that changes to the user_data script result in a new EC2 instance being created with the updated configuration.

However, user_data_replace_on_change is not directly applicable to the inline attribute of a remote-exec or local-exec provisioner. Changes to the inline block do not trigger instance replacement by default.

Key Points

  • user_data_replace_on_change is specific to the user_data attribute in resources like aws_instance or aws_launch_template.
  • Provisioners like remote-exec or local-exec do not have a direct equivalent to user_data_replace_on_change.
  • If you want to force the replacement of a resource based on changes to a provisioner’s inline attribute, you must use the triggers argument or manage the resource lifecycle manually.

Example of Forcing Replacement with Triggers

resource "aws_instance" "example" { ami = "ami-12345678" instance_type = "t2.micro" provisioner "remote-exec" { connection { type = "ssh" user = "ec2-user" private_key = file("~/.ssh/id_rsa") host = self.public_ip } inline = [ "sudo apt-get update", "sudo apt-get install -y nginx" ] } # Use the 'triggers' argument to force replacement when the 'inline' commands change lifecycle { create_before_destroy = true } triggers = { inline_commands = sha256(join("", provisioner["remote-exec"][0].inline)) } }

Summary

  • Triggers Argument: The triggers argument in the resource lifecycle configuration can be used to specify arbitrary values (like a hash of the inline commands) that, when changed, will force the resource to be replaced.
  • create_before_destroy: This lifecycle setting ensures a new resource is created before the old one is destroyed, minimizing downtime.

user_data_replace_on_change does not apply to inline in provisioners. To achieve similar behavior, the triggers argument or other lifecycle controls should be used to manage resource replacement based on changes to provisioner commands.