我正在使用 Terraform 管理 AWS 资源,我有一个模块,它的源是整个 terraform
文件夹,但现在我想在此模块下为 {{1} 创建一个子模块} 和 A.tf
文件,这样当我应用 terraform 时,如果我指定这个子模块,Terraform 就不必在这个子模块之外创建所有资源。
我已经尝试了几件事,但仍然无法正常工作,有什么我可以效仿的例子吗?
答案 0 :(得分:1)
正如@luk2302 指出的那样,最好创建可组合的模块而不是子模块。
无论如何,我能够按照你的要求创造一些东西。
❯❯ tree
.
├── main.tf
├── sub_module_1
│ └── main.tf
├── sub_module_2
│ └── main.tf
└── terraform.tfstate
2 directories, 4 files
tmp/boo/parent_module
❯❯ ls
main.tf sub_module_1/ sub_module_2/ terraform.tfstate
❯❯ terraform state list
aws_iam_role_policy_attachment.lambda_logs
aws_sns_topic.user_updates
module.iam_role_info.aws_iam_role.iam_for_lambda
module.logging_policy.aws_iam_policy.lambda_logging
❯❯ ls
main.tf parent_module/
/private/tmp/boo
❯❯ cat main.tf
variable "env" {
type = string
default = "dev"
}
locals {
default_tags = {
Product = "wallaby",
Environment = var.env,
Application = "wallaby-api"
}
}
module "parent_module" {
source = "./parent_module"
}
output "sns_info" {
value = module.parent_module.sns_info
}
在 parent_module
main.tf
❯❯ cat main.tf
module "iam_role_info" {
source = "./sub_module_1"
}
module "logging_policy" {
source = "./sub_module_2"
}
resource "aws_iam_role_policy_attachment" "lambda_logs" {
role = module.iam_role_info.lambda_role_name
policy_arn = module.logging_policy.iam_policy_arn
}
resource "aws_sns_topic" "user_updates" {
name = "user-updates-topic"
}
output "sns_info" {
value = aws_sns_topic.user_updates.arn
}
❯❯ cat sub_module_1/main.tf
resource "aws_iam_role" "iam_for_lambda" {
name = "iam_for_lambda"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
output "lambda_role_name" {
value = aws_iam_role.iam_for_lambda.name
}
❯❯ cat sub_module_2/main.tf
# See also the following AWS managed policy: AWSLambdaBasicExecutionRole
resource "aws_iam_policy" "lambda_logging" {
name = "lambda_logging"
path = "/"
description = "IAM policy for logging from a lambda"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*",
"Effect": "Allow"
}
]
}
EOF
}
output "iam_policy_arn" {
value = aws_iam_policy.lambda_logging.arn