使用AWS CloudFormation参考创建yaml



我需要一个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" }}
]
}
}

最新更新