Logging user-data Script Output on EC2 Instances

| 6 Comments

Real time access to user-data script output

The early implementations of user-data scripts on EC2 automatically sent all output of the script (stdout and stderr) to /var/log/syslog as well as to the EC2 console output, to help monitor the startup progress and to debug when things went wrong.

The recent Ubuntu AMIs still send user-data script to the console output, so you can view it remotely, but it is no longer available in syslog on the instance. The console output is only updated a few minutes after the instance boots, reboots, or terminates, which forces you to wait to see the output of the user-data script as well as not capturing output that might come out after the snapshot.

Here is an example written in bash that demonstrates how to send all user-data script stdout and stderr automatically, transparently, and simultaneously to three locations:

  1. /var/log/syslog - In case you’d like to have the results in a standard logging location with automatic timestamps (real time).

  2. /var/log/user-data.log - In case you’d like to have a single place to get just the output and nothing but the output (real time).

  3. Console output - In case you’d like to be able to see the results through an EC2 API call or the ec2-get-console-output command line program without logging in to the instance (snapshot available a few minutes after boot).

The magic line to put towards the top of your bash script is:

exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1

From that point on, all output from the bash script and from programs it invokes will go to the above three locations.

Take care to put a space between the two > > characters at the beginning of the statement.

Here’s a complete user-data script as an example:

#!/bin/bash -ex
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
echo BEGIN
date '+%Y-%m-%d %H:%M:%S'
echo END

I started a new Ubuntu 10.10 Maverick instance with this script specified as the user-data:

ec2-run-instances --user-data-file user-data.sh --key $USERNAME ami-508c7839

I waited a bit for the instance to come up, made a note of the instance id and IP address, and then looked for the output in all three places:

$ ssh ubuntu@50.16.102.155 grep user-data: /var/log/syslog
Dec 22 05:00:31 ip-10-117-73-160 user-data: + echo BEGIN
Dec 22 05:00:31 ip-10-117-73-160 user-data: BEGIN
Dec 22 05:00:31 ip-10-117-73-160 user-data: + date '+%Y-%m-%d %H:%M:%S'
Dec 22 05:00:31 ip-10-117-73-160 user-data: 2010-12-22 05:00:31
Dec 22 05:00:31 ip-10-117-73-160 user-data: + echo END
Dec 22 05:00:31 ip-10-117-73-160 user-data: END

$ ssh ubuntu@50.16.102.155 cat /var/log/user-data.log
+ echo BEGIN
BEGIN
+ date '+%Y-%m-%d %H:%M:%S'
2010-12-22 05:00:31
+ echo END
END

$ ec2-get-console-output i-0c9e9461 | grep user-data:
user-data: + echo BEGIN
user-data: BEGIN
user-data: + date '+%Y-%m-%d %H:%M:%S'
user-data: 2010-12-22 05:00:31
user-data: + echo END
user-data: END

And, don’t forget to clean up your running test instance:

ec2kill i-0c9e9461

Notes:

  1. The “+” lines showed up in the output because I used the -x option in the bash script. This outputs each statement before executing it. The -e option tells bash to stop running the script as soon as one of the commands returns an error. Combined, these assist in debugging and figuring out what went wrong if there are problems.

  2. My ssh command examples do not use the -i option to specify a private key file because I followed my instructions on uploading your personal ssh key to EC2.

  3. user-data scripts can be written in any language as long as you can start the program file with shabang (#!). Bash is popular for writing startup scripts since it’s so easy to run other programs and has basic instructions for program flow, which is why I demonstrate it here. Redirecting output for other languages is left as an exercise for the reader.*

6 Comments

This didn't work for me on the instance-store 64-bit version of 10.10. I double-checked the exec line, it seems fine, but it still failed with a "redirection unexpected" error in the system log:

  /var/lib/cloud/data/scripts/part-000: 4: Syntax error: redirection unexpected
  run-parts: /var/lib/cloud/data/scripts/part-000 exited with return code 2

My user data:

  #!/bin/sh
  export AWS_ACCESS_KEY_ID=access key here
  export AWS_SECRET_ACCESS_KEY=secret access key here
  exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
  echo "I should be in the log file now."

Any idea? Thanks!

Oh, most likely it was because I used /bin/sh instead of /bin/bash!

I've been using a similar snippet in my user-data scripts but I also add "ERROR" to the start of any line that returned an error.

exec > >(tee >(logger -t "user-data")) 2> >(tee >(logger -t "user-data: ERROR") >&2)

bannistered:

Nested process substitutions! Love it!

#!/bin/bash -ex
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1

gives me:
2: Syntax error: redirection unexpected

on lucid. Ideas?

slatem:

You need to use /bin/bash for this trick to work. The error you provided is a result of running that command with /bin/sh, which is a symlink to /bin/dash.

Leave a comment

Ubuntu AMIs

Ubuntu AMIs for EC2:


More Entries

When Are Your SSL Certificates Expiring on AWS?
If you uploaded SSL certificates to Amazon Web Services for ELB (Elastic Load Balancing) or CloudFront (CDN), then you will want to keep an eye on the expiration dates and…
Throw Away The Password To Your AWS Account
reduce the risk of losing control of your AWS account by not knowing the root account password As Amazon states, one of the best practices for using AWS is Don’t…
AWS Community Heroes Program
Amazon Web Services recently announced an AWS Community Heroes Program where they are starting to recognize publicly some of the many individuals around the world who contribute in so many…
EBS-SSD Boot AMIs For Ubuntu On Amazon EC2
With Amazon’s announcement that SSD is now available for EBS volumes, they have also declared this the recommended EBS volume type. The good folks at Canonical are now building Ubuntu…
EC2 create-image Does Not Fully "Stop" The Instance
The EC2 create-image API/command/console action is a convenient trigger to create an AMI from a running (or stopped) EBS boot instance. It takes a snapshot of the instance’s EBS volume(s)…
Finding the Region for an AWS Resource ID
use concurrent AWS command line requests to search the world for your instance, image, volume, snapshot, … Background Amazon EC2 and many other AWS services are divided up into various…
Changing The Default "ubuntu" Username On New EC2 Instances
configure your own ssh username in user-data The official Ubuntu AMIs create a default user with the username ubuntu which is used for the initial ssh access, i.e.: ssh ubuntu@<HOST>…
Default ssh Usernames For Connecting To EC2 Instances
Each AMI publisher on EC2 decides what user (or users) should have ssh access enabled by default and what ssh credentials should allow you to gain access as that user.…
New c3.* Instance Types on Amazon EC2 - Nice!
Worth switching. Amazon shared that the new c3.* instance types have been in high demand on EC2 since they were released. I finally had a minute to take a look…
Query EC2 Account Limits with AWS API
Here’s a useful tip mentioned in one of the sessions at AWS re:Invent this year. There is a little known API call that lets you query some of the EC2…
Using aws-cli --query Option To Simplify Output
My favorite session at AWS re:Invent was James Saryerwinnie’s clear, concise, and informative tour of the aws-cli (command line interface), which according to GitHub logs he is enhancing like crazy.…
Reset S3 Object Timestamp for Bucket Lifecycle Expiration
use aws-cli to extend expiration and restart the delete or archive countdown on objects in an S3 bucket Background S3 buckets allow you to specify lifecycle rules that tell AWS…
Installing aws-cli, the New AWS Command Line Tool
consistent control over more AWS services with aws-cli, a single, powerful command line tool from Amazon Readers of this tech blog know that I am a fan of the power…
Using An AWS CloudFormation Stack To Allow "-" Instead Of "+" In Gmail Email Addresses
Launch a CloudFormation template to set up a stack of AWS resources to fill a simple need: Supporting Gmail addresses with “-” instead of “+” separating the user name from…
New Options In ec2-expire-snapshots v0.11
The ec2-expire-snapshots program can be used to expire EBS snapshots in Amazon EC2 on a regular schedule that you define. It can be used as a companion to ec2-consistent-snapshot or…
Replacing a CloudFront Distribution to "Invalidate" All Objects
I was chatting with Kevin Boyd (aka Beryllium) on the ##aws Freenode IRC channel about the challenge of invalidating a large number of CloudFront objects (35,000) due to a problem…
Email Alerts for AWS Billing Alarms
using CloudWatch and SNS to send yourself email messages when AWS costs accrue past limits you define The Amazon documentation describes how to use the AWS console to monitor your…
Cost of Transitioning S3 Objects to Glacier
how I was surprised by a large AWS charge and how to calculate the break-even point Glacier Archival of S3 Objects Amazon recently introduced a fantastic new feature where S3…
Running Ubuntu on Amazon EC2 in Sydney, Australia
Amazon has announced a new AWS region in Sydney, Australia with the name ap-southeast-2. The official Ubuntu AMI lookup pages (1, 2) don’t seem to be showing the new location…
Save Money by Giving Away Unused Heavy Utilization Reserved Instances
You may be able to save on future EC2 expenses by selling an unused Reserved Instance for less than its true value or even $0.01, provided it is in the…
Installing AWS Command Line Tools from Amazon Downloads
This article describes how to install the old generation of AWS command line tools. For the most part, these have been replaced with the new AWS cli that is…
Convert Running EC2 Instance to EBS-Optimized Instance with Provisioned IOPS EBS Volumes
Amazon just announced two related features for getting super-fast, consistent performance with EBS volumes: (1) Provisioned IOPS EBS volumes, and (2) EBS-Optimized Instances. Starting new instances and EBS volumes with…
Which EC2 Availability Zone is Affected by an Outage?
Did you know that Amazon includes status messages about the health of availability zones in the output of the ec2-describe-availability-zones command, the associated API call, and the AWS console? Right…
Installing AWS Command Line Tools Using Ubuntu Packages
See also: Installing AWS Command Line Tools from Amazon Downloads Here are the steps for installing the AWS command line tools that are currently available as Ubuntu packages. These include:…
Ubuntu Developer Summit, May 2012 (Oakland)
I will be attending the Ubuntu Developer Summit (UDS) next week in Oakland, CA. ┬áThis event brings people from around the world together in one place every six months to…
Uploading Known ssh Host Key in EC2 user-data Script
The ssh protocol uses two different keys to keep you secure: The user ssh key is the one we normally think of. This authenticates us to the remote host, proving…
Seeding Torrents with Amazon S3 and s3cmd on Ubuntu
Amazon Web Services is such a huge, complex service with so many products and features that sometimes very simple but powerful features fall through the cracks when you’re reading the…
CloudCamp
There are a number of CloudCamp events coming up in cities around the world. These are free events, organized around the various concepts, technologies, and services that fall under the…
Use the Same Architecture (64-bit) on All EC2 Instance Types
A few hours ago, Amazon AWS announced that all EC2 instance types can now run 64-bit AMIs. Though t1.micro, m1.small, and c1.medium will continue to also support 32-bit AMIs, it…
ec2-consistent-snapshot on GitHub and v0.43 Released
The source for ec2-conssitent-snapshot has historically been available here: ec2-consistent-snapshot on Launchpad.net using Bazaar For your convenience, it is now also available here: ec2-consistent-snapshot on GitHub using Git You are…