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

2 minute read
1

I want to log the user data invocation and ship it to the console logs on my Amazon Elastic Compute Cloud (Amazon EC2) Linux instance.

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 runs, you can see your user-data invocation logs in your console.

Note: This resolution is only for Amazon Linux 1, Amazon Linux 2, and Amazon Linux 2023. For information on instances running RHEL 7 or RHEL 8, see How can I send user-data output to the console logs on an EC2 instance running RHEL 7 or RHEL 8?

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

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: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!

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 OFFICIAL
AWS OFFICIALUpdated 2 years ago