All Products
Search
Document Center

Elastic Compute Service:Create a custom image with Packer

Last Updated:Apr 27, 2026

Install Packer on an ECS instance, define an HCL or JSON template, and build a custom image for batch deployment.

Prerequisites

An AccessKey pair (AccessKey ID and AccessKey secret) is obtained. See Obtain an AccessKey pair.

Note
  • To prevent AccessKey leaks, create a RAM user and use the RAM user's credentials. See Create a RAM user.

  • The AccessKey secret is displayed only when the AccessKey pair is created. Record and keep it confidential.

Background

Packer uses Builders, Provisioners, and Post-Processors to turn HCL or JSON templates into custom images, replacing manual image creation with configuration as code. See the Packer documentation for details.

Procedure

Step 1: Install Packer

  1. Connect to a Linux instance.

  2. Navigate to /usr/local/bin:

    cd /usr/local/bin
    Note

    /usr/local/bin is in the system PATH. You can also install Packer in any other directory already in the PATH.

  3. Download the Packer installation package.

    You can also visit the Install Packer page to download the package for your OS and architecture. This example uses packer_1.8.5_linux_amd64.zip.

    wget https://releases.hashicorp.com/packer/1.8.5/packer_1.8.5_linux_amd64.zip
  4. Unzip the package:

    unzip packer_1.8.5_linux_amd64.zip
  5. Verify the installation.

    packer -v
    • If a version number is returned, Packer is installed.

    • If command not found is returned, Packer is not installed correctly. Ensure the Packer directory is in your system PATH.

Step 2: Define a Packer template

Create an HCL or JSON template that specifies Builders and Provisioners. This example uses the Shell provisioner.

  1. Export your AccessKey ID.

    export ALICLOUD_ACCESS_KEY=<AccessKey ID>

    Replace <AccessKey ID> with your actual AccessKey ID. See View the information about AccessKey pairs of a RAM user.

  2. Export your AccessKey secret.

    export ALICLOUD_SECRET_KEY=<AccessKey Secret>

    Replace <AccessKey Secret> with your actual AccessKey secret. The AccessKey secret is displayed only at creation time and cannot be retrieved later. See Obtain an AccessKey pair.

  3. Create a file named alicloud.

    Note

    You can use either format to create the alicloud file. If you create an HCL file, use the HCL examples and commands in subsequent steps.

    HCL file

    vi alicloud.pkr.hcl

    JSON file

    vi alicloud.json
  4. Press I to enter Insert mode. Copy one of the following templates into the alicloud file and modify the parameters as needed.

    HCL file

    variable "access_key" {
      type    = string
      default = "${env("ALICLOUD_ACCESS_KEY")}"
    }
    
    variable "secret_key" {
      type    = string
      default = "${env("ALICLOUD_SECRET_KEY")}"
    }
    
    source "alicloud-ecs" "autogenerated_1" {
      associate_public_ip_address = true
      image_name                  = "packer_basic"
      instance_type               = "ecs.g6.large"
      internet_charge_type        = "PayByTraffic"
      io_optimized                = true
      region                      = "cn-qingdao"
      skip_image_validation       = true
      source_image                = "aliyun_3_x64_20G_alibase_20220907.vhd"
      ssh_username                = "root"
    }
    
    build {
      sources = ["source.alicloud-ecs.autogenerated_1"]
      provisioner "shell" {
        inline = ["sleep 30", "yum install redis.x86_64 -y"]
      }
    }

    JSON file

    {
         "variables": {
           "access_key": "{{env `ALICLOUD_ACCESS_KEY`}}",
           "secret_key": "{{env `ALICLOUD_SECRET_KEY`}}"
         },
         "builders": [{
           "type":"alicloud-ecs",
           "region":"cn-qingdao",
           "image_name":"packer_basic",
           "source_image":"aliyun_3_x64_20G_alibase_20220907.vhd",
           "associate_public_ip_address":true,
           "ssh_username":"root",
           "instance_type":"ecs.g6.large",
           "internet_charge_type":"PayByTraffic",
           "io_optimized":true,
           "skip_image_validation":true
         }],
         "provisioners": [{
           "type": "shell",
           "inline": [
             "sleep 30",
             "yum install redis.x86_64 -y"
           ]
         }]
       }

    The following table describes the supported parameters. See the Packer documentation for the full parameter reference.

    Parameter

    Type

    Required

    Description

    region

    string

    Yes

    The region of the temporary ECS instance used to create the custom image. Example: cn-qingdao.

    image_name

    string

    Yes

    The custom image name. Example: packer_basic.

    instance_type

    string

    Yes

    The instance type of the temporary ECS instance. Example: ecs.g6.large. The temporary instance is automatically released after image creation.

    Note

    Packer calls the CreateInstance operation to create a temporary pay-as-you-go ECS instance with the required operating system and software. This instance incurs fees.

    ssh_username

    string

    Yes

    The SSH username for connecting to the temporary ECS instance.

    internet_charge_type

    string

    No

    The network billing method for the temporary ECS instance. Valid values:

    • PayByBandwidth: pay-by-bandwidth.

    • PayByTraffic: pay-by-traffic.

    source_image

    string

    You must specify one of the parameters.

    The ID of the base image for the temporary ECS instance. Obtain the ID from the ECS console public image list or by calling the DescribeImages operation.

    Important

    The selected image type must be compatible with the specified instance type. For example, an Arm image (whose ID contains _arm64_) must be used with an Arm-based instance type. Otherwise, the build fails.

    image_family

    string

    The image family name. Packer uses the latest available image from this family to create the instance.

    Note

    The name must be 2 to 128 characters in length. The name cannot start with a digit, a special character, http://, or https://. The name can contain letters, digits, periods (.), underscores (_), hyphens (-), and colons (:).

    target_image_family

    string

    No

    The image family of the custom image to be created.

    Note

    The name must be 2 to 128 characters in length. The name cannot start with a digit, a special character, http://, or https://. The name can contain letters, digits, periods (.), underscores (_), hyphens (-), and colons (:).

    ssh_private_ip

    boolean

    You must specify one of the parameters.

    Specifies whether to use a private SSH connection. Default value: false. Valid values:

    • false: A public IP address is assigned for internet connection.

    • true: No EIP or public IP address is assigned. The instance is connected over its private IP address.

    Note

    For private connections, the Packer host and the created instance must be in the same vSwitch.

    associate_public_ip_address

    boolean

    Specifies whether to assign a public IP address to the temporary ECS instance.

    eip_id

    string

    The ID of the EIP associated with the temporary ECS instance.

    skip_image_validation

    boolean

    No

    Specifies whether to skip image validation. Default value: false.

    system_disk_mapping

    object

    No

    The system disk configuration. Example:

    "system_disk_mapping": {
     "disk_name": "sysdisk",
     "disk_category": "cloud_essd",
     "disk_size": 40
    }

    See the Cloud disk configurations section.

    image_disk_mappings

    list

    No

    The data disk configuration in the custom image. Example:

    "image_disk_mappings": {
     "disk_name": "datadisk",
     "disk_snapshot_id": "s-bp1xxxxxx",
     "disk_device": "dev/xvdb"
    }

    See the Cloud disk configurations section.

    image_ignore_data_disks

    boolean

    No

    Specifies whether the created image includes data disk snapshots. Default value: false. Valid values:

    • false: The created image includes data disks.

    • true: The created image includes only the system disk.

    profile

    string

    No

    The Packer configuration file. If specified, configurations are preferentially loaded from this file.

    ram_role_name

    string

    No

    The RAM role name. Used to obtain a temporary AccessKey for the local RAM role to execute the Packer template.

    Note

    Applies only when Packer runs on an ECS instance with an attached RAM role.

    ram_role_arn

    string

    No

    The Alibaba Cloud Resource Name (ARN) of the RAM role. Used with ram_session_name to allow Account A to assume Account B's role for image creation.

    ram_session_name

    string

    No

    The RAM role session name. Used with ram_role_arn for cross-account image creation.

    ecs_ram_role_name

    string

    No

    The instance RAM role attached to the temporary ECS instance. Call the ListRoles operation to query available roles.

    ssh_keypair_name

    string

    No

    The SSH key pair name for connecting to the temporary ECS instance.

    ssh_private_key_file

    string

    No

    The private key file path of the SSH key pair for connecting to the temporary ECS instance.

    custom_endpoint_ecs

    string

    No

    The custom ECS endpoint.

    security_group_id

    string

    No

    The security group ID for the temporary ECS instance.

    security_group_name

    string

    No

    The security group name. If no security group ID is specified, Packer creates one with this name.

    vpc_id

    string

    No

    The VPC ID for the temporary ECS instance.

    vpc_name

    string

    No

    The VPC name. If vpc_id is not specified, Packer creates a VPC with this name.

    vswitch_id

    string

    No

    The vSwitch ID for the temporary ECS instance.

    vswitch_name

    string

    No

    The vSwitch name. If vswitch_id is not specified, Packer creates a vSwitch with this name.

    user_data

    string

    No

    The instance user data. Must be Base64-encoded, with raw data not exceeding 32 KB. See Customize initialization configurations for an instance for limits, format, and execution frequency.

    Note

    Encrypt sensitive data (passwords, private keys) before Base64 encoding, then decrypt inside the instance.

    user_data_file

    string

    No

    The user data file path for the temporary ECS instance.

    boot_mode

    string

    No

    The boot mode of the custom image. Valid values: BIOS, UEFI, and UEFI-Preferred.

    wait_snapshot_ready_timeout

    Integer

    No

    The snapshot timeout period. Default value: 3600. Unit: seconds.

    instance_name

    string

    No

    The temporary ECS instance name. Defaults to the InstanceId.

    Note

    The name must be 2 to 128 characters in length and can contain letters, digits, colons (:), underscores (_), periods (.), and hyphens (-).

    image_force_delete

    boolean

    No

    Specifies whether to delete an existing image with the same name before creating the new one. Default value: false. Valid values:

    • true: Deletes the existing same-name image, then creates the new image.

    • false: Does not delete the existing same-name image. Image creation fails.

    image_force_delete_snapshots

    boolean

    No

    Specifies whether to delete snapshots of an existing same-name image. Default value: false. Valid values:

    • true: Deletes the existing same-name image and its snapshots, then creates the new image.

    • false: Does not delete the existing same-name image or its snapshots. Image creation fails.

    image_version

    string

    No

    The custom image version.

    resource_group_id

    string

    No

    The resource group ID for the custom image.

    force_stop_instance

    boolean

    No

    Specifies whether to force stop the temporary ECS instance. Default value: false.

    disable_stop_instance

    boolean

    No

    Specifies whether to skip stopping the instance after the provisioner runs. Set to true when the instance must remain running, such as when running Sysprep on Windows. Default value: false.

    run_tags

    object

    No

    The tags for the custom image. Example: {"key":"value"}.

    image_description

    string

    No

    The custom image description.

    image_share_account

    []string

    No

    The accounts to share the custom image with. Example: ["123456"].

    image_copy_regions

    []string

    No

    The regions to copy the custom image to. Example: ["cn-beijing"].

    provisioners

    string

    No

    The provisioner type. Valid values:

    • File

    • PowerShell

    • Shell

    • Local Shell

    • Windows Shell

    See Provisioners.

    Cloud disk configurations

    Parameter

    Type

    Required

    Description

    disk_name

    string

    No

    The cloud disk name.

    Note

    The name must be 2 to 128 characters in length and can contain letters, digits, colons (:), underscores (_), periods (.), and hyphens (-).

    disk_category

    string

    No

    The cloud disk category. Valid values:

    • cloud_efficiency: ultra disk

    • cloud_ssd: standard SSD

    • cloud_essd: Enterprise SSD (ESSD)

    • cloud: basic disk

    disk_size

    int

    No

    The cloud disk size. Unit: GiB. Must be at least 20 and no less than the image size. Default value: 40 or the image size, whichever is greater.

    disk_description

    string

    No

    The cloud disk description. Empty by default.

    Note

    The description must be 2 to 256 characters in length and cannot start with http:// or https://.

    disk_snapshot_id

    string

    No

    The snapshot ID to use for creating the data disk.

    disk_delete_with_instance

    boolean

    No

    Specifies whether to release the data disk when the instance is released. Valid values:

    • true

    • false

    Default value: true.

    disk_device

    string

    No

    The data disk mount point.

    disk_encrypted

    boolean

    No

    Specifies whether to encrypt the data disk. Valid values:

    • true

    • false

    Default value: false.

  5. Press Esc, type :wq, and press Enter to save and exit.

Step 3: Use Packer to create a custom image

Build a custom image from the Packer template.

  1. Create the custom image.

    HCL file

    packer build alicloud.pkr.hcl

    The following output shows that image m-m5e3f0gu2dxs4z0s**** was created in the China (Qingdao) region.

    alicloud-ecs.autogenerated_1: output will be in this color.
    
    ==> alicloud-ecs.autogenerated_1: Prevalidating source region and copied regions...
    ==> alicloud-ecs.autogenerated_1: Prevalidating image name...
        alicloud-ecs.autogenerated_1: Found image ID: aliyun_3_x64_20G_alibase_20220907.vhd
    ==> alicloud-ecs.autogenerated_1: Creating temporary keypair: packer_64bf3d40-2fe7-8251-276d-df59a0bb****
    ---------------------------
    ==> alicloud-ecs.autogenerated_1: Provisioning with shell script: /tmp/packer-shell3356722207
        alicloud-ecs.autogenerated_1: Last metadata expiration check: 0:00:11 ago on Tue 25 Jul 2023 11:12:18 AM CST.
    ---------------------------
        alicloud-ecs.autogenerated_1: Complete!
    ==> alicloud-ecs.autogenerated_1: Stopping instance: i-m5e87pt498pr8zv0****
    ==> alicloud-ecs.autogenerated_1: Waiting instance stopped: i-m5e87pt498pr8zv0****
    ==> alicloud-ecs.autogenerated_1: Creating image: packer_basic
        alicloud-ecs.autogenerated_1: Detach keypair packer_64bf3d40-2fe7-8251-276d-df59a0bb**** from instance: i-m5e87pt498pr8zv0****
    ==> alicloud-ecs.autogenerated_1: Cleaning up 'EIP'
    ==> alicloud-ecs.autogenerated_1: Cleaning up 'instance'
    ==> alicloud-ecs.autogenerated_1: Cleaning up 'security group'
    ==> alicloud-ecs.autogenerated_1: Cleaning up 'vSwitch'
    ==> alicloud-ecs.autogenerated_1: Cleaning up 'VPC'
    ==> alicloud-ecs.autogenerated_1: Deleting temporary keypair...
    Build 'alicloud-ecs.autogenerated_1' finished after 4 minutes 32 seconds.
    
    ==> Wait completed after 4 minutes 32 seconds
    
    ==> Builds finished. The artifacts of successful builds are:
    --> alicloud-ecs.autogenerated_1: Alicloud images were created:
    
    cn-qingdao: m-m5e3f0gu2dxs4z0s****

    JSON file

    packer build alicloud.json

    The following output shows that image m-m5e3f0gu2dxs4z0s**** was created in the China (Qingdao) region.

    alicloud-ecs output will be in this color.
    
    ==> alicloud-ecs: Prevalidating image name...
        alicloud-ecs: Found image ID: aliyun_3_x64_20G_alibase_20220907.vhd
    ==> alicloud-ecs: Creating temporary keypair: packer_6345090e-ec1f-8ea0-348c-f85ba047****
    ==> alicloud-ecs: Creating vpc
    ---------------------------
    ==> alicloud-ecs: Provisioning with shell script: /tmp/packer-shell090019677
        alicloud-ecs: Last metadata expiration check: 0:00:15 ago on Tue 11 Oct 2022 02:12:51 PM CST.
    ---------------------------
        alicloud-ecs: Complete!
    ==> alicloud-ecs: Deleting image snapshots.
    ==> alicloud-ecs: Creating image: packer_basic
        alicloud-ecs: Detach keypair packer_6345090e-ec1f-8ea0-348c-f85ba047**** from instance: i-m5e7it5p4dpwetfr****
    ==> alicloud-ecs: Cleaning up 'EIP'
    ==> alicloud-ecs: Cleaning up 'instance'
    ==> alicloud-ecs: Cleaning up 'security group'
    ==> alicloud-ecs: Cleaning up 'vSwitch'
    ==> alicloud-ecs: Cleaning up 'VPC'
    ==> alicloud-ecs: Deleting temporary keypair...
    Build 'alicloud-ecs' finished.
    
    ==> Builds finished. The artifacts of successful builds are:
    --> alicloud-ecs: Alicloud images were created:
    
    cn-qingdao: m-m5e3f0gu2dxs4z0s****
  2. Verify the custom image.

    1. Log in to the ECS console.

    2. In the left navigation bar, select Instances & Images > Image.

    3. In the top navigation bar, select the region specified in your template, such as China (Qingdao).

    4. On the Custom Images tab, find the image named packer_basic.