D. Meier
D. Meier

Reputation: 31

How to declare a managed resource in Terraform sub-folder

Structure:

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

Out tfstate file is in S3 and has a DynamoDB lock. Our sub-account is loaded as a module within main.tf with:

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

in

aws/ou/dev2/dev2_foo/main.tf

I'm trying to assume into this account:

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"
}

I'm getting this error if I run Terraform:

A managed resource "aws_organizations_account" "devteam02" has not been declared in aws_dev2_dev2_foo.

So, in this scenario, how can I declare this managed resource?

The resource was declared inside aws/master/accounts.tf:

resource "aws_organizations_account" "devteam02" {
  name      = "devteam02"
  email     = "[email protected]"
  role_name = "terrasume"
  parent_id = "${aws_organizations_organizational_unit.dev2_foo.id}"

  lifecycle {
    ignore_changes = ["role_name"]
  }
}

Upvotes: 3

Views: 11854

Answers (1)

Dude0001
Dude0001

Reputation: 3450

You need to pass the aws_organizations_account.devteam2 resource as a variable to the module.

In aws/ou/dev2/dev2_foo create a variables.tf. This will hold the input variable to your dev2_foo module.

The contents could be something like

variable "other_aws_org_id"
{
  type = string
}

Then in main.tf, you need to initialize this variable when you call the module. e.g.

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

Then in your module main.tf, change the provider block to something like

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

Upvotes: 3

Related Questions