Execute User Data After the Initial Launch of Your EC2 Instance

0 67
  1. By default, user data scripts and cloud-init directives run only during the first boot cycle when an instance is launched. However, you can configure your user data script and cloud-init directives with a mime multi-part file. A mime multi-part file allows your script to override how frequently user data is executed in the cloud-init package. Then, the file executes the user script.
  2. Launch  a new EC2 instance using below bootstrap, please refer the link for help!
    #!/bin/bash
    sudo su
    yum install httpd -y
    service httpd start
    chkconfig httpd on
    echo "First Boot" > /var/www/html/index.html
  3. Above bash script will initial a webserver with index.html, which can be browsed in browser using Public IP  of EC2 instance
  4. Now stop your EC2 instance by selecting it > Action > Instance state > Stop
  5. Now from Actions menu > Instance Setting > View/Change User Data
  6. Input below Bash script in input box & save it
    Content-Type: multipart/mixed; boundary="//"
    MIME-Version: 1.0
    
    --//
    Content-Type: text/cloud-config; charset="us-ascii"
    MIME-Version: 1.0
    Content-Transfer-Encoding: 7bit
    Content-Disposition: attachment; filename="cloud-config.txt"
    
    #cloud-config
    cloud_final_modules:
    - [scripts-user, always]
    
    --//
    Content-Type: text/x-shellscript; charset="us-ascii"
    MIME-Version: 1.0
    Content-Transfer-Encoding: 7bit
    Content-Disposition: attachment; filename="userdata.txt"
    
    #!/bin/bash
    /bin/echo "Second Boot" > /var/www/html/index.html

  7. Now start your EC2 instance by going Actions > Instance State > Start
  8. To verify if the bash script execute again or not, can open Public IP of EC2 instance. Voila! New Webpage!

Leave A Reply

Your email address will not be published.