gpt4 book ai didi

python - 使用 AWS CloudFormation 引用创建 yaml

转载 作者:行者123 更新时间:2023-12-03 07:48:24 24 4
gpt4 key购买 nike

我需要一个 python 代码来创建下面的 yaml 代码。

    Tags:
- Key: key1
Value: !Ref 'AWS::StackName'
- Key: Key2
Value: !Ref 'AWS::StackId'

这是我所拥有的,但不起作用。

def generate_resource(ami, source_data):
resource = {
"Type": "AWS::EC2::Instance",
"Properties": {
"ImageId": ami["ImageId"],
"InstanceType": ami["InstanceType"],
"PrivateIpAddress": ami["PrivateIpAddress"],
"KeyName": ami["KeyName"]
"SubnetId": { "Ref": "SubnetId" },
"SecurityGroupIds": { "Ref": "SecurityGroupId" },
"Tags": [
{ "Key": "key1", "Value": "{!Ref 'AWS::StackName'}"},
{ "Key": "key2", "Value": "{!Ref 'AWS::StackId'}"}
]
}
}

此代码的 yaml 输出格式不正确,因此它只是复制 {!Ref 'AWS::StackName'} 作为值。

import os, sys
import lib.aws as aws, lib.cft as cft, lib.inventory as inventory

BUCKET_NAME = 'testbucket'


def generate_cft(commit_hash, file_dict, dry_run):
return (
"# Autogenerated CFT for commit hash " + commit_hash + "\n" +
cft.generate(inventory.read(file_dict["path"]))
)


def upload_cft(commit_hash, file_dict, cft_text):
target_key = commit_hash + "/" + file_dict["name"].split("_")[0] + ".yaml"

aws.upload(BUCKET_NAME, target_key, cft_text)


def show_cft(file_dict, cft_text):
print(file_dict["path"] + " generates the following cft:")
print("")
print(cft_text)
print("")


def generate_and_upload(commit_hash, file_dict, dry_run):
cft_text = generate_cft(commit_hash, file_dict, dry_run)

aws.validate_cft(cft_text)

if dry_run:
show_cft(file_dict, cft_text)
else:
upload_cft(commit_hash, file_dict, cft_text)


def generate_and_upload_all(commit_hash, dry_run):
for file_dict in inventory.list():
print("generating cft for " + file_dict["path"])
generate_and_upload(commit_hash, file_dict, dry_run)


if __name__ == "__main__":
if not os.getcwd().endswith("ci"):
print("Please run this script from the ci directory")
exit()

commit_hash = sys.argv[1] if len(sys.argv) >= 2 else "test"
generate_and_upload_all(commit_hash, False)

最佳答案

是的!!!我研究了一下代码并弄清楚了。这是 CFT 创建期间的语法错误。现在,当我使用生成的 CFT 创建堆栈时,标记值将被实际的“StackId”替换。感谢大家的帮助和指导。

def generate_resource(ami, source_data):
resource = {
"Type": "AWS::EC2::Instance",
"Properties": {
"ImageId": ami["ImageId"],
"InstanceType": ami["InstanceType"],
"PrivateIpAddress": ami["PrivateIpAddress"],
"KeyName": ami["KeyName"],
"SubnetId": { "Ref": "SubnetId" },
"SecurityGroupIds": { "Ref": "SecurityGroupId" },
"Tags": [
{ "Key": "Name", "Value": ami["Name"] },
{ "Key": "BootUpDependsOn", "Value": ami["BootUpDependsOn"]},
{ "Key": "WaitTimeAfterBootUp", "Value": ami["WaitTimeAfterBootUp"]},
{ "Key": "Key1", "Value": { "Ref": "AWS::StackName" }},
{ "Key": "Key2", "Value": { "Ref": "AWS::StackId" }}
]
}
}

关于python - 使用 AWS CloudFormation 引用创建 yaml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63958872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com