Write a `terraform test` file that asserts the bucket name follows a convention.
AdvancedHands-onWrite-Terraform tasks
Answer
# tests/bucket.tftest.hcl
variables {
env = "dev"
}
run "bucket_name_convention" {
command = plan
assert {
condition = startswith(aws_s3_bucket.artifacts.bucket, "devopsshack-")
error_message = "Bucket name must start with devopsshack-"
}
assert {
condition = aws_s3_bucket_versioning.artifacts.versioning_configuration[0].status == "Enabled"
error_message = "Versioning must be enabled"
}
}
Run with terraform test.
Key trick → The native test framework (Terraform 1.6+) runs plan-only tests with no real resources created, which is fast enough for every PR. command = apply gives full integration tests against a sandbox account.
More on Write-Terraform tasks
Write Terraform for an S3 bucket with versioning, encryption and public access blocked.BeginnerWrite the remote backend configuration with S3 and state locking.BeginnerWrite a VPC with public and private subnets across 3 AZs using `count` or `for_each`.IntermediateWrite a reusable module for an EC2 instance with inputs, outputs and validation.AdvancedWrite a security group that allows HTTPS from anywhere and SSH only from an office CIDR.BeginnerCreate multiple IAM users from a list with `for_each`, and output their ARNs as a map.Beginner