我在dev_account创建了一个codepipeline,它在dev_account,test_account和prod_account都触发了codedeploy,三个帐户的代码部署看起来相同,只是它们位于不同的帐户中。
以下是我的terraform文件的组织。我使用terraform模块重用代码,但我仍然认为我的代码有很多重复的代码,如何优化它们?
common_infr/
codepipeline.tf # dev_account has codepipeline, codedeploy
codedeploy.tf
test_account/
codedeploy.tf # test_account has a codedeploy
prod_account/
codedeploy.tf # prod_account has a codedeploy
pipeline1/
main.tf #run terraform apply here using dev account
test_account/
main.tf #run terraform apply here using test account
prod_account/
main.tf #run terraform apply here using prod account
这是pipeline1 / main.tf:
module "pipeline1" {
source = "../common_infra"
variable1 = "..."
...
}
这是pipeline1 / test_account / main.tf:
module "pipeline1" {
source = "../../common_infra/test_account"
variable1 = "..."
...
}
这是pipeline1 / prod_account / main.tf:
module "pipeline1" {
source = "../../common_infra/prod_account"
variable1 = "..."
...
}
三个帐户的codedeploy.tf看起来一样。如何优化这个?
答案 0 :(得分:4)
不是为每个帐户的codedeploy.tf
创建3个模块,而是创建一个codedeploy
模块。在每个帐户的main.tf中,来源codedeploy
模块和pass in the account's provider。这是test_account
的样子。
provider "aws" {
alias = "test_account"
profile = "your_profile_name_for_test_account"
}
module "pipeline1" {
providers = {
aws = "aws.test_account"
}
source = "../../common_infra/codedeploy"
variable1 = "..."
...
}
编辑以详细说明目录布局。最后,您要从codepipeline
中移除common_infr
并将其放入自己的模块中。
modules/
codepipeline/
codepipeline.tf
common_infr/
codedeploy.tf
accounts/
test_account/
main.tf
prod_account/
main.tf
test_account / main.tf:
provider "aws" {
alias = "test_account"
profile = "your_profile_name_for_test_account"
}
module "pipeline1" {
providers = {
aws = "aws.test_account"
}
source = "../modules/codepipeline"
variable1 = "..."
...
}
module "common_infr" {
providers = {
aws = "aws.test_account"
}
source = "../modules/common_infr"
variable1 = "..."
...
}
prod_account / main.tf:
provider "aws" {
alias = "prod_account"
profile = "your_profile_name_for_prod_account"
}
module "common_infr" {
providers = {
aws = "aws.prod_account"
}
source = "../modules/common_infr"
variable1 = "..."
...
}