title: AWS Cloudformation invoke bash script for ec2 user data
body: <p>I have created a cloudformation template for EC2 instance , that will setup Tomcat in the user data. The template works fine when the script is embedded in the template. But I want to move the script in a separate bash script (named tomcat.sh) and invoke the script using userdata as cfn parameter from the AWS CLI. But getting the error</p>
  <pre><code>aws cloudformation create-stack --stack-name EC2Instance2 --template-url s3://cfn04012021/14-01-CFN-EC2-Instance2.yml --parameters ParameterKey=UserData,ParameterValue=$(base64 -w0 tomcat)
  
  usage: aws [options] &lt;command&gt; &lt;subcommand&gt; [&lt;subcommand&gt; ...] [parameters]
  To see help text, you can run:
  
    aws help
    aws &lt;command&gt; help
    aws &lt;command&gt; &lt;subcommand&gt; help
  
  Unknown options: -w0, tomcat)
  </code></pre>
  <p>The cloudformation template is as follows</p>
  <pre><code>AWSTemplateFormatVersion: 2010-09-09
  Description: EC2 Instance with Instance profile role to access S3 buckets
  
  Parameters:
    KeyName:
      Description: Key name to SSH to VM's. 
      Type: AWS::EC2::KeyPair::KeyName
    UserData:
      Type: String
      Default: &quot;&quot;
  
    MyStageVMInstance:
      Type: AWS::EC2::Instance
      Properties:
        ImageId: ami-0533f2ba8a1995cf9
        InstanceType: t2.micro
        KeyName: !Ref KeyName
        SecurityGroups:
          - !Ref MySecurityGroup
        IamInstanceProfile: !Ref MyInstanceProfile
        Tags:
          - Key: Name        
            Value: dev
        UserData: !Ref UserData
  </code></pre>
  <p>the bash script is</p>
  <pre><code>#!/bin/bash|
  sudo amazon-linux-extras install java-openjdk11
  sudo groupadd --system tomcat 
  sudo useradd -d /usr/share/tomcat -r -s /bin/false -g tomcat tomcat
  getent passwd tomcat
  getent group tomcat
  export VER=&quot;9.0.41&quot;
  wget https://archive.apache.org/dist/tomcat/tomcat-9/v${VER}/bin/apache-tomcat-${VER}.tar.gz
  sudo tar xvf apache-tomcat-${VER}.tar.gz -C /usr/share/
  sudo ln -s /usr/share/apache-tomcat-$VER/ /usr/share/tomcat
  sudo chown -R tomcat:tomcat /usr/share/tomcat
  sudo chown -R tomcat:tomcat /usr/share/apache-tomcat-$VER/ 
  sudo tee /etc/systemd/system/tomcat.service&lt;&lt;EOF
  [Unit]
  Description=Tomcat Server
  After=syslog.target network.target
  
  [Service]
  Type=forking
  User=tomcat
  Group=tomcat
  
  Environment=JAVA_HOME=/usr/lib/jvm/jre
  Environment='JAVA_OPTS=-Djava.awt.headless=true'
  Environment=CATALINA_HOME=/usr/share/tomcat
  Environment=CATALINA_BASE=/usr/share/tomcat
  Environment=CATALINA_PID=/usr/share/tomcat/temp/tomcat.pid
  Environment='CATALINA_OPTS=-Xms512M -Xmx1024M'
  ExecStart=/usr/share/tomcat/bin/catalina.sh start
  ExecStop=/usr/share/tomcat/bin/catalina.sh stop
  
  [Install]
  WantedBy=multi-user.target
  EOF
  sudo systemctl daemon-reload
  sudo systemctl start tomcat
  sudo systemctl enable tomcat
  </code></pre>