Sunday, November 17, 2013

AWS CloudFormation - Tips for the Novice (How to perform a task once per launch - not once per instance)

Here's the issue - we want to launch a stack that includes an RDS database.  We only want to execute some process one time per stack launch, not for each instance.



Here's the singleton pattern I came up with after Googling for an hour with no luck.

Basic strategy is to retrieve the ami launch index for an instance during the execution of the UserData script and only execute some snippet if the instance index is 0 (presumably the first one to launch).

We're also updating Bedrock's tagx.xml file with the RDS endpoint to point to the session database.

...
"# get RDS host name and update tagx.xml\n",
"BEDROCK_DB_HOST=",  { "Fn::GetAtt" : [ "BedrockDB", "Endpoint.Address"] }, "\n",
"echo $BEDROCK_DB_HOST > /tmp/bedrock-host\n",
"sed \"s/:bedrock/:bedrock:$BEDROCK_DB_HOST/;\" /usr/lib/bedrock/config/tagx.xml > /tmp/tagx.xml\n",
"mv /tmp/tagx.xml /usr/lib/bedrock/config/tagx.xml\n",
"\n",
"# create session database if this is instance 0\n",
"ami_launch_index=$(wget http://169.254.169.254/latest/meta-data/ami-launch-index -O - 2>/dev/null)\n",
"[ $ami_launch_index = \"0\" ] && mysqladmin -u fred --password=flintstone -h $BEDROCK_DB_HOST create bedrock\n",


"[ $ami_launch_index = \"0\" ] && cat /usr/share/bedrock/create-session.sql | mysql -u fred --password=flintstone -h $BEDROCK_DB_HOST bedrock\n",

Sort of proud of this one...


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.