Terraform 帮我们创建好instance以后,这个时候我们只是有一个空的instance,任何事情都干不了,我们需要做一些初始化的操作,例如安装必要的软件包,增加特定用户,修改特定配置文件等
Terraform 也帮我们提供了这个工具:Provisioner
直接看例子
1 2 3 4 5 6 7 8 |
resource "aws_instance" "example" { ami = "ami-b374d5a5" instance_type = "t2.micro" provisioner "local-exec" { command = "echo ${aws_instance.example.public_ip} > ip_address.txt" } } |
每个资源都支持多个provisioner ,上边的例子中我们用的是local-exec 这个provisioner
local-exec 提供的功能是在当前机器(跑terraform 命令的机器)上执行一些操作,所以暂时我们不用担心需要远程登录到别的机器上做操作的问题
与local-exec 对应的的provisioner是remote-exec ,这个命令是在远程的机器上执行的命令,这个时候我们就需要选择是ssh或者winrm来连接到目标机器了
看一个remote-exec的例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
resource "aws_key_pair" "example" { key_name = "examplekey" public_key = file("~/.ssh/id_rsa.pub") } resource "aws_instance" "web" { key_name = aws_key_pair.example.key_name # ... connection { type = "ssh" user = "root" private_key = file("~/.ssh/id_rsa") host = self.ip } provisioner "remote-exec" { inline = [ "sudo amazon-linux-extras enable nginx1.12", "sudo yum -y install nginx", "sudo systemctl start nginx" ] } |
注意provisioner仅仅会在资源被创建的时候执行,它并不能代替配置管理工具,它不能修改已经在运行的资源
Tainted Resources
有时候,我们资源创建成功了,但是provisioner没有执行成功,这个时候Terraform认为我们的资源是不“安全”的,Terraform 会将这个资源标记为tainted
当我们下次执行apply的时候,terraform不会重新尝试provisioner,它会直接将标记为tainted的资源删掉,然后重新创建,通过这样的方式来触发provisioner进行再次尝试
所以我们可以利用Terraform的这个特点,来重新创建指定的资源
1 |
terraform taint resource.id |
命令执行后,不会立刻修改我们的基础架构,它修改的是本地的状态文件,一旦某个资源被标记为tainted,下次apply的时候,这个资源就会被重新创建
Latest posts by Zhiming Zhang (see all)
- aws eks node 自动化扩展工具 Karpenter - 8月 10, 2022
- ReplicationController and ReplicaSet in Kubernetes - 12月 20, 2021
- public key fingerprint - 5月 27, 2021