You can use the count meta-parameter to achieve the effects of an if-else statement. It is talked about in detail in the link below and I also pulled one relevant example out.
I'm not 100% sure if you can give both the data source and resource the same name without a conflict; but I assume it would work. It may be dependent on the resource you're creating though, not sure.
https://blog.gruntwork.io/terraform-tips-tricks-loops-if-statements-and-gotchas-f739bbae55f9
Excerpt:
# This is just pseudo code. It won't actually work in Terraform.
if var.give_neo_cloudwatch_full_access {
resource "aws_iam_user_policy_attachment" "neo_cloudwatch_full" {
user = aws_iam_user.example[0].name
policy_arn = aws_iam_policy.cloudwatch_full_access.arn
}
} else {
resource "aws_iam_user_policy_attachment" "neo_cloudwatch_read" {
user = aws_iam_user.example[0].name
policy_arn = aws_iam_policy.cloudwatch_read_only.arn
}
}
To do this in Terraform, you can use the count parameter and a conditional expression on each of the resources:
resource "aws_iam_user_policy_attachment" "neo_cloudwatch_full" {
count = var.give_neo_cloudwatch_full_access ? 1 : 0
user = aws_iam_user.example[0].name
policy_arn = aws_iam_policy.cloudwatch_full_access.arn
}
resource "aws_iam_user_policy_attachment" "neo_cloudwatch_read" {
count = var.give_neo_cloudwatch_full_access ? 0 : 1
user = aws_iam_user.example[0].name
policy_arn = aws_iam_policy.cloudwatch_read_only.arn
}