基础使用
基本命令
Usage: terraform [global options] <subcommand> [args]
The available commands for execution are listed below.
The primary workflow commands are given first, followed by
less common or more advanced commands.
Main commands:
init Prepare your working directory for other commands
validate Check whether the configuration is valid
plan Show changes required by the current configuration
apply Create or update infrastructure
destroy Destroy previously-created infrastructure
All other commands:
console Try Terraform expressions at an interactive command prompt
fmt Reformat your configuration in the standard style
force-unlock Release a stuck lock on the current workspace
get Install or upgrade remote Terraform modules
graph Generate a Graphviz graph of the steps in an operation
import Associate existing infrastructure with a Terraform resource
login Obtain and save credentials for a remote host
logout Remove locally-stored credentials for a remote host
metadata Metadata related commands
modules Show all declared modules in a working directory
output Show output values from your root module
providers Show the providers required for this configuration
refresh Update the state to match remote systems
show Show the current state or a saved plan
stacks Manage HCP Terraform stack operations
state Advanced state management
taint Mark a resource instance as not fully functional
test Execute integration tests for Terraform modules
untaint Remove the 'tainted' state from a resource instance
version Show the current Terraform version
workspace Workspace management
Global options (use these before the subcommand, if any):
-chdir=DIR Switch to a different working directory before executing the
given subcommand.
-help Show this help output or the help for a specified subcommand.
-version An alias for the "version" subcommand.
state
terraform refresh:获取资源实际状态更新stateterraform state list:列出state 记录的资源terraform state rm:删除某些state状态terraform state pull:远端拉取状态文件terraform state push:推送本地的状态更新到远端
Terraform Layout(推荐代码文件布局)
- main.tf: 主要业务逻辑
- outputs.tf: 定义输出内容
- vars.tf: 定义变量参数
- version.tf: 定义依赖和版本
└── localstack-terraform-test
├── LICENSE
├── main.tf
├── outputs.tf
├── provider.tf
├── README.md
├── vars.tf
├── versions.tf
如何传参
- 1.通过在命令行配置:
terraform apply -var="prefix=values' - 2.指定配置文件:
terraform apply -var-file="testing.tfvars' - 3.环境变量:
export TF_VAR_prefix=values - 4.定义的默认值
- 5.交互式输入
表达式
- 算术运算符和逻辑运算符
- 条件表达式
<CONDITION>?<TRUE_VALUE>:<FALSE_VALUE> - for表达式
[for s in var.list : upper(s)] - splat 表达式
var.listp[*].id
函数
- 数值函数(
abs/floor/log/max/min/pow) - 字符串函数(
format/join/lower/regex/replace/split/substr) - 集合函数(
concat/containers/flatten/list/map/merge/reverse/sort) - 编码函数(
base64/json/urlencode/yaml) - 文件系统函 数(
dirname/abspath/file/basename/templatefile) - 时间函数(
timestaml/formatdate/timeadd) - 哈希和加密函数(
sha1/md5/sha256/sha512/uuiid) - 类型转换函数(
tolist/tomap/toset/tostring/)
元参数
作用域
- resource
- modules
depends_on
- Terraform会根据引用自动生成资源的依赖关系图(DAG:有向无环图)
- 根据DAG来控制创建和销毁顺序
- 可以通过depends_on显性指定依赖关系,控制创建和销毁过程
- 使用
terraform graph|dot -Tsvg > graph.svg生成依赖图(graphviz)
resource "helm_release" "argo_cd" {
depends_on = [module.k3s, null_resource.download_k3s_yaml]
name = "argocd"
repository = "https://argoproj.github.io/argo-helm"
chart = "argo-cd"
namespace = "argocd"
create_namespace = true
}
count
- 对相同的资源指定创建的数量
resource "tencentcloud_instance" "web" {
count = 4
instance_name = "web server"
availability_zone = data.tencentcloud_availability_zones_by_product.default.zones.0.name
image_id = data.tencentcloud_images.default.images.0.image_id
instance_type = data.tencentcloud_instance_types.default.instance_types.0.instance_type
system_disk_type = "CLOUD_BSSD"
system_disk_size = 50
allocate_public_ip = true
internet_max_bandwidth_out = 100
instance_charge_type = "SPOTPAID"
orderly_security_groups = [tencentcloud_security_group.default.id]
password = var.password
}
for_each
- 在单个块中创建多个资源
- 控制资源的分布
如对不同的子网进行创建
locals {
subnet_ids = toset([
"subnet-1",
"subnet-2",
])
}
resource "aws_instance" "server" {
for_each = local.subnet_ids
ami = "ami_afdhjklass12"
instance_type = "t2.micro"
subbet_id = each.key
tags = {
Name = "server ${each.key}"
}
}
lifecycle
- create_before_destroy
- 销毁前先创建,防止服务中断
- prevent_destroy
- 阻止删除
- ignore_changes
- 忽略差异
- replace_triggered_by
- 当引用项目发生变化时替换资源
resource "azurerm_resource_group" "example" {
·····
lifecycle {
create_before_destory = true
}
}
Provisioners执行动作
file
- 将本地文件复制到远端
resource "aws_instance" "web" {
···
provisioner "file" {
source = "conf/app.conf"
destination = "/etc/app.conf"
}
}
local-exec
- 在terraform本端执行
resource "null_resource" "download_k3s_yaml" {
provisioner "local-exec" {
command = "scp -i ${path.module}/sshkey/key -o StrictHostKeyChecking=no ubuntu@${tencentcloud_instance.web[0].public_ip}:/tmp/k3s.yaml ${path.module}/config.yaml"
}
depends_on = [null_resource.fetch_kubeconfig]
}
remote-exec
- 在远端设备执行
通过inline执行命令
resource "null_resource" "fetch_kubeconfig" {
provisioner "remote-exec" {
connection {
type = "ssh"
host = tencentcloud_instance.web[0].public_ip
user = "ubuntu"
password = var.password
}
inline = [
"mkdir -p ~/.ssh",
"echo '${file("${path.module}/sshkey/key.pub")}' >> ~/.ssh/authorized_keys",
"chmod 700 ~/.ssh",
"chmod 600 ~/.ssh/authorized_keys",
"sudo cp /etc/rancher/k3s/k3s.yaml /tmp/k3s.yaml",
"sudo chown ubuntu:ubuntu /tmp/k3s.yaml",
"sed -i 's/127.0.0.1/${tencentcloud_instance.web[0].public_ip}/g' /tmp/k3s.yaml"
]
}
depends_on = [module.k3s]
}
多环境管理,Module+目录隔离
把组件制作成模块,标准化variables及output,差异部分通过传入的参数控制
├─modules
│ ├─cvm
│ │ main.tf
│ │ output.tf
│ │ variables.tf
│ │ version.tf
│ │
│ └─k3s
│ main.tf
│ output.tf
│ variables.tf
│
├─dev
│ main.tf
│ variables.tf
│
└─testing
main.tf
variables.tf