How to Refactor Hundreds of Cloudformation JSON Templates in Minutes

Do U need to refactor hundreds of JSON templates?

files = `ag DATA_BUCKET cloudformation/ -l`.split

files.each do |file|
  contents = `jq -f add_account_id.jq #{file}`, 'w') do |f|
    f.puts contents
walk(if type == "object" and .["Fn::Sub"]? and (.["Fn::Sub"] | type == "string" and (. | test("^[^$]*\\${DATA_BUCKET}[^$]*$"))) then .["Fn::Sub"] else . end)

Let’s start with an easy refactor. I needed to add an environment variable to every lambda function.

if .Resources.LambdaFunction then setpath(["Resources", "LambdaFunction", "Properties", "Environment", "Variables", "AWS_ACCOUNT_ID"]; { "Ref": "AWS::AccountId" }) else . end