terraform 中的任务执行 IAM 角色
Posted
技术标签:
【中文标题】terraform 中的任务执行 IAM 角色【英文标题】:Task execution IAM role in terraform 【发布时间】:2020-12-05 19:29:10 【问题描述】:我正在为任务执行创建一个 IAM 角色。我已经在 cloudformation 中完成了,现在我在 terraform 中进行,但我遇到的问题是在 cloudformation 中有一个属性可以提供ManagedPolicyArns
,但是你将如何在 terraform 中提供它。我附上了两个脚本。 Terraform 脚本不完整,我需要帮助,而 cloudformation 脚本已完成,我想将其复制到 terraform。
地形:
resource "aws_iam_role" "task_execution"
name = "task-execution-$terraform.workspace"
assume_role_policy = <<EOF
"Version": "2012-10-17",
"Statement": [
"Action": "sts:AssumeRole",
"Principal":
"Service": "ecs-tasks.amazonaws.com"
,
"Effect": "Allow",
"Sid": "",
"path": "/",
]
EOF
tags =
tag-key = "tag-value"
云形成
---
AWSTemplateFormatVersion: 2010-09-09
Parameters:
Env:
Type: String
Resources:
ExRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- ecs-tasks.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
RoleName: !Sub "excutionrole-$Env"
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
Policies:
- PolicyName: AccessECR
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ecr:BatchGetImage
- ecr:GetAuthorizationToken
- ecr:GetDownloadUrlForLayer
Resource: '*'
【问题讨论】:
这能回答你的问题吗? Terraform: correct way to attach AWS managed policies to a role? 【参考方案1】:在 Terraform 中,您可以使用 iam_role_policy_attachment 资源将策略附加到角色:
resource "aws_iam_role_policy_attachment" "test-attach"
role = aws_iam_role.test_role.name
policy_arn = // ARN of the managed policy
【讨论】:
【参考方案2】:assume_role_policy
仅用于
信任关系(即谁/什么可以担任该角色)。因此,
你的aws_iam_role
应该是:
resource "aws_iam_role" "test_role"
name = "s3_access"
assume_role_policy = <<EOF
"Version": "2012-10-17",
"Statement": [
"Sid": "1",
"Effect": "Allow",
"Principal":
"Service": "ecs-tasks.amazonaws.com"
,
"Action": "sts:AssumeRole"
]
EOF
tags =
tag-key = "tag-value"
然后,可以将所需的权限附加到角色,如下所示:
resource "aws_iam_role_policy_attachment" "ecs-task-permissions"
role = aws_iam_role.test_role.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
resource "aws_iam_role_policy" "ecr-access"
name = "ecs-access"
role = aws_iam_role.test_role.name
policy = <<EOF
"Version": "2012-10-17",
"Statement": [
"Sid": "2",
"Effect": "Allow",
"Action": [
"ecr:BatchGetImage",
"ecr:GetAuthorizationToken",
"ecr:GetDownloadUrlForLayer"
],
"Resource": "*"
]
EOF
【讨论】:
它给出了一个错误Error: "assume_role_policy" contains an invalid JSON: invalid character '' looking for beginning of object key string
@aws-noob 它说的是哪一行?
``` 在模块/Iam_role/main.tf 第 1 行,在资源“aws_iam_role”“task_execution”中:1:资源“aws_iam_role”“task_execution”```
您能否用您的更改更新问题。似乎其他东西也必须改变,可能是错误的。
@aws-noob 没有戏剧性。如果您有任何问题,请随时提问:-) 我或其他人会尽力提供帮助。以上是关于terraform 中的任务执行 IAM 角色的主要内容,如果未能解决你的问题,请参考以下文章
Terraform aws_iam_role_policy 中的 JSON 语法错误
使用 Terraform 创建 GCP 自定义 IAM 角色
使用 terraform 创建 IAM 角色并将其附加到 EC2