interpolationterraformamazon-cloudwatch

Create cloudwatch scheduled expression based on a variable - expected expression but found "*"


I'm trying to create AWS Clouwatch event rule via terraform

variable "schedule_expression" {
  default = "cron(5 * * * ? *)"
  description = "the aws cloudwatch event rule scheule expression that specifies when the scheduler runs. Default is 5 minuts past the hour. for debugging use 'rate(5 minutes)'. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html"
}

I want to specify variable instead of 5

variable "AutoStopSchedule" {
   default = "5"
}

variable "schedule_expression" {
  default = "cron(${var.AutoStopSchedule} * * * ? *)"
  description = "the aws cloudwatch event rule scheule expression that specifies when the scheduler runs. Default is 5 minuts past the hour. for debugging use 'rate(5 minutes)'. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html"
}

but getting:

Error: variable "schedule_expression": default may not contain interpolations

main.tf

# Cloudwatch event rule
resource "aws_cloudwatch_event_rule" "check-scheduler-event" {
    name = "check-scheduler-event"
    description = "check-scheduler-event"
    schedule_expression = "${var.schedule_expression}"
    depends_on = ["aws_lambda_function.demo_lambda"]
}

i want to create schedule_expression based on AutoStopSchedule variable, how to do it ?

Tried following:

resource "aws_cloudwatch_event_rule" "check-scheduler-event" {
    name = "check-scheduler-event"
    description = "check-scheduler-event"

    #schedule_expression = "cron(15 * * * ? *)"
    schedule_expression = "${var.AutoStopSchedule == "5" ? cron(5 * * * ? *) : cron(15 * * * ? *)}"
    depends_on = ["aws_lambda_function.demo_lambda"]
}

getting expected expression but found "*"


Solution

  • You don't need to do that. What you need to do is use a local instead, like:

    variable "AutoStopSchedule" {
       default = "5"
    }
    
    
    locals{
    schedule_expression= "cron(${var.AutoStopSchedule} * * * ? *)"  
    }
    
    output "schedule_expression" {
      value = "${local.schedule_expression}"
    }
    

    If you terraform apply that you get:

    Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
    
    Outputs:
    
    schedule_expression = cron(5 * * * ? *)
    

    To use it ${local.sschedule_expression} where you had ${var.schedule_expression} before.