1
votes

I need to pass IAM role ARN to module so i can create lambda function and cloudwath event using terraform

main.tf:

resource "aws_iam_role" "this" {
    count = "${var.create_iam_role_automatically ? 1 : 0}"
    name = "${var.aws_iam_role_name}"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF

}

output.tf:

output "lambda_iam_role" {
  value = "${aws_iam_role.this.*.arn}"
}

module file:

module "lambda2" {

  source = "D:/Users/1"

  ### Parameters ###
  schedule_expression = "5"
  function_name = "jjjj"
  enabled = "false"
  cloudwatch_event_rule_name = "jjjj"
  create_iam_role_automatically=false
  lambda_iam_role = "${module.lambda.lambda_iam_role}"
  #lambda_iam_role = "${var.lambda.iam}"

}

and getting:

module.lambda2.var.lambda_iam_role: variable lambda_iam_role in module lambda2 should be type string, got list

How to get string value ?

2

2 Answers

3
votes

solved it in following way:

output "lambda_iam_role" {
value = "${join(",",aws_iam_role.this.*.arn)}"

 }
0
votes

This is because you're using a splat (*) in your output:

output "lambda_iam_role" {
  value = "${aws_iam_role.this.*.arn}"
}

Despite the fact you have a count of 0 or 1 being used, this will always be a list. You can work around it by taking the first element of that list, but also taking into account for when there's nothing in the list (ie when the count is 0):

output "lambda_iam_role" {
    value = "${length(aws_iam_role.this.*.arn) > 0 ? element(concat(aws_iam_role.this.*.arn, list("")), 0) : ""}"
}

It looks quite complex, because we also need to work around an issue with Terraform where it will evaluate both return values from a conditional expression (this will be fixed in 0.12).

If the length of the list is greater than 0, take the first element of the list, otherwise take an empty value. Since both return values of a conditional expression are evaluated, we need to concat the actual list with an extra list with a blank value, to make sure that the element command doesn't throw an error in the case where there's a count of 0, even though it's returning the second value.