text 加密的env var到Terraform aws_secretsmanager_secret文件(带本地的数据对象)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 加密的env var到Terraform aws_secretsmanager_secret文件(带本地的数据对象)相关的知识,希望对你有一定的参考价值。

import argparse
import subprocess
from string import Template


def main():
    global env
    global project
    global secretType
    global secretsFile
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'secretsFile', help='env var secrets file to process, e.g. .secrets')
    parser.add_argument('project', help='project name, e.g. my_app')
    parser.add_argument('env', help='environment, e.g. production')
    parser.add_argument('type', help='secret type, e.g. credentials')
    args = parser.parse_args()
    env = args.env
    project = args.project
    secretType = args.type
    secretsFile = args.secretsFile
    secrets, locals = createSecrets()
    joinedSecrets = ''.join(str(secret) for secret in secrets)
    joinedLocals = ''.join(str(local) for local in locals)
    terraformLocalsFile = buildTerraformLocals(joinedLocals)
    terraformDataSecretsFile = buildTerraformDataSecrets(joinedSecrets)
    writeFile(secretsFile + "_locals", terraformLocalsFile)
    writeFile(secretsFile, terraformDataSecretsFile)
    subprocess.run(["terraform", "fmt"])


def createSecrets():
    locals = []
    secrets = []
    f = open(secretsFile, "r")
    fl = f.readlines()
    for line in fl:
        parts = line.split('=', 1)
        key = parts[0].lower()
        value = parts[1].rstrip()
        name = env + "_" + key
        locals.append(buildLocal(name, key))
        secrets.append(buildSecret(name, key, value))
    return secrets, locals


def buildSecret(name, key, value):
    secretTemplate = Template(
        'secret { name = "$name" payload = "$value" context { type = "$secretType" env = "$env"} }')
    return secretTemplate.substitute(name=name, env=env, key=key, value=value, secretType=secretType)


def buildLocal(name, key):
    localTemplate = Template(
        '$key = "$${data.aws_kms_secrets.$project.plaintext["$name"]}"')
    return localTemplate.substitute(key=key, name=name, project=project)


def buildTerraformLocals(locals):
    localsTemplate = Template('locals { $locals }')
    return localsTemplate.substitute(locals=locals)


def buildTerraformDataSecrets(secrets):
    secretsTemplate = Template(
        'data "aws_kms_secrets" "$project" { $secrets }')
    return secretsTemplate.substitute(project=project, secrets=secrets)


def writeFile(name, content):
    f = open(name + ".tf", "w+")
    f.write(content)
    f.close()


if __name__ == "__main__":
    main()

以上是关于text 加密的env var到Terraform aws_secretsmanager_secret文件(带本地的数据对象)的主要内容,如果未能解决你的问题,请参考以下文章

Terraform 在单个条件中匹配多个条件

通过 Terraform 添加 AWS 安全组时出现问题

在 terraform 文件而不是 env 变量中为 Terraform 提供凭据

如何在 Terraform 中进行简单的字符串连接?

在另一个模板中包含一个 terraform 模板

terraform plan 未检测到漂移