如何在Terraform子文件夹中声明托管资源

时间:2019-09-29 15:00:56

标签: amazon-web-services resources terraform declare

结构:

.
├── aws
│   ├── master
│   │   ├── accounts.tf
│   │   ├── dynamodb.tf
│   │   ├── main.tf
│   │   ├── organization.tf
│   │   └── s3.tf
│   └── ou
│       └── dev2
│           └── dev2_foo
│               └── main.tf
├── main.tf

tfstate文件在s3中,并且具有一个dynamodb锁。 子帐户在main.tf中作为模块加载

module "aws_dev2_dev2_foo" {
         source         = "./aws/ou/dev2/dev2_foo"
}

aws/ou/dev2/dev2_foo/main.tf

我正尝试使用此帐户:

provider "aws" {
         alias          = "assume"
         region         = "eu-central-1"
         profile        = "terraform"
         assume_role {
            role_arn = "arn:aws:iam::${aws_organizations_account.devteam02.id}:role/terrasume"
            session_name = "terraforming"
         }
}

resource "aws_iam_account_alias" "alias" {
  provider = "aws.assume"
  account_alias = "dev02_devteam02-foo"
}

如果我运行Terraform,我会收到此错误:

  

托管资源“ aws_organizations_account”“ devteam02”没有   在aws_dev2_dev2_foo中声明。   在这种情况下:如何声明此托管资源?

该资源在 aws / master / accounts.tf 中声明:

resource "aws_organizations_account" "devteam02" {
  name      = "devteam02"
  email     = "john@devteam02.loc"
  role_name = "terrasume"
  parent_id = "${aws_organizations_organizational_unit.dev2_foo.id}"

  lifecycle {
    ignore_changes = ["role_name"]
  }

}

1 个答案:

答案 0 :(得分:0)

您需要将aws_organizations_account.devteam2资源作为变量传递给模块。

aws/ou/dev2/dev2_foo中创建一个variables.tf。这会将输入变量保存到您的dev2_foo模块。

内容可能类似于

variable "other_aws_org_id"
{
  type = string
}

然后在main.tf中,调用模块时需要初始化此变量。例如

module "aws_dev2_dev2_foo"
{
  source = "./aws/ou/dev2/dev2_foo"
  other_aws_org_id = "${aws_organizations_account.devteam02.id}"
}

然后在模块main.tf中,将provider块更改为类似

provider "aws"
{
  alias = "assume"
  region = "eu-central-1"
  profile = "terraform"
  assume_role  
  { 
    role_arn = "arn:aws:iam::${var.other_aws_org_id}:role/terrasume"
    session_name = "terraforming"
  } 
}

https://www.terraform.io/docs/configuration/variables.html