2

Basically, what I'd like to do is create a module that does this pseudocode:

if <boolean> then
  resource "<resource type>" "name" {
    # ... set variables ...
  } else {
  data "<data source>" "name" {
    # grab data
  }

output "resource_type.name" {
  if <boolean> then
    value = resource_type.name
  else
    value = data_source.name
}

I hope I'm being clear. Happy to add more info to clarify what I'm hoping is possible.

1
  • 1
    It's not exactly what you were asking, but there's some official documentation with some advice on how to handle this sort of thing in modules: terraform.io/docs/modules/… Apr 1, 2020 at 16:48

1 Answer 1

2

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
}
2
  • Thank you for this answer, but it's not quite what I'm looking for, because I want to use a boolean to decide if we're creating a resource or sourcing a data source. It may be the best answer, though - we'll see! :D Apr 1, 2020 at 16:54
  • It really seems what I was seeking is just not possible via the current version of HCL. But, I "accepted" this answer because this is likely the closest we'll get to what I wanted. Thanks! Jul 27, 2020 at 3:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.