I wrote a Python script for this. My version is for yaml, but can easily be adapted to json.
Single dependency for parsing the template, with thanks to this SO post
pip install cfn_flip
#!/usr/bin/env python
import subprocess
import time
import yaml
from cfn_tools import load_yaml, dump_yaml
template_file = open('./template.yaml')
template = load_yaml(template_file.read())
for resource_key in template["Resources"]:
resource = template["Resources"][resource_key]
if resource["Type"] != 'AWS::DynamoDB::Table':
continue
table_name = resource["Properties"]["TableName"]
print(f'Creating table "{table_name}"')
table_definition = template["Resources"][resource_key]["Properties"]
time_to_live_definition = table_definition.get("TimeToLiveSpecification")
if time_to_live_definition:
# TimeToLiveSpecification is not accepted by create-table, it is a separate command
del(table_definition["TimeToLiveSpecification"])
subprocess.run(["aws", "dynamodb", "create-table", "--cli-input-yaml",dump_yaml(table_definition)])
if time_to_live_definition:
time_to_live_definition = {
"TableName": table_name,
"TimeToLiveSpecification": time_to_live_definition
}
subprocess.run(["aws", "dynamodb", "update-time-to-live", "--cli-input-yaml", dump_yaml(time_to_live_definition)])
# Tables are created asynch, give some time to complete
time.sleep(1)
The sleep at the end is for following warning mentioned in the help of create-table
. I have only tested this locally so far, so a smarter way to wait for completion might be needed.
You can optionally define secondary indexes on the new table, as part
of the "CreateTable" operation. If you want to create multiple tables
with secondary indexes on them, you must create the tables
sequentially. Only one table with secondary indexes can be in the
"CREATING" state at any given time.