38. 使用 Terraform 设置用户变量
发布: (2026年2月2日 GMT+8 17:30)
2 min read
原文: Dev.to
Source: Dev.to
实验信息
Nautilus DevOps 团队正在使用 Terraform 自动化 IAM 用户创建,以实现更好的身份管理。
创建一个满足以下要求的 AWS IAM 用户:
- IAM 用户名
iamuser_mark应存储在名为KKE_user的变量中。 - 配置值应存放在
variables.tf文件中。 - Terraform 脚本应使用引用
variables.tf的main.tf文件进行组织。 - 工作目录:
/home/bob/terraform。
variables.tf
# Define variable for IAM user name
variable "KKE_user" {
description = "The name of the IAM user to create"
type = string
default = "iamuser_mark"
}
main.tf
# Create AWS IAM User with variable reference
resource "aws_iam_user" "this" {
name = var.KKE_user
tags = {
Name = var.KKE_user
}
}
Terraform 命令
cd /home/bob/terraform
terraform init
输出(摘录):
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/aws versions matching "5.91.0"...
- Installing hashicorp/aws v5.91.0...
- Installed hashicorp/aws v5.91.0 (signed by HashiCorp)
Terraform has created a lock file .terraform.lock.hcl to record the provider selections.
Terraform has been successfully initialized!
terraform plan
输出(摘录):
Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
+ create
# aws_iam_user.this will be created
+ resource "aws_iam_user" "this" {
+ arn = (known after apply)
+ force_destroy = false
+ id = (known after apply)
+ name = "iamuser_mark"
+ path = "/"
+ tags = {
+ "Name" = "iamuser_mark"
}
+ tags_all = {
+ "Name" = "iamuser_mark"
}
+ unique_id = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
terraform apply
提示时,输入 yes 进行确认。
输出(摘录):
aws_iam_user.this: Creating...
aws_iam_user.this: Creation complete after 0s [id=iamuser_mark]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.