Automatically run scripts on ECS instances

Updated at:

This tutorial describes how to use an Auto Scaling lifecycle hook to suspend an ECS instance and a CloudOps Orchestration Service (OOS) template to automatically execute a script on the instance during scaling activities.

Prerequisites

  • A scaling group is created and is in the Enabled state.

  • You have a script ready. This tutorial uses a script that installs Apache on a CentOS 7.6 Linux instance as an example.

  • A Resource Access Management (RAM) role is created for OOS. The trusted entity of the RAM role must be Alibaba Cloud Service, the trusted service must be CloudOps Orchestration Service, and the RAM role must have the permissions to perform operations on the OOS template. For more information, see Create a RAM role for OOS and grant permissions.

    Note

    In this topic, the OOSServiceRole RAM role is used as an example. You can also use other roles.

Procedure

This tutorial uses the ACS-ESS-LifeCycleRunCommand public OOS template to demonstrate how to automatically run a script on an ECS instance during a scale-out event.

Step 1: Configure OOS RAM role permissions

The ACS-ESS-LifeCycleRunCommand template requires permissions to perform operations on ECS and Auto Scaling resources. You must grant these permissions to the RAM role that OOS assumes.

  1. Log on to the RAM console.

  2. Create a policy.

    1. In the left-side navigation pane, choose Permissions > Policies.

    2. On the Policies page, click Create Policy.

    3. On the Create Policy page, select the JSON tab, configure the parameters, and then click OK.

      The following table describes the parameters that are used in this tutorial. Use the default values for other parameters.

      Parameter

      Description

      Name

      Enter ESSHookPolicyForRunCommand.

      Policy Document

      Enter the following content:

      {
          "Version": "1",
          "Statement": [
              {
                  "Action": [
                      "ecs:DescribeInvocationResults",
                      "ecs:DescribeInvocations",
                      "ecs:RunCommand"
                  ],
                  "Resource": "*",
                  "Effect": "Allow"
              },
              {
                  "Action": [
                      "ess:CompleteLifecycleAction"
                  ],
                  "Resource": "*",
                  "Effect": "Allow"
              }
          ]
      }
  3. Attach the policy to the OOSServiceRole RAM role.

    1. In the left-side navigation pane, choose Identities > Roles.

    2. Find the OOSServiceRole RAM role and click Grant Permission in the Actions column.

      Add the required permissions for the OOSServiceRole RAM role that is assumed by OOS to complete the authorization.

    3. On the Grant Permission page, specify the resource scope and permissions, and then click OK.

      The following table describes the parameters that are used in this tutorial. Use the default values for other parameters.

      Parameter

      Description

      Resource Scope

      Select Account.

      Policies

      Add the custom policy ESSHookPolicyForRunCommand.

Step 2: Create a lifecycle hook for scale-out events

When you create the lifecycle hook, configure it to use an OOS template. This ensures that the script is automatically run when a scale-out event is triggered.

  1. Log on to the Auto Scaling console.

  2. In the navigation pane on the left, click Scaling Groups.

  3. In the top navigation bar, select a region.

  4. Find the scaling group that you want to manage and open its details page in one of the following ways:

    • In the Scaling Group Name/ID column, click the ID of the scaling group.

    • In the Actions column, click Details.

  5. Create a lifecycle hook for the scale-out event.

    1. At the top of the page, click the Event and adhesive hook tab.

    2. Click Create Lifecycle Hook.

    3. Configure the lifecycle hook parameters and click OK.

      The following table describes the parameters that are used in this tutorial. Use the default values for other parameters.

      Parameter

      Description

      Name

      Enter ESSHookForRunCommand.

      Scaling Activity Type

      Select Scale-Out.

      Timeout Period

      Enter a timeout period, for example, 300 seconds.

      Note

      The timeout specifies how long custom operations can run. If the timeout is too short, the operations may fail. Evaluate the time required for your custom operations and set an appropriate timeout.

      Default Execution Policy

      Select Continue.

      Send Notification When Lifecycle Hook Takes Effect

      Configure the template as follows:

      • Notification Method: Select OOS Template.

      • OOS Template Type: Select Public Templates.

      • Public Template: Select ACS-ESS-LifeCycleRunCommand.

      Configure the execution parameters for ACS-ESS-LifeCycleRunCommand as follows:

      • commandType: Select RunShellScript.

      • commandContent: Enter the script to be run. This tutorial uses the script that automatically installs Apache as an example.

        yum install -y httpd
        systemctl start httpd
        systemctl enable httpd
      • OOSAssumeRole: Select OOSServiceRole. In the Procedure section, you granted permissions to this role for managing ECS and Auto Scaling resources. OOS assumes this RAM role to obtain those permissions.

  6. Trigger a scale-out event.

    This tutorial uses a manually executed scaling rule as an example. You can also trigger scale-out events with scheduled or event-triggered tasks.

    Note

    Lifecycle hooks are triggered by scaling rules, but not by manually adding or removing ECS instances from a scaling group.

    1. On the details page of the scaling group, click the Scaling Rules and Event-triggered Tasks tab.

    2. On the Scaling Rules tab, click Create Scaling Rule.

    3. Set the scaling rule parameters and click OK.

      The following table describes the parameters that are used in this tutorial. Use the default values for other parameters.

      Parameter

      Description

      Rule Name

      Enter Add1.

      Rule Type

      Select Simple Scaling Rule.

      Operation

      Set to add 1 instance.

    4. In the scaling rule list, find the Add1 rule and click Recurrently in the Actions column.

    5. Click OK.

    After the scaling rule executes, an ECS instance is automatically created. Because the ESSHookForRunCommand lifecycle hook exists in the scaling group, the new instance enters a wait state. OOS is then notified to perform the operations defined in the ACS-ESS-LifeCycleRunCommand template.

  7. Verify that the automatically created ECS instance is properly configured.

    1. At the top of the page, click the Instance Management tab.

    2. Find the automatically created ECS instance and click the instance ID in the ECS Instance ID/Name column.

    3. In the navigation pane on the left, click Cloud Assistant.

    4. In the upper-right corner of the page, click Create/Run Command.

    5. Run the following command to check the Apache installation status.

      For more information, see Create and run a command. The command content is as follows:

      systemctl status httpd
      • On the Command Execution Result tab, view the execution details. If the result shows that the Apache service is installed and the status is active, the script in the commandContent parameter of the ACS-ESS-LifeCycleRunCommand template ran successfully.

      • If an ECS instance is created but Apache fails to install automatically, go to the OOS console to view the task execution details. For more information, see (Optional) Step 3: View the OOS execution details.

(Optional) Step 3: View the OOS execution details

  1. Log on to the OOS console.

  2. In the left-side navigation pane, choose Automated Task > Task Execution Management.

  3. Find the execution task by time and click Details in the Actions column.

  4. The execution details page provides a complete overview of the task.

    For example, you can view the execution ID and status in the Basic Information section. You can also click a task node in the Execution Result section to view its details. For more information, see View the details of an execution.

    Note

    If the execution fails, the related error message is displayed on the execution details page.

FAQ

If you fail to execute an O&M task, troubleshoot the issue based on the error message in the execution result. For more information, see FAQ.

The following table describes the common error message.

Error message

Cause

Solution

Forbidden.Unauthorized message: A required authorization for the specified action is not supplied.

You have not authorized Auto Scaling to perform the current action.

Check whether the OOSServiceRole RAM role has the required permissions.

Forbidden.RAM message: User not authorized to operate on the specified resource, or this API doesn't support RAM.

The RAM user or RAM role does not have the permissions to operate the corresponding resources.

Check whether the OOSServiceRole RAM role has the required permissions. For example, you can grant the OOS permissions to the RAM role. Before OOS can manage the resources that are declared in the OOS template, you must grant the required permissions to the RAM role.

LifecycleHookIdAndLifecycleActionToken.Invalid message: The specified lifecycleActionToken and lifecycleActionId you provided does not match any in process lifecycle action.

The ongoing lifecycle hook action has ended or been stopped.

Assess the timeout period of the lifecycle hook to make sure that the O&M tasks specified in the OOS template can be complete within the allotted time limit.

References

To run scripts on existing ECS instances in a scaling group, use the rolling update feature. For more information, see the following topics: