CloudFormationのテンプレートをVelocityで生成する
CloudFormationのテンプレートは変数を定義したり他のコンポーネントを参照させたり結構いろいろなことが出来ますが汎用的に書こうとすると複雑になってしまい慣れてない人だと読みづらいテンプレートになってしまうため、 テンプレートのテンプレートを作成してApache VelocityでAMIやスナップショットIDなど
注入する方がメンテナンスも楽かなと思い試してみました。
要するにMappingsとParametersを使用せずにVelocityのテンプレートを書いてJavaから変数を渡します。
Velocityに限らずのテンプレートエンジンだとコメントも書き放題なのでメンテナンスを考えると何かしらテンプレートエンジンを使用する方がいい気がします。
他にCloudFormationのテンプレートに向いているテンプレートエンジンがあれば教えて欲しいです。
テンプレート
セキュリティグループにEC2インスタンス×1+EBSボリューム×1(ファイル用)+EBSボリューム×N(DB用)みたいな簡単な構成です。
velocity-cfn-template-sample.template.vm
Javaコード
VelocityContext context = new VelocityContext(); context.put("description", new String("this is my sample template.")); context.put("availability_zone", new String("ap-notrheast-1")); context.put("instance", new Instance("ami-00000000", "SampleInstance", "t2.micro")); context.put("volume", new Snapshot(null, "File", "standard", "/dev/sdf", "/mnt/file", 10)); List<Ingress> ingress = new ArrayList<>(); ingress.add(new Ingress("tcp", 22, 22, "XXX.XXX.XXX.XXX")); ingress.add(new Ingress("tcp", 5432, 5432, "XXX.XXX.XXX.XXX")); context.put("security_group", new SecurityGroup("SampleSG", "this is a sample.", ingress)); List<Snapshot> snapshots = new ArrayList<>(); snapshots.add(new Snapshot("snap-00000001", "DB01", "standard", "/dev/sdh", "/var/lib/pgsql9/data1", 10)); snapshots.add(new Snapshot("snap-00000002", "DB02", "standard", "/dev/sdi", "/var/lib/pgsql9/data2", 10)); snapshots.add(new Snapshot("snap-00000003", "DB03", "standard", "/dev/sdj", "/var/lib/pgsql9/data3", 10)); context.put("snapshots", snapshots); Velocity.addProperty("input.encoding", "UTF-8"); Velocity.addProperty("output.encoding", "UTF-8"); Velocity.addProperty("resource.loader", "class"); Velocity.addProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); Velocity.init(); Template template = Velocity.getTemplate(name); StringWriter sw = new StringWriter(); template.merge(context, sw); System.out.println(sw.toString());