How can I send user-data output to the console logs on an EC2 instance running Amazon Linux or Amazon Linux 2?

Last updated: 2020-08-14

I'm trying to troubleshoot my Amazon Elastic Compute Cloud (Amazon EC2) Linux instance bootstrap. How can I log the user-data invocation and then ship it to the console logs?

Short description

To troubleshoot issues on your EC2 instance bootstrap without having to access the instance through SSH, you can add code to your user-data bash script that redirects all the output both to the /var/log/user-data.log and to /dev/console. When the code is executed, you can see your user-data invocation logs in your console.

Note: This resolution is for Amazon Linux and Amazon Linux 2 only. For information on instances running RHEL 7 or RHEL 8, see How can I log user-data for my EC2 instance running RHEL 7 or RHEL 8 and then ship it to the console logs? 

Resolution

Enter the following command to redirect the user-data output console:

#!/bin/bash -xe
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
  yum -y update
  echo "Hello from user-data!"

The following is the line that redirects the user-data output:

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

The following is sample console output:

<13>Nov 13 13:49:59 user-data:   amazon-ssm-agent.x86_64 0:2.3.228.0-1.amzn2
<13>Nov 13 13:49:59 user-data:   irqbalance.x86_64 2:1.5.0-2.amzn2.0.1
<13>Nov 13 13:49:59 user-data:   kernel-tools.x86_64 0:4.14.77-80.57.amzn2
<13>Nov 13 13:49:59 user-data:   kmod.x86_64 0:25-3.amzn2.0.2
<13>Nov 13 13:49:59 user-data:   kmod-libs.x86_64 0:25-3.amzn2.0.2
<13>Nov 13 13:49:59 user-data:   lz4.x86_64 0:1.7.5-2.amzn2.0.1
<13>Nov 13 13:49:59 user-data:   nss.x86_64 0:3.36.0-7.amzn2
<13>Nov 13 13:49:59 user-data:   nss-sysinit.x86_64 0:3.36.0-7.amzn2
<13>Nov 13 13:49:59 user-data:   nss-tools.x86_64 0:3.36.0-7.amzn2
<13>Nov 13 13:49:59 user-data:   openssl.x86_64 1:1.0.2k-16.amzn2.0.1
<13>Nov 13 13:49:59 user-data:   openssl-libs.x86_64 1:1.0.2k-16.amzn2.0.1
<13>Nov 13 13:49:59 user-data:
<13>Nov 13 13:49:59 user-data: Complete!
<13>Nov 13 13:49:59 user-data: + echo 'Hello from user-data!

Did this article help?


Do you need billing or technical support?