Update elasticsearch configuration on some ec2 instances

I am pretty new to aws stack. I setup a 3 nodes elasticsearch cluster by using cloudformation template. elasticsearch automatically set 2 nodes as master node, which is good. I want to scale up to 5 nodes with 3 nodes as master. Without specific setting, 4 nodes would be masters. I believe elasticsearch.yml needs specific setting to tell this node is a master node or not. But since the cloudformation is the same for all nodes, logic needs to be added to some of the nodes that there are 3 master nodes already, don't set itself as a master... which means nodes needs kinda communicate with each other while starting up.

Anybody have done something similar?