Tuesday, July 29, 2014

Gotcha of the Day: Accessing AWS EC2 Tags from within PHP

I've got bunch of dedicated EC2 instances running, and I'd like an easy way to configure the web app that runs on them. While I could control their configuration any number of ways, it occurred to me that it would be pretty dang sweet to be able to set parameters from within the Amazon Web Console. Each instance can have a number of tags associated with it, so if I could access those tags from within the server, I'd be golden.

Turns out, getting access to the tags isn't especially hard and is explained here. Essentially, you need to grab two programs from the web: ec2-metadata (or, use curl) and ec2-describe-tags.

Given these tools, I was able to write the following init script:


## Capture the ec2 tags associated with this server. Not
## really a long running process. Just something that can
## be invoked whenever

prog=`basename $0`

function start() {
  echo -n "Starting $prog: "
  instance_id=`$ec2_metadata | grep instance-id: | sed 's/^.*: //'`
  $ec2_describe_tags | grep  $instance_id | awk -F'\t' '{printf "%s:%s\n", $4, $5}' > $etc_tags
  echo "OK"

function stop() {
  echo "Stopping $prog: OK"

case "$1" in
    echo "Usage: $prog {start|stop|restart}"

(This lives in /etc/rc.d/init.d/ec2tags)

I then setup a softlink to this init script in /etc/rc.d/rc3.d/S80ec2tags.

Now, when the server boots the script runs, which generates /usr/local/etc/ec2-tags. For now, I'm manually updating the configuration by changing the parameters and running /etc/rc.d/init.d/ec2tags restart. Though, that could certainly be setup to be automated.

Finally, to get access these values in PHP, I've written this function:

function app_env() {
  $env = array();
  $fd = fopen("/usr/local/etc/ec2-tags", "r");
  while($line = fgets($fd)) {
    list($key, $value) = explode(":", $line);
    $env[trim($key)] = trim($value);
  return $env;

And I'm all set. Now, my PHP code can efficiently read EC2 tags, and I can control the configuration of my servers from a central location.

No comments:

Post a Comment