title: AWS EC2 log userdata output to cloudwatch logs
body: <p>I'm doing pre-processing tasks using EC2.</p>
  <p>I execute shell commands using the userdata variable. The last line of my userdata has <code>sudo shutdown now -h</code>. So the instance gets terminated automatically once the pre-processing task completed.</p>
  <p>This is how my code looks like.</p>
  <pre><code>import boto3
  
  
  userdata = '''#!/bin/bash
  pip3 install boto3 pandas scikit-learn
  aws s3 cp s3://.../main.py .
  python3 main.py
  sudo shutdown now -h
  '''
  
  
  def launch_ec2():
      ec2 = boto3.resource('ec2',
                           aws_access_key_id=&quot;&quot;, 
                           aws_secret_access_key=&quot;&quot;,
                           region_name='us-east-1')
      instances = ec2.create_instances(
          ImageId='ami-0c02fb55956c7d316',
          MinCount=1,
          MaxCount=1,
          KeyName='',
          InstanceInitiatedShutdownBehavior='terminate',
          IamInstanceProfile={'Name': 'S3fullaccess'},
          InstanceType='m6i.4xlarge', 
          UserData=userdata,
          InstanceMarketOptions={
              'MarketType': 'spot',
              'SpotOptions': {
                  'SpotInstanceType': 'one-time',
              }
          }
      )
      print(instances)
  
  
  launch_ec2()
  </code></pre>
  <p>The problem is, sometime when there is an error in my python script, the script dies and the instance get terminated.</p>
  <p>Is there a way I can collect error/info logs and send it to cloudwatch before the instance get terminated? This way, I would know what went wrong.</p>