执行Terraform适用于AWS假定角色

问题描述 投票:3回答:3

我需要执行Terraform模板来为AWS账户配置基础架构,我可以通过承担角色来访问该账户。

我现在遇到的问题是我在该AWS账户中没有IAM用户,因此我没有aws_access_key_idaws_secret_access_key在我的~/.aws/credentials中设置另一个命名的配置文件。当我运行命令terraform apply时,模板为我的帐户而不是其他帐户创建基础结构。

如何使用您的帐户运行Terraform模板,该帐户具有访问其他AWS账户服务的角色?

这是我的Terraform文件:

# Input variables
variable "aws_region" {
    type = "string"
    default = "us-east-1"
}

variable "pipeline_name" {
    type = "string"
    default = "static-website-terraform"
}

variable "github_username" {
    type = "string"
    default = "COMPANY"
}

variable "github_token" {
    type = "string"
}

variable "github_repo" {
    type = "string"
}

provider "aws" {
    region = "${var.aws_region}"
    assume_role {
        role_arn = "arn:aws:iam::<AWS-ACCOUNT-ID>:role/admin"
        profile = "default"
    }
}

# CodePipeline resources
resource "aws_s3_bucket" "build_artifact_bucket" {
    bucket = "${var.pipeline_name}-artifact-bucket"
    acl = "private"
}

data "aws_iam_policy_document" "codepipeline_assume_policy" {
    statement {
        effect = "Allow"
        actions = ["sts:AssumeRole"]

        principals {
            type = "Service"
            identifiers = ["codepipeline.amazonaws.com"]
        }
    }
}

resource "aws_iam_role" "codepipeline_role" {
    name = "${var.pipeline_name}-codepipeline-role"
    assume_role_policy = "${data.aws_iam_policy_document.codepipeline_assume_policy.json}"
}

# CodePipeline policy needed to use CodeCommit and CodeBuild
resource "aws_iam_role_policy" "attach_codepipeline_policy" {
    name = "${var.pipeline_name}-codepipeline-policy"
    role = "${aws_iam_role.codepipeline_role.id}"

    policy = <<EOF
{
    "Statement": [
        {
            "Action": [
                "s3:GetObject",
                "s3:GetObjectVersion",
                "s3:GetBucketVersioning",
                "s3:PutObject"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "cloudwatch:*",
                "sns:*",
                "sqs:*",
                "iam:PassRole"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "codebuild:BatchGetBuilds",
                "codebuild:StartBuild"
            ],
            "Resource": "*",
            "Effect": "Allow"
        }
    ],
    "Version": "2012-10-17"
}
EOF
}

# CodeBuild IAM Permissions
resource "aws_iam_role" "codebuild_assume_role" {
    name = "${var.pipeline_name}-codebuild-role"

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

resource "aws_iam_role_policy" "codebuild_policy" {
    name = "${var.pipeline_name}-codebuild-policy"
    role = "${aws_iam_role.codebuild_assume_role.id}"

    policy = <<POLICY
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:GetObjectVersion",
                "s3:GetBucketVersioning"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Effect": "Allow",
            "Resource": [
                "${aws_codebuild_project.build_project.id}"
            ],
            "Action": [
                "codebuild:*"
            ]
        },
        {
            "Effect": "Allow",
            "Resource": [
                "*"
            ],
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ]
        }
    ]
}
POLICY
}

# CodeBuild Section for the Package stage
resource "aws_codebuild_project" "build_project" {
    name = "${var.pipeline_name}-build"
    description = "The CodeBuild project for ${var.pipeline_name}"
    service_role = "${aws_iam_role.codebuild_assume_role.arn}"
    build_timeout = "60"

    artifacts {
        type = "CODEPIPELINE"
    }

    environment {
        compute_type = "BUILD_GENERAL1_SMALL"
        image = "aws/codebuild/nodejs:6.3.1"
        type = "LINUX_CONTAINER"
    }

    source {
        type = "CODEPIPELINE"
        buildspec = "buildspec.yml"
    }
}

# Full CodePipeline
resource "aws_codepipeline" "codepipeline" {
    name = "${var.pipeline_name}-codepipeline"
    role_arn = "${aws_iam_role.codepipeline_role.arn}"

    artifact_store = {
        location = "${aws_s3_bucket.build_artifact_bucket.bucket}"
        type     = "S3"
    }

    stage {
        name = "Source"

        action {
            name = "Source"
            category = "Source"
            owner = "ThirdParty"
            provider = "GitHub"
            version = "1"
            output_artifacts = ["SourceArtifact"]

            configuration {
                Owner = "${var.github_username}"
                OAuthToken = "${var.github_token}"
                Repo = "${var.github_repo}"
                Branch = "master"
                PollForSourceChanges = "true"
            }
        }
    }

    stage {
        name = "Deploy"

        action {
            name = "DeployToS3"
            category = "Test"
            owner = "AWS"
            provider = "CodeBuild"
            input_artifacts = ["SourceArtifact"]
            output_artifacts = ["OutputArtifact"]
            version = "1"

            configuration {
                ProjectName = "${aws_codebuild_project.build_project.name}"
            }
        }
    }
}

更新:

在下面达伦的回答(这很有道理)之后,我补充道:

provider "aws" {
  region                  = "us-east-1"
  shared_credentials_file = "${pathexpand("~/.aws/credentials")}"
  profile                 = "default"

  assume_role {
    role_arn = "arn:aws:iam::<OTHER-ACCOUNT>:role/<ROLE-NAME>"
  }
}

但是,我遇到了这个错误:

  • provider.aws:不能假定角色“arn:aws:iam ::: role /”。 造成这种情况的原因有很多 - 最常见的是: 用于承担该角色的凭据无效 凭据没有适当的权限来承担该角色 角色ARN无效

我已经检查了其他帐户中的角色,我可以使用我的帐户中的AWS控制台切换到该角色。我还检查了AWS指南here

所以:该角色ARN是有效的,我确实有凭据来承担角色以及运行堆栈所需的所有权限。

更新

我还尝试了一个可以访问服务的新角色。但是,我遇到了这个错误:

错误:刷新状态错误:发生了2个错误:

    * aws_codebuild_project.build_project: 1 error(s) occurred:

    * aws_codebuild_project.build_project: aws_codebuild_project.build_project: Error retreiving Projects:

“InvalidInputException:无效的项目ARN:帐户ID与调用方的帐户\匹配\ on \ status代码:400,请求ID:...”* aws_s3_bucket.build_artifact_bucket:发生1个错误:

    * aws_s3_bucket.build_artifact_bucket: aws_s3_bucket.build_artifact_bucket: error getting S3 Bucket CORS

配置:AccessDenied:拒绝访问状态代码:403,请求ID:...,主机ID:...

=====

更新2019年4月29日:

根据@ Rolando的建议,我已将此政策添加到主要帐户的用户,我正在尝试使用其他帐户的角色,我计划执行terraform apply

{
    "Version": "2012-10-17",
    "Statement": {
        "Effect": "Allow",
        "Action": "sts:AssumeRole",
        "Resource": "arn:aws:iam::<OTHER-ACCOUNT-ID>:role/admin"
    }
}

这是Trust Relationship角色属于其他账户的admin

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::<MAIN_ACCOUNT_ID>:root"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "Bool": {
          "aws:MultiFactorAuthPresent": "true"
        }
      }
    }
  ]
}

但是,当我运行此命令时:

aws sts assume-role --role-arn arn:aws:iam::<OTHER-ACCOUNT-ID>:role/admin --role-session-name "RoleSession1" --profile default > assume-role-output.txt

我有这个错误:

An error occurred (AccessDenied) when calling the AssumeRole operation: Access denied
amazon-web-services terraform aws-codepipeline terraform-provider-aws
3个回答
1
投票

您应该能够这样做:在Terraform中配置aws提供程序以使用本地shared_credentials_file

provider "aws" {
  region                  = "us-east-1"
  shared_credentials_file = "${pathexpand("~/.aws/credentials")}"
  profile                 = "default"

  assume_role {
    role_arn = "arn:aws:iam::1234567890:role/OrganizationAccountAccessRole"
  }
}

“profile”是具有AWS Access密钥的〜/ .aws / credentials中的命名配置文件。例如。

[default]
region = us-east-1
aws_access_key_id = AKIAJXXXXXXXXXXXX
aws_secret_access_key = Aadxxxxxxxxxxxxxxxxxxxxxxxxxxxx    

这不是您要访问的帐户中的IAM用户。它位于“源”帐户中(您在某些时候需要密钥才能访问AWS cli)。

“assume_role.role_arn”是您要假设的帐户中的角色。需要允许“profile”中的IAM用户承担该角色。


1
投票

每当您想要将命令作为特定角色(包括其他帐户)运行时,我都有一个防弹解决方案。我假设您已安装AWS CLI工具。您还必须安装jq(简单的工具来解析和从json中提取数据),尽管您可以按照您希望的任何方式解析数据。

aws_credentials=$(aws sts assume-role --role-arn arn:aws:iam::1234567890:role/nameOfMyrole --role-session-name "RoleSession1")

export AWS_ACCESS_KEY_ID=$(echo $aws_credentials|jq '.Credentials.AccessKeyId'|tr -d '"')
export AWS_SECRET_ACCESS_KEY=$(echo $aws_credentials|jq '.Credentials.SecretAccessKey'|tr -d '"')
export AWS_SESSION_TOKEN=$(echo $aws_credentials|jq '.Credentials.SessionToken'|tr -d '"')

第一行从aws sts命令分配响应并将其放入变量中。最后3行将从第一个命令中选择值,并将它们分配给aws cli使用的变量。

注意事项:

如果您创建了一个bash脚本,也可以在那里添加terraform命令。您也可以使用上面的行创建一个bash,并使用'。'运行它。在前面(即:. ./get-creds.sh)。这将在您当前的bash shell上创建变量。

角色到期,请记住角色通常一小时到期。

你的shell现在将有三个变量AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYAWS_SESSION_TOKEN。这意味着它会覆盖你的~/.aws/credentials。最简单的方法就是开始一个新的bash会话。

我用这篇文章作为我的来源来解决这个问题:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html


0
投票

一般来说,您需要引导目标帐户。最小化这意味着创建一个可以从管道角色中假设的角色,但可以包括一些其他资源。

© www.soinside.com 2019 - 2024. All rights reserved.