All Products
Search
Document Center

Elastic Compute Service:Use Packer to create a custom image

Last Updated:Mar 07, 2024

Packer is a lightweight open source tool that can be used to create images. Packer runs on mainstream operating systems, such as Windows, Linux, and macOS, and can create virtual machine images for multiple platforms in a synchronous and efficient manner. This topic describes how to install Packer on an Elastic Compute Service (ECS) instance, define a Packer template, and use Packer to create a custom image.

Prerequisites

An AccessKey pair is created and obtained. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. For more information, see Obtain an AccessKey pair.

Note
  • To prevent leaks of the AccessKey pair of your Alibaba Cloud account, we recommend that you create a Resource Access Management (RAM) user and use the credentials of the RAM user to create an AccessKey pair. For information about how to create a RAM user, see Create a RAM user.

  • An AccessKey secret for a RAM user is displayed only when you create the AccessKey pair for the RAM user. You cannot query the AccessKey secret after the AccessKey pair is created. Record and keep your AccessKey secret confidential.

Background information

Packer consists of various components, such as Builders, Provisioners, and Post-Processors. Packer uses templates in the Hashicorp Configuration Language (HCL) or JSON format to simplify the process of creating custom images. In addition, Packer standardizes and automates the image creation process and allows you to define images as code to facilitate your cloud migration.

Procedure

Step 1: Install Packer

  1. Connect to a Linux instance.

  2. Run the following command to go to the /usr/local/bin directory:

    cd /usr/local/bin
    Note

    The /usr/local/bin directory is included in environment variables. You can install Packer in this directory or a different directory that is added to environment variables.

  3. Run the following command to obtain the Packer installation package.

    You can also go to the Install Packer page to obtain a Packer installation package that is suitable for the operating system and architecture of the Linux instance. In this example, the packer_1.8.5_linux_amd64.zip installation package is obtained.

    wget https://releases.hashicorp.com/packer/1.8.5/packer_1.8.5_linux_amd64.zip
  4. Run the following command to decompress the Packer installation package:

    unzip packer_1.8.5_linux_amd64.zip
  5. Run the following command to check whether Packer is installed and check the version of Packer:

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

    • If Packer is not properly installed, the command not found message is returned. Check whether the directory in which Packer resides is added to environment variables.

Step 2: Define a Packer template

To create a custom image by using Packer, create a template in the HCL or JSON format. In the template, specify a builder and a provisioner. For more information, see Builders and Provisioners. Packer provides various provisioners that you can use to create custom images. In this example, a Shell provisioner is used.

  1. Run the following command to import your AccessKey ID:

    export ALICLOUD_ACCESS_KEY=<AccessKey ID>

    In the preceding command, replace <AccessKey ID> with your AccessKey ID. For information about how to query the AccessKey ID of a RAM user, see View the information about AccessKey pairs of a RAM user.

  2. Run the following command to import your AccessKey secret:

    export ALICLOUD_SECRET_KEY=<AccessKey Secret>

    In the preceding command, replace <AccessKey Secret> with your AccessKey secret. The AccessKey secret of a RAM user is displayed only when you create the AccessKey pair for the RAM user. You cannot query the AccessKey secret after the AccessKey pair is created. For more information, see Create an AccessKey pair.

  3. Run the following command to create a file named alicloud.

    Note

    You can create the alicloud file in the HCL or JSON format. If you create the file in the HCL format, perform the subsequent operations that are suitable for a template in the HCL format.

    HCL file

    vi alicloud.pkr.hcl

    JSON file

    vi alicloud.json
  4. Press the I key to enter the Insert mode, configure the parameters in the following content based on your business requirements, and then paste the content to the alicloud file:

    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 parameters.

    Parameter

    Description

    region

    The region in which the temporary instance that is used to create the custom image resides. Example: cn-qingdao.

    image_name

    The name of the custom image. Example: packer_basic.

    source_image

    The name of the base image that is used to create the temporary instance. You can obtain the name of the base image from the public image list in the ECS console or by calling the DescribeImages operation.

    Important

    Make sure that the base image that you select supports the instance type that you specify to create the temporary instance. For example, if the base image is an Arm image whose ID contains _arm64_, you must specify an Arm-based instance. Otherwise, the custom image cannot be created.

    instance_type

    The instance type of the temporary instance that is used to create the custom image. Example: ecs.g6.large. After the custom image is created, the temporary instance is automatically released.

    Note

    When Packer creates the custom image, the CreateInstance operation is called to create a temporary instance. The instance contains the operating system and software that are required to create the custom image. The temporary instance is a pay-as-you-go instance. You are charged for the instance.

    internet_charge_type

    The billing method for network usage of the temporary instance that is used to create the custom image. Valid values:

    • PayByBandwidth

    • PayByTraffic

    provisioners

    The type of provisioner that is used to create the custom image. Valid values:

    • File

    • PowerShell

    • Shell

    • Local Shell

    • Windows Shell

    For more information, see Provisioners.

  5. Press the Esc key, enter :wq, and then press the Enter key to save your changes and exit the Insert mode.

Step 3: Create a custom image by using Packer

To create a custom image by using the Packer template that you created, perform the following operations:

  1. Run the following command to create a custom image.

    HCL file

    packer build alicloud.pkr.hcl

    The following sample command output indicates that a custom image whose ID is m-m5e3f0gu2dxs4z0s**** is 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 sample command output indicates that a custom image whose ID is m-m5e3f0gu2dxs4z0s**** is 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. View the created custom image.

    1. Log on to the ECS console.

    2. In the left-side navigation pane, choose Instances & Images > Images.

    3. In the upper-left corner of the top navigation bar, select the region that is specified in the alicloud file. Example: China (Qingdao).

    4. On the Custom Images tab, view the custom image named packer_basic.