首页 > 解决方案 > 使用 count 或 for_each 在 terraform 中按顺序创建资源。可能的?

问题描述

当我在资源定义中使用 count 或 for_each 时,资源是并行创建的。是否有一种解决方法可以使其连续?首先创建一个 count.index=0 的资源,然后 count.index=1,然后 count.index=2 等等

一点背景......我正在使用 terraform 进行初始 Hyperledger Fabric 设置。对于某些任务,我需要按顺序对区块链网络进行配置更新(例如为参与组织批准链代码)。否则我得到(MVCC_READ_CONFLICT)。如果我将这个逻辑完全外包给一些 bash 脚本,这当然可以实现,但也许......

标签: terraform

解决方案


因此,为了让事情发挥作用,需要在别处存储一种状态。最简单的就是使用一个文件:

resource "null_resource" "set_initial_state" {
    provisioner "local-exec" {
        interpreter = ["bash", "-c"]
        command = "echo \"0\" > current_state.txt"
    }
}

第二个资源在开始时实现了一个等待循环,在最后实现了状态改变:

resource "null_resource" "sequential_resources" {
    count = var.x
    provisioner "local-exec" {
        interpreter = ["bash", "-c"]
        command = "while [[ $(cat current_state.txt) != \"${count.index}\" ]]; do echo \"${count.index} is waiting...\";sleep 5;done"
    }

# Here you pack your sequential logic, e.g. upload of files to a service, 
# that can handle only one file at once.

    provisioner "file" {
        connection {
                type     = "ssh"
                host     = var.ip_address
                private_key = file(var.config.private_key)
                user     = var.config.admin_username
                script_path = var.provisioner_script_path
        }
        source = "${var.local_folder}/file_${count.index}.txt"
        destination = "/opt/data/file_${count.index}.txt"
    }

    provisioner "local-exec" {
        interpreter = ["bash", "-c"]
        command = "echo \"${count.index+1}\" > current_state.txt"
    }

depends_on = [null_resource.set_initial_state]
}

在此示例中,首先上传 file_0.txt,然后上传 file_1.txt,然后上传 file_2.txt 等,直到 file_x.txt


推荐阅读