Launch / Terminate Linux services using AWS Run Command

Introduction

In this post, we will learn controlling system services using AWS Run Command. We will see how to control Apache service with an example. The same process can be applied to other services like Mysql, Tomcat, etc.

In small IT firms, there are limited team members who know about the command line. There are situations when some limited number of commands needs to be performed.

Think about a situation when you need to restart your Apache server and your IT staff not available at that moment. To solve this, we can configure AWS Run command so that someone just goes to AWS dashboard and perform required actions.

Prerequisites

  • AWS Run command
  • Ubuntu EC2 instance

To Run AWS command, we first need to create a document that contains the required command to execute.

Create Document

Let’s create a document that contains Linux command and runtime parameters.

  1. Open EC2 dashboard and click on Documents link. (available under SYSTEM MANAGER SHARED RESOURCES)
  2. Click on Create Document. Enter following details:
    1. Name*: ApacheServiceController
    2. Document type: Command
    3. Content*: {"schemaVersion":"2.2", "description":"linux apache service controller", "parameters":{"action":{"type":"String","default":"status"}}, "mainSteps":[{"action":"aws:runShellScript","name":"ApacheService", "precondition":{"StringEquals":["platformType","Linux"]}, "inputs":{"runCommand":["service apache2 {{action}}"]}}]}
    4. Click on Create Command.
  3. Now go to Documents section and scroll down to find ApacheServiceController.

Run command

Let’s execute the document to the target machine. Following are requirements to run document:

Please prepare all required steps and continue.

Now we are ready to use our document to control apache service using Run command.

  1. Open EC2 Dashboard and click on ‘Run Command’ under SYSTEM MANAGER SERVICES.
  2. Click on ‘Run Command’ button.
  3. Select Command document*: ApacheServiceController.
  4. Select Targets by* : <select ec2 instance to which you attached IAM role and SSM installed along with apache2 running>.
  5. ‘Action’ : start. This will start your apache2 service.
  6. Click ‘Run’. Click ‘View Result’.
  7. Select latest command id associated with Document ApacheServiceController. It must show the status success.

You can reuse this command by modifying Action field. You can stop, restart, or perform any other action.

Conclusion

We learned how to control system services using EC2 Run command. We can use Run Command to decouple administration and configuration part of EC2 instances. There are much more we can do with help or Run Command. Please explore and comment, that might help others too.

Leave a Reply

Your email address will not be published. Required fields are marked *