2017-08-22 5 views
1
variable "iam_action" { 
    type = "list" 
    default = ["ec2.amazonaws.com","ecs.amazonaws.com"] 
} 

resource "aws_iam_role" "s3_role" { 
    name    = "abcd" 
    assume_role_policy = <<EOF 
{ 
    "Version": "2012-10-17", 
    "Statement": [ 
    { 
     "Action": "sts:AssumeRole", 
     "Principal": { 
     "Service": [ "${var.iam_action}" 
     ] 
     }, 
     "Effect": "Allow, 
     "Sid": "" 
    } 
    ] 
} 
EOF 
} 

エラー資源に取得テラフォーム:機能に参加し、私は機能に参加してみましたが、私はリスト["a","b","c"]する出力を必要とするリスト変数が

At column 1, line 1: output of an HIL expression must be a string, or a single list (argument 2 is TypeList) in: 

は私がすることによってjsonencodeで固定し["a,b,c"]

答えて

2

のような出力を提供しますtemplate_file

最初に作成するjsonファイル

$ cat s3_policy.json 

{ 
    "Version": "2012-10-17", 
    "Statement": [ 
    { 
     "Action": "sts:AssumeRole", 
     "Principal": { 
     "Service": ${iam_action} 
     }, 
     "Effect": "Allow", 
     "Sid": "" 
    } 
    ] 
} 

更新TFファイル

variable "iam_action" { 
    type = "list" 
    default = ["ec2.amazonaws.com", "ecs.amazonaws.com"] 
} 

data "template_file" "s3_role" { 
    template = "${file("${path.module}/s3_policy.json")}" 

    vars { 
    iam_action = "${jsonencode(var.iam_action)}" 
    } 
} 

resource "aws_iam_role" "s3_role" { 
    name = "abcd" 

    assume_role_policy = "${data.template_file.s3_role.rendered}" 
} 

は、実行template plan

+ aws_iam_role.s3_role 
     arn:     "<computed>" 
     assume_role_policy: "{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n  \"Action\": \"sts:AssumeRole\",\n  \"Principal\": {\n  \"Service\": [\"ec2.amazonaws.com\",\"ecs.amazonaws.com\"]\n  },\n  \"Effect\": \"Allow\",\n  \"Sid\": \"\"\n }\n ]\n}\n" 
     create_date:   "<computed>" 
     force_detach_policies: "false" 
     name:     "abcd" 
     path:     "/" 
     unique_id:    "<computed>" 

は参照してください。

terraform interpolation

jsonencode(item) - Returns a JSON-encoded representation of the given item, which may be a string, list of strings, or map from string to string. Note that if the item is a string, the return value includes the double quotes.

R私が直接template_file"${var.iam_action}"でVARSを使用することはできませんイーソンがここで説明されています

vars - (Optional) Variables for interpolation within the template. Note that variables must all be primitives. Direct references to lists or maps will cause a validation error.

+0

'' 'assume_role_policy: ""=> "{\ nは\" バージョン\ ":" 2012年10月17日\」\ \ n \ "サービス\":\ "\" \ "\" \ "\" \ \ n "\ n" \ n "\ n" \ n "create_date : "" => "" "エラー:* aws_iam_role.s3_role:IAMロールの作成中にエラーが発生しましたs3_sysops_role:MalformedPolicyDocument:ポリシーの無効なプリンシパル:" SERVICE ":" $ {var.iam_action} " – user60679

+0

$ {foo }私はfoo = ["a"、 "b"、 "c"]をレンダリングしません。 – user60679

+0

@ user60679答えを修正して更新しました。 – BMW