Terraform’s AWS provider implements destroying an individual
aws_instance instance by calling
ec2:TerminateInstances and then polling periodically until the instance status shows as “terminated” as far as the EC2 API is concerned.
Terraform has no direct control over how EC2 implements that shutdown, how the software inside the EC2 instance responds to being asked to shut down, or how long EC2 will wait for the shutdown to complete.
The EC2 guide Troubleshooting Terminating (Shutting Down) Your Instance suggests that EC2 will give the instance an opportunity to run shutdown scripts before the instance is finally forcefully terminated.
Elsewhere in the EC2 docs, there is another section What Happens When You Terminate an Instance, which explains that
TerminateInstances causes the EC2 system to send an ACPI Shutdown event (similar to what happens when you press a power button on a physical computer) which software in the instance must listen for and respond to. In your case it sounds like you are using systemd, in which case it’s systemd that would respond to that event, as you described. Although it’s impossible to say for certain what’s going on with your system from here, my first theory would be that the systemd configuration isn’t quite right and so systemd is not running the script as you intended.
While not directly related to your question, I want to note that I’d recommend using
aws_autoscaling_group to launch EC2 instances from Terraform rather than
aws_instance directly. In that case, Terraform simply configures EC2 autoscaling and then autoscaling in turn manages your instances. This is helpful in many situations because EC2 autoscaling can then constantly monitor your instances and replace them if any fail, whereas Terraform can only react to changing infrastructure when you explicitly run it.