Enabling termination/removal protection for EC2 instances
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "example" {
ami = "ami-0c94855ba95c574c8"
instance_type = "t2.micro"
}
In the above Terraform code, an AWS instance is being created without the
disable_api_termination
attribute. This attribute is used to enable termination protection for an instance. When this attribute is not specified or set to false, the instance can be easily terminated or deleted.
The
aws_instance
resource block creates an EC2 instance with the specified AMI and instance type. However, it does not include the
disable_api_termination
attribute that is necessary for protection against deletion. This leaves the instance vulnerable to accidental termination or deletion.
The lack of deletion protection can lead to accidental data loss or service disruption. It's particularly risky in production environments where the accidental deletion of an instance can lead to significant problems.
To fix this vulnerability, you should set the
disable_api_termination
attribute to
true
in your
aws_instance
resource block. This will enable termination protection for the instance and protect it from being accidentally terminated or deleted.
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "example" {
ami = "ami-0c94855ba95c574c8"
instance_type = "t2.micro"
disable_api_termination = true
}
The above code is a fixed version of the original vulnerable code. The vulnerability was that the EC2 instance did not have termination protection enabled. This could potentially lead to accidental termination of the instance, which could cause loss of data and service disruption.
To fix this vulnerability, the
disable_api_termination
attribute was added to the
aws_instance
resource. This attribute is used to enable termination protection for the EC2 instance. When this attribute is set to
true
, it prevents the instance from being accidentally terminated through the AWS Management Console, CLI, and SDKs.
This is a critical security measure to ensure the integrity and availability of the EC2 instance. It is especially important for instances that host critical applications or store sensitive data.
Please note that even with termination protection enabled, the instance can still be terminated if the
disable_api_termination
attribute is manually set to
false
or if the instance is deleted from the AWS Management Console. Therefore, it is also important to implement proper access controls and regularly review IAM policies to prevent unauthorized changes.