Conditionally creating a resource if variable is not empty

Hi all,

I’m trying to conditionally create a resource based on a variable. If the variable is empty, then the resource should be skipped.

Following the documentation I’ve created:

count = var.pg_slave01_db_ebs_snapshot_id != "" ? 1 : 0 && (terraform.workspace == "prod") ? 1 : 0

If the variable pg_slave01_db_ebs_snapshot_id is not empty and the Terraform Workspace is prod, it should create the resource.

But I get the following error when running terraform plan:

Error: Invalid operand
│ 
│   on modules/database/ec2-database-slave01.tf line 45, in resource "aws_iam_role" "pgsql_slave01_database_role":
│   45:   count              = var.pg_slave01_db_ebs_snapshot_id != "" ? 1 : 0 && (terraform.workspace == "prod") ? 1 : 0
│ 
│ Unsuitable value for left operand: bool required.

Am am I missing, please?
Cheers!

Edit:

The pg_slave01_db_ebs_snapshot_id variable is type string.

Couldn’t find a solution, so had to do this instead:

var.pg_slave01_create && (terraform.workspace == "prod") ? 1 : 0

Variable pg_slave01_create is type bool.

However, this is a workaround for me. It’s not the final solution. If I could get the variable to be string that would be much better.

@lpossamai you can’t combine two conditional expressions like that, you need to combine the two tests into a single conditional expression like this:

count = var.pg_slave01_db_ebs_snapshot_id != "" && terraform.workspace == "prod" ? 1 : 0
2 Likes

Thanks. That worked!