minamijoyo / tfmigrate

A Terraform / OpenTofu state migration tool for GitOps
MIT License
1.12k stars 57 forks source link

split resources with dependencies. #170

Open chore1110 opened 7 months ago

chore1110 commented 7 months ago

I want to split the following tf file with dependencies into different states only for operator-role module by tf migrate. I would like to leave the production-hoge resource in its current state.

# main.tf

module "production-hoge" {
  source = "git@github.com:hoge/terraform.git?ref"

  stage       = "production"
  project     = "hoge"
  description = "hoge"
  alias-name  = "hoge"

  user-role-arns = [
    module.operator.role-arn,
  ]
}

module "operator" {
  source = "git@github.com:Hoge/terraform-hoge.git"
  name = "operator"
  additional-policy-arns = [
    module.base_policy.developer-policy-arn,
    aws_iam_policy.s3-policy.arn,
  ]
}

output.tf

# output.tf
output "admin-iam" {
  value = module.admin.role-arn
}
# hoge.hcl

migration "multi_state" "migrator" {
  from_dir       = "../infra/aws"
  from_skip_plan = false
  to_dir         = "../infra/global/aws"
  to_skip_plan   = false
  from_workspace = ""
  to_workspace   = ""
  actions        = ["mv module.operator module.operator"]
  force          = false
}

But when I run tfmigrate plan, I get an error. Is there any way to work around this error?

% tfmigrate plan hoge.hcl

Error: Reference to undeclared module

  on main.tf line 10, in module "production-hoge":
  10:     module.operator.role-arn,

No module call named "common-master-operator" is declared in the root module.
minamijoyo commented 6 months ago

There are several ways to share values between different root modules in Terraform.

(1) Just put the literal value in the code (2) Use a data source that references a specific resource type. (e.g. data "aws_iam_role") (3) Use a data source that references some Key-Value store (e.g. data "aws_ssm_parameter") (4) Use a data source that references a remote Terraform state. (a.k.a. data "terraform_remote_state")

This is more of a Terraform usage question than a tfmigrate one, so I won't say which one is best for you.

FYI: https://developer.hashicorp.com/terraform/language/state/remote-state-data