How to create a dynamic definition for AWS state machine on Terraform?

I'm trying to create a definition for AWS state machine generating it from this list of object:

state_object_list = [ { name = "task1", type = "Task", resource = "arn:aws:lambda:us-east-1:123456789:function:test", end = false }, { name = "task2", type = "Task", resource = "arn:aws:lambda:us-east-1:1234567890:function:test2", end = true } ] 

I would like to have something similar to this, so with the possibility to define dinamically the key and the values of each state.

resource "aws_sfn_state_machine" "this" { name = "my-state" role_arn = "my-role" definition = jsonencode({ Comment = var.definition_comment StartAt = var.definition_startat States = { for state in var.state_object_list: { state.name = { Type = state.type Resource = state.resource End = state.end } } } }) } 

Is it possible? Thank you for the help.

4

2 Answers

Can you explain why you want this? The state machine definition follows JSON format so putting your JSON object into the definition=jsonencode({...}) with minor adjustments to follow the Amazon States Language syntax should work and doesn't create more complexity in the code. Maybe I missed your point.

Easiest way to accomplish this issue to create a local variable then use it in your resource.

variables.tf


variable "state_object_list" { default = [ { name = "task1", type = "Task", resource = "arn:aws:lambda:us-east-1:123456789:function:test", end = false }, { name = "task2", type = "Task", resource = "arn:aws:lambda:us-east-1:1234567890:function:test2", end = true } ] } variable "definition_comment" { type = string default = "definition comment" } variable "definition_startat" { type = string default = "definition state" } 

main.tf


locals { states = { for state in var.state_object_list: state.name => { Type = state.type Resource = state.resource End = state.end } } } resource "aws_sfn_state_machine" "this" { name = "my-state" role_arn = "arn:aws:iam::123456789098:role/my-role" definition = jsonencode({ Comment = var.definition_comment StartAt = var.definition_startat States = local.states }) } 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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.

You Might Also Like