Use custom parameters in commands

更新时间:
复制 MD 格式

Cloud Assistant lets you use custom parameters, including user-defined and built-in environment parameters, to customize commands.

Prerequisites

  • The instance must be in the Running state.

  • The Cloud Assistant Agent is installed on the instance, and the agent version must be one of the following versions or newer.

    • Linux: 2.2.3.309

    • Windows: 2.1.3.309

Usage notes

Custom parameters: You can define parameters by using the {{parameter}} format and manually assign values. This is useful for dynamic or frequently reused values. You can also use built-in environment parameters as custom parameters. When you run a command, Cloud Assistant automatically replaces built-in environment parameters with their corresponding values from the environment. You do not need to assign values to these parameters. For more information about supported built-in environment parameters, see Built-in environment parameters.

  • Using custom parameters when calling an API.

    When you call the RunCommand or InvokeCommand operation to run a Cloud Assistant command, you can enable custom parameters by setting EnableParameter=true. Then, you can define custom parameters in the CommandContent parameter by using the {{}} format. The following limits apply:

    • For user-defined parameters: A parameter name can contain only letters, digits, hyphens (-), and underscores (_), and is case-insensitive. The name cannot exceed 64 bytes.

    • For built-in environment parameters: The acs:: prefix is reserved for built-in environment parameters. You cannot use this prefix for user-defined parameter names.

    • Spaces and line breaks before and after a parameter name within {{}} are ignored.

    • A command can contain a maximum of 20 custom parameters, including user-defined and built-in environment parameters.

Use custom parameters

Using custom parameters in Cloud Assistant commands makes scripts more flexible and reusable. For example, if you have a scheduled script that runs on a Linux instance, you can use a custom parameter to dynamically set its execution frequency.

import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.RunCommandRequest;
import com.aliyun.teaopenapi.models.Config;

import java.util.Collections;
import java.util.List;


public class EcsService {

    /**
     * Obtain the AccessKey ID and AccessKey secret from environment variables.
     */
    private static final String ACCESS_KEY_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private static final String ACCESS_KEY_SECRET = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");

    public static void main(String[] args_) throws Exception {
        // The region ID.
        String regionId = "cn-hangzhou";
        Config config = new Config()
                .setAccessKeyId(ACCESS_KEY_ID)
                .setAccessKeySecret(ACCESS_KEY_SECRET)
                .setRegionId(regionId);
        Client ecsClient = new Client(config);
        List<String> instanceIds = Collections.singletonList("i-bp1h23xufsi8XXXXXXXX");
        // The content of the command to run. Replace /path/to/your/script.sh with the script to run.
        String commandContent = "#!/bin/bash\n " +
                "(crontab -l 2>/dev/null; echo \"{{cron}} /path/to/your/script.sh\") | crontab -";
        // The command execution timeout period in seconds.
        long commandTimeOut = 60;
        RunCommandRequest request = new RunCommandRequest();
        request.setRegionId(regionId);
        request.setType("RunShellScript");
        // Enable the custom parameter feature.
        request.setEnableParameter(true);
        // Set the value of the custom parameter cron.
        request.setParameters(Collections.singletonMap("cron", "0 2 * * *"));
        request.setCommandContent(commandContent);
        request.setInstanceId(instanceIds);
        request.setTimeout(commandTimeOut);
        ecsClient.runCommand(request);
    }
}
import json
import os

from alibabacloud_ecs20140526 import models as ecs_20140526_models
from alibabacloud_ecs20140526.client import Client as Ecs20140526Client
from alibabacloud_tea_openapi import models as open_api_models

ACCESS_KEY_ID = os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
ACCESS_KEY_SECRET = os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")


def get_ecs_client(region_id):
    config = open_api_models.Config(
        access_key_id=ACCESS_KEY_ID,
        access_key_secret=ACCESS_KEY_SECRET,
        region_id=region_id
    )
    return Ecs20140526Client(config)


def main():
    # The region ID.
    region_id = "cn-hangzhou"
    client = get_ecs_client(region_id)
    # The ID of the ECS instance on which the command is to be run.
    instance_ids = ["i-bp1h23xufsi8XXXXXXXX"]
    # The content of the command to run. Replace /path/to/your/script.sh with the script to run.
    command_content = "#!/bin/bash\n (crontab -l 2>/dev/null; echo \"{{cron}} /path/to/your/script.sh\") | crontab -"
    # The command execution timeout period in seconds.
    command_timeout = 60
    # The shell command for Linux instances: RunShellScript.
    command_type = "RunShellScript"

    # Run the command.
    request = ecs_20140526_models.RunCommandRequest()
    request.region_id = region_id
    request.type = command_type
    # Enable the custom parameter feature.
    request.enable_parameter = True
    # Set the value of the custom parameter.
    request.parameters = {"cron": "0 2 * * *"}
    request.command_content = command_content
    request.instance_id = instance_ids
    request.timeout = command_timeout
    response = client.run_command(request)
    print("execute_command result:", json.dumps(response.to_map()['body']))


if __name__ == "__main__":
    main()

Use OOS parameters

CloudOps Orchestration Service (OOS) provides a parameter store that supports standard and encrypted parameters. You can use the OOS parameter store with Cloud Assistant commands to manage custom parameters more conveniently and securely. To use the OOS parameter store, you must first activate OOS and grant the oos:GetParameter and oos:GetParameters permissions.

Use standard parameters

If your command does not involve sensitive data, you can use standard parameters. This section shows how to use a standard parameter from the OOS parameter store in a Cloud Assistant command to add a new user to a Linux instance.

  1. Create a standard parameter in the OOS parameter store. For more information, see Standard parameters.

    In this example, a standard parameter named username is created with the value user01.

    Parameter

    Example value

    Parameter

    username

    Parameter Type

    String

    Value

    user01

  2. Call an API to run the Cloud Assistant command.

    This example runs a Cloud Assistant command as a RAM user to create a new user on a Linux instance. The command is adduser {{oos:username}}. In this command, {{oos:username}} specifies the new username, which uses the value of the username standard parameter in the OOS parameter store.

    For a RAM user to run Cloud Assistant commands that contain OOS standard parameters, you must grant the RAM user the required permissions. For more information about the access policy, see Use OOS standard parameters in commands.
    import com.aliyun.ecs20140526.Client;
    import com.aliyun.ecs20140526.models.RunCommandRequest;
    import com.aliyun.ecs20140526.models.RunCommandResponse;
    import com.aliyun.teaopenapi.models.Config;
    import com.google.gson.Gson;
    
    import java.util.Arrays;
    import java.util.List;
    
    public class EcsService {
        public static void main(String[] args_) throws Exception {
            // The region ID.
            String regionId = "cn-hangzhou";
            Config config = new Config()
                    .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                    .setRegionId(regionId);
            Client ecsClient = new Client(config);
            RunCommandRequest request = new RunCommandRequest();
            request.setRegionId(regionId);
            request.setType("RunShellScript");
            // Enable the custom parameter feature.
            request.setEnableParameter(true);
            // The content of the command to run.
            String commandContent = "adduser {{oos:username}}";
            request.setCommandContent(commandContent);
            List<String> instanceIds = Arrays.asList("i-bp1h23xufsi8XXXXXXXX");
            request.setInstanceId(instanceIds);
            // The command execution timeout period in seconds.
            request.setTimeout(60L);
            RunCommandResponse response = ecsClient.runCommand(request);
            System.out.println(new Gson().toJson(response.getBody()));
        }
    }
    import json
    import os
    
    from alibabacloud_ecs20140526 import models as ecs_20140526_models
    from alibabacloud_ecs20140526.client import Client as Ecs20140526Client
    from alibabacloud_tea_openapi import models as open_api_models
    
    ACCESS_KEY_ID = os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
    ACCESS_KEY_SECRET = os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
    
    
    def get_ecs_client(region_id):
        config = open_api_models.Config(
            access_key_id=ACCESS_KEY_ID,
            access_key_secret=ACCESS_KEY_SECRET,
            region_id=region_id
        )
        return Ecs20140526Client(config)
    
    
    def main():
        # The region ID.
        region_id = "cn-hangzhou"
        client = get_ecs_client(region_id)
        # The ID of the ECS instance on which the command is to be run.
        instance_ids = ["i-bp1h23xufsi8XXXXXXXX"]
        # The content of the command to run.
        command_content = "adduser {{oos:username}}"
        # The command execution timeout period in seconds.
        command_timeout = 60
        # The shell command for Linux instances: RunShellScript.
        command_type = "RunShellScript"
    
        # Run the command.
        request = ecs_20140526_models.RunCommandRequest()
        request.region_id = region_id
        request.type = command_type
        # Enable the custom parameter feature.
        request.enable_parameter = True
        request.command_content = command_content
        request.instance_id = instance_ids
        request.timeout = command_timeout
        response = client.run_command(request)
        print("execute_command result:", json.dumps(response.to_map()['body']))
    
    
    if __name__ == "__main__":
        main()
    

Use encrypted parameters

For sensitive data, such as passwords, we recommend using encrypted parameters. This requires you to activate Key Management Service (KMS).

  1. Create an encrypted parameter and a standard parameter in the OOS parameter store.

    The following example creates a standard parameter named username and an encrypted parameter named password in the OOS parameter store.

    • Create a standard parameter named username with the value user01.

      Parameter

      Example value

      Parameter

      username

      Parameter Type

      String

      Value

      user01

    • Create an encrypted parameter named password with the value MyPassword01.

      Parameter

      Example value

      Parameter

      password

      KMS Key ID

      Default Service CMK

      The example value is a free service key generated by KMS. Select a key based on your business requirements.

      Value

      MyPassword01

      This password is for demonstration purposes only. Do not use it in a production environment.
  2. Attach a RAM role to the target ECS instance.

    1. Create a RAM role. For more information, see Create a RAM role for a trusted Alibaba Cloud service.

      The following table shows an example configuration.

      Parameter

      Example

      principal type

      Select Cloud Service.

      Principal name

      Elastic Compute Service / ECS.

      Click OK. Set Role Name to AxtParametersRamRole.

    2. Create a custom access policy for the RAM role. For more information, see Create a custom policy.

      Example access policy

      The policy name is AxtParametersRamPolicy, which allows you to call relevant APIs of Key Management Service (KMS) and Operation Orchestration Service (OOS) (GetSecretValue, GetParameters, GetSecretParameters, GetParameter, and GetSecretParameter).

      {
          "Version": "1",
          "Statement": [
              {
                  "Action": [
                      "kms:GetSecretValue",
                      "oos:GetParameters",
                      "oos:GetSecretParameters",
                      "oos:GetParameter",
                      "oos:GetSecretParameter"
                  ],
                  "Resource": "*",
                  "Effect": "Allow"
              }
          ]
      }
    3. Attach the AxtParametersRamPolicy policy to the AxtParametersRamRole RAM role. For more information, see Grant permissions to a RAM role.

    4. Attach the AxtParametersRamRole RAM role to the target ECS instance. For more information, see Attach an instance RAM role.

  3. Call an API to run the Cloud Assistant command.

    This example runs a Cloud Assistant command as a RAM user to change a user's password on a Linux instance.

    For a RAM user to run Cloud Assistant commands that contain OOS encrypted parameters, you must grant the RAM user the required permissions. For more information about the access policy, see Use OOS encrypted parameters in commands.
     echo '{{oos-secret:password}}' | passwd '{{oos:username}}' --stdin

    {{oos-secret:password}} specifies the new password, which uses the value of the password encrypted parameter in the OOS parameter store. {{oos:username}} specifies the username, which uses the value of the username standard parameter in the OOS parameter store.

    The passwd --stdin command in this example applies to Red Hat-based operating systems, such as CentOS and Alibaba Cloud Linux. If you use an Ubuntu or Debian system, run the echo '{{oos:username}}:{{oos-secret:password}}' | chpasswd command.
    import com.aliyun.ecs20140526.Client;
    import com.aliyun.ecs20140526.models.RunCommandRequest;
    import com.aliyun.ecs20140526.models.RunCommandResponse;
    import com.aliyun.teaopenapi.models.Config;
    import com.google.gson.Gson;
    
    import java.util.Arrays;
    import java.util.List;
    
    public class EcsService {
        public static void main(String[] args_) throws Exception {
            // The region ID.
            String regionId = "cn-hangzhou";
            Config config = new Config()
                    .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                    .setRegionId(regionId);
            Client ecsClient = new Client(config);
            RunCommandRequest request = new RunCommandRequest();
            request.setRegionId(regionId);
            request.setType("RunShellScript");
            // Enable the custom parameter feature.
            request.setEnableParameter(true);
            // The content of the command to run.
            String commandContent = "echo '{{oos-secret:password}}' | passwd '{{oos:username}}' --stdin";
            request.setCommandContent(commandContent);
            List<String> instanceIds = Arrays.asList("i-bp1h23xufsi8XXXXXXXX");
            request.setInstanceId(instanceIds);
            // The command execution timeout period in seconds.
            request.setTimeout(60L);
            RunCommandResponse response = ecsClient.runCommand(request);
            System.out.println(new Gson().toJson(response.getBody()));
        }
    }
    import json
    import os
    
    from alibabacloud_ecs20140526 import models as ecs_20140526_models
    from alibabacloud_ecs20140526.client import Client as Ecs20140526Client
    from alibabacloud_tea_openapi import models as open_api_models
    
    ACCESS_KEY_ID = os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
    ACCESS_KEY_SECRET = os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
    
    
    def get_ecs_client(region_id):
        config = open_api_models.Config(
            access_key_id=ACCESS_KEY_ID,
            access_key_secret=ACCESS_KEY_SECRET,
            region_id=region_id
        )
        return Ecs20140526Client(config)
    
    
    def main():
        # The region ID.
        region_id = "cn-hangzhou"
        client = get_ecs_client(region_id)
        # The ID of the ECS instance on which the command is to be run.
        instance_ids = ["i-bp1h23xufsi8XXXXXXXX"]
        # The content of the command to run.
        command_content = "echo '{{oos-secret:password}}' | passwd '{{oos:username}}' --stdin"
        # The command execution timeout period in seconds.
        command_timeout = 60
        # The shell command for Linux instances: RunShellScript.
        command_type = "RunShellScript"
    
        # Run the command.
        request = ecs_20140526_models.RunCommandRequest()
        request.region_id = region_id
        request.type = command_type
        # Enable the custom parameter feature.
        request.enable_parameter = True
        request.command_content = command_content
        request.instance_id = instance_ids
        request.timeout = command_timeout
        response = client.run_command(request)
        print("execute_command result:", json.dumps(response.to_map()['body']))
    
    
    if __name__ == "__main__":
        main()
    

Built-in environment parameters

You can use built-in environment parameters as custom parameters. You do not need to assign values to them because Cloud Assistant automatically replaces them with their corresponding values when the command runs.

Built-in environment parameter

Description

{{ACS::RegionId}}

The region ID.

{{ACS::AccountId}}

The ID of the Alibaba Cloud account.

{{ACS::InstanceId}}

The instance ID.

{{ACS::InstanceName}}

The instance name. If you run a command on multiple instances and want to specify {{ACS::InstanceName}} as a built-in environment parameter, make sure that the Cloud Assistant Agent version is one of the following versions or newer:

  • Linux: 2.2.3.344

  • Windows: 2.1.3.344

{{ACS::InvokeId}}

The command execution ID.

{{ACS::CommandId}}

The command ID.