Terraformer 合并多个 tfstate 文件

2024-01-04

我正在使用 terraformer 导入(不是 terraform,检查这个 https://github.com/GoogleCloudPlatform/terraformer https://github.com/GoogleCloudPlatform/terraformer)一些托管在 Google Cloud 上的基础设施,请参阅下面的命令。

i.e: terraformer import google --resources=networks,subnetworks,firewall,routes,forwardingRules,vpnTunnels --regions=europe-blabla1 --projects=my_project

它工作正常,命令的输出是一个单独的文件夹,其中包含我导入的每个资源的 tfstate 和 tf 文件。

2021/05/18 11:03:20 google Connecting....
2021/05/18 11:03:20 google save firewall
2021/05/18 11:03:20 google save tfstate for firewall
2021/05/18 11:03:20 google save routes
2021/05/18 11:03:20 google save tfstate for routes
2021/05/18 11:03:20 google save forwardingRules
2021/05/18 11:03:20 google save tfstate for forwardingRules
2021/05/18 11:03:20 google save vpnTunnels
2021/05/18 11:03:20 google save tfstate for vpnTunnels
2021/05/18 11:03:20 google save networks
2021/05/18 11:03:20 google save tfstate for networks
2021/05/18 11:03:20 google save subnetworks
2021/05/18 11:03:20 google save tfstate for subnetworks

现在我想要完成的是将多个 tfstate 文件合并为一个文件,以便拥有堆栈:一个用于网络,一个用于 iam、实例等。

我想知道是否有人能够做到这一点?或者是否有更好的方法来实现这一点?


我去过那里并且使用过Terraformer然后合并状态文件,这是我编写的用于进行状态文件迁移(合并)的脚本:

#!/usr/bin/env bash

state_pull() {
    echo ">> state pull"
    cd "$1" || return 1
    terraform init
    terraform state pull >terraform.tfstate
    cd ..
    return 0
}

state_mv() {
    echo ">> state mv"
    cd "$2" || return 1
    terraform init
    for i in $(terraform state list); do
        terraform state mv -state-out="../$1/terraform.tfstate" "$i" "$i"
    done
    cd ..
    return 0
}

state_push() {
    echo ">> state push"
    cd "$1" || return 1
    terraform state push terraform.tfstate
    cd ..
    return 0
}

cleanup() {
    echo ">> cleanup"
    cd "$1" || return 1
    rm terraform.tfstate
    rm terraform.tfstate.*
    cd ..
    return 0
}

# Print help text and exit.
if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    echo "Usage: tfmv.sh [options]"
    echo
    echo "Examples:"
    echo
    echo "  - ./tfmv.sh stack1-migrate-to stack2-migrate-from"
    echo "  - ./tfmv.sh app data"
    exit 1
fi

echo "> START"
echo ">> TF =  $(terraform version)..."
state_pull "$1"
state_mv "$1" "$2"
state_push "$1"
# cleanup "$1"
echo "> FINISHED"

如果这看起来很花哨,你可以使用https://github.com/minamijoyo/tfmigrate https://github.com/minamijoyo/tfmigrate使用 Go 可以做得更好。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Terraformer 合并多个 tfstate 文件 的相关文章

随机推荐