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

2 minute read

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 run, 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?


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

By default, user data scripts and cloud-init directives are run only during the first boot when an instance is launched. For more information, see How can I utilize user data to automatically run a script with every restart of my Amazon EC2 Linux instance?

The following is sample console output:

<13>Nov 13 13:49:59 user-data:   amazon-ssm-agent.x86_64 0:
<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!

Note: The posted system (console) log output isn't updated continuously. Instances built on the Nitro system support the retrieval of the latest serial console output. For more information, see Instance console output.

Related information

Run commands on your Linux instance at launch

AWS OFFICIALUpdated 9 months ago