If you want to perform system configurations or run specific business scripts when you create an ECS instance, such as pre-installing software like Nginx and Docker or modifying the hostname, use the User Data parameter.
Custom Data Overview
User data consists of scripts, instructions, or configuration files that you can upload to an instance to perform initialization or configuration tasks. For example, when an instance starts for the first time, it can automatically run service startup scripts, install software, or print logs. User data runs automatically when an instance is first started. Some user data formats also support execution every time a Linux instance starts. For more information, see User data formats and running frequencies.
Limits
The instance must be in a virtual private cloud (VPC).
The instance must use a public image or a custom image created from a public image. The operating system must be one of the following:
Alibaba Cloud Linux, CentOS, CentOS Stream, Ubuntu, SUSE Linux Enterprise Server, Red Hat Enterprise Linux, OpenSUSE, Debian, AlmaLinux, Rocky Linux, or Fedora
Windows Server 2008 R2 or later
Among retired instance types, only I/O optimized instances support the user data feature. This feature is not supported on non-I/O optimized instances. For more information, see Retired instance types.
Use user data when you create an instance
1. Prepare custom data
During instance initialization, an initialization tool reads the user data that you provide to perform custom configurations. Linux and Windows instances use different initialization tools. These tools can support multiple user data formats. For more information about the data formats and their running frequencies, see the following sections.
Custom Data Format and Execution Frequency
Linux instances
Linux instances use the cloud-init component to perform initialization actions. Different configurations are run depending on whether the instance is starting for the first time. Some instances that use earlier image versions also use Upstart Job for initialization.
The cloud-init tool supports user data types that can directly configure instances, such as User-Data and Cloud Config formats. It also supports other user data formats. The most common formats are include files and Gzip compressed content. In addition to the cloud-init tool, some instances that use earlier image versions also use Upstart Job for initialization.
For more information about user data formats, see User-Data Formats in the cloud-init documentation.
If the size of your User-Data script, Cloud Config data, or Include file exceeds 32 KB, select Gzip compressed content as the data type.
If a task needs to run every time the instance starts, select Cloud Config data or Upstart Job as the data type.
User-Data scripts
Overview
When a User-Data script is passed to a Linux instance, it is run as a shell script. The script runs only once when the instance is first started.
Running frequency
Start instance: Runs only once when the instance is first started. The script does not run again when the instance is restarted.
Replace operating system: Runs automatically.
Re-initialize system disk: Runs automatically.
ImportantThe script does not automatically run in the following cases:
If you use a custom image that is created from the source instance to replace the operating system, the system determines that the instance is not starting for the first time and does not run the script.
If you use a custom image to create an instance, the system disk of the instance already contains data. When you initialize the system disk, the system determines that the instance is not starting for the first time and does not run the script.
Format
The first line must start with a shebang (
#!).Sample User-Data scripts
Run a custom script
#!/bin/sh echo "Hello World. The time is now $(date -R)!" | tee /root/userdata_test.txtThis sample User-Data script writes the system time to the userdata_test.txt file when the instance is first started.
Customize software sources, DNS configurations, and time synchronization services
When you create an instance, you can use a User-Data script to customize the software sources, DNS configurations, and time synchronization services for the instance. The following example uses CentOS Stream 9. Replace the configurations with those appropriate for your operating system.
ImportantThe system automatically configures the default yum repository, Network Time Protocol (NTP) service, and DNS service when an instance starts. You can use user data to change the default yum repository, NTP service, and DNS service. Note the following:
If you customize the yum repository, Alibaba Cloud no longer provides support for the yum repository.
If you customize the NTP service, Alibaba Cloud no longer provides time synchronization services.
#!/bin/sh # Modify DNS echo "nameserver 114.114.114.114" | tee /etc/resolv.conf # Modify yum repo and update cp /etc/yum.repos.d/centos.repo /etc/yum.repos.d/centos.repo.bak cp /etc/yum.repos.d/centos-addons.repo /etc/yum.repos.d/centos-addons.repo.bak sed -i "s@http://mirrors.cloud.aliyuncs.com/centos-stream/@https://mirror.stream.centos.org/@g" /etc/yum.repos.d/centos.repo sed -i "s@http://mirrors.cloud.aliyuncs.com/centos-stream/@https://mirror.stream.centos.org/@g" /etc/yum.repos.d/centos-addons.repo yum update -y # Modify NTP Server echo "server ntp1.aliyun.com" | tee /etc/ntp.conf systemctl restart ntpd.serviceNoteIn the preceding code,
114.114.114.114is the DNS server address,https://mirror.stream.centos.orgis the yum repository address for CentOS Stream, andserver ntp1.aliyun.comis the NTP server address for Alibaba Cloud. Replace them as needed.You can also use Cloud Config data to change the yum repository. However, this method is less flexible and cannot adapt to cases where Alibaba Cloud has pre-configured some yum repositories. We recommend that you use a User-Data script.
Customize the administrator account
By default, Linux instances use the root user as the administrator. You can use user data to specify another user as the administrator.
#!/bin/sh useradd test-user echo "test-user ALL=(ALL) NOPASSWD:ALL" | tee -a /etc/sudoers mkdir /home/test-user/.ssh touch /home/test-user/.ssh/authorized_keys echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCRnnUveAis****" | tee -a /home/test-user/.ssh/authorized_keysNoteReplace the sample public key ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCRnnUveAis**** with your actual public key.
If an issue occurs while a User-Data script is running, you can run the common Cloud Assistant command ACS-ECS-UserData-Check-for-linux.sh to obtain the error logs. If an error message is returned, the script failed to run. If no error message is returned, the script ran without errors, and you must investigate other potential issues. For more information about common Cloud Assistant commands, see View and run public commands.
Cloud Config data
Overview
Cloud-init uses a series of functional modules to perform tasks such as installing software packages and setting up networks. The modules to run and their logic are determined by Cloud Config data, which can be retrieved from vendor data, user data, or kernel parameters. When you create an ECS instance, you can customize the Cloud Config data to specify which modules and tasks to run. When the instance starts, cloud-init reads and parses the Cloud Config data, runs the corresponding modules, and performs the specified configuration tasks to automatically configure and deploy the ECS instance.
Running frequency
Start instance: Whether tasks in Cloud Config data run depends on the frequency settings of their corresponding modules. For more information about the modules, see Modules.
Frequency is once-per-instance: Runs only when the instance is first started. For example, if you configure modules such as Apt and Set Passwords, the frequency is once-per-instance, and they do not run when the instance is restarted.
Frequency is always: Runs every time the instance starts. For example, if you configure modules such as Bootcmd and Update Etc Hosts, the frequency is always, and they run every time the instance starts.
Replace operating system: Runs automatically.
Re-initialize system disk: Runs automatically.
ImportantThe script does not automatically run in the following cases:
If you use a custom image that is created from the source instance to replace the operating system, the system determines that the instance is not starting for the first time and does not run the script.
If you use a custom image to create an instance, the system disk of the instance already contains data. When you initialize the system disk, the system determines that the instance is not starting for the first time and does not run the script.
Format
The first line must be
#cloud-config, with no spaces before it.The content must be written in YAML syntax.
Sample Cloud Config data
Customize instance software sources
In the User Data section, enter the following content to configure custom instance software sources. The example uses an Ubuntu image to create the instance. If you use a different image, replace the configuration with the content for the appropriate module.
#cloud-config apt: preserve_sources_list: false disable_suites: - $RELEASE-updates - backports - $RELEASE - mysuite primary: - arches: - amd64 - i386 - default uri: http://us.archive.ubuntu.com/ubuntuConfigure the automatic installation of the Nginx service
In the User Data section, enter the following content to configure the instance to automatically install the Nginx service.
#cloud-config packages: - nginx runcmd: - systemctl start nginx.serviceConfigure a custom hostname
In the User Data section, enter the following content to set a custom hostname.
#cloud-config hostname: my-instance fqdn: my-instance.localdomainConfigure a custom script to run automatically
In the User Data section, enter the following content to configure a shell script to run automatically every time the instance starts.
#cloud-config bootcmd: - echo "Hello World. The time is now $(date -R)!" | tee /root/userdata_test.txt
Include files
Overview
An Include file contains links to one or more User-Data scripts or Cloud Config data files. Separate multiple links with newlines. When an instance starts, cloud-init parses and reads the content of each link sequentially. If an error occurs while reading the content of a link, cloud-init stops reading the remaining links.
NoteYou can use Alibaba Cloud Object Storage Service (OSS) to upload User-Data scripts or Cloud Config data, retrieve links, and set the validity period of the links. For more information, see Getting Started with the OSS console.
Running frequency
Start instance: The running frequency is determined by the content of the link. For example, if the link content is a User-Data script, it runs only once when the instance is first started. If the link content is Cloud Config data, it follows the running frequency of Cloud Config data.
Replace operating system: Runs automatically.
Re-initialize system disk: Runs automatically.
ImportantThe script does not automatically run in the following cases:
If you use a custom image that is created from the source instance to replace the operating system, the system determines that the instance is not starting for the first time and does not run the script.
If you use a custom image to create an instance, the system disk of the instance already contains data. When you initialize the system disk, the system determines that the instance is not starting for the first time and does not run the script.
Format
The first line must be
#include, with no spaces before it.Sample Include file
#include https://ecs-image-test.oss-cn-hangzhou.aliyuncs.com/userdata/myscript.shThe sample Include file contains a link to a script. The script is a User-Data script, so it runs only once when the instance is first started.
NoteIf you use an Include file or Gzip compressed content, you must use a storage service to upload the script, retrieve the script link, and set the validity period of the link. We recommend that you use Alibaba Cloud OSS. For more information, see Getting Started with the OSS console.
Gzip compressed content
Overview
If the size of your User-Data script, Cloud Config data, or Include file exceeds 32 KB, you can use Gzip compressed content (in the
.gzformat). Create a link to the compressed content and enter the link in an Include file. cloud-init automatically decompresses the Gzip content. The effect of running the decompressed content is the same as passing and running the original content directly.NoteYou can use Alibaba Cloud OSS to upload User-Data scripts or Cloud Config data, retrieve links, and set the validity period of the links. For more information, see Getting Started with the OSS console.
Running frequency
Start instance: Determined by the script type and module type. For example, if the link to the Gzip compressed content is for a User-Data script, it runs only once when the instance is first started.
Replace operating system: Runs automatically.
Re-initialize system disk: Runs automatically.
ImportantThe script does not automatically run in the following cases:
If you use a custom image that is created from the source instance to replace the operating system, the system determines that the instance is not starting for the first time and does not run the script.
If you use a custom image to create an instance, the system disk of the instance already contains data. When you initialize the system disk, the system determines that the instance is not starting for the first time and does not run the script.
Format
The first line must be
#include, with no spaces before it.Sample Gzip-compressed content
#include https://ecs-image-test.oss-cn-hangzhou.aliyuncs.com/userdata/myscript.gzThis example shows an Include file that contains a link to Gzip compressed content. After cloud-init reads the Gzip compressed content, it automatically decompresses and runs it. The Gzip content is a compressed User-Data script, which runs only once when the instance is first started.
Upstart Job
To use Upstart Job, you must install the upstart service on the instance. Operating systems that support using the upstart service to manage startup behavior include CentOS 6, Ubuntu 10/12/14, and Debian 6/7.
Overview
Upstart is an event-driven initialization system. An Upstart Job is a configuration file that defines when a service or task starts, stops, and how it runs. It is usually placed in the /etc/init/ directory with a .conf file name extension.
Running frequency
Start instance: Runs automatically every time the instance starts.
Replace operating system: Runs automatically.
Re-initialize system disk: Runs automatically.
ImportantThe script does not automatically run in the following cases:
If you use a custom image that is created from the source instance to replace the operating system, the system determines that the instance is not starting for the first time and does not run the script.
If you use a custom image to create an instance, the system disk of the instance already contains data. When you initialize the system disk, the system determines that the instance is not starting for the first time and does not run the script.
Format
The first line must be
#upstart-job, with no spaces before it.Sample Upstart Job content
#upstart-job description "upstart test" start on runlevel [2345] # Executes at run levels 2, 3, 4, and 5 stop on runlevel [!2345] # Does not execute at run levels other than 2, 3, 4, and 5 exec echo "Hello World. The time is now $(date -R)!" | tee /root/output.txtThe sample Upstart Job outputs a message with a timestamp when the system enters the specified run levels and records the message in the
/root/output.txtfile. The job stops running when the system leaves these run levels.
MIME multi-part files
Overview
A MIME multi-part file can transmit multiple types of instructions. For example, you can use a MIME multi-part file to include both
text/cloud-config(for cloud-init configuration) andtext/x-shellscript(shell script) in the user data. Cloud-init parses and runs these different types of instructions separately.Running frequency
Start instance: Depends on the type of each part in the MIME message and the cloud-init configuration. For example, if the content type in the MIME message is a User-Data script, it runs only once when the instance is first started. If the content type is Cloud Config data, it follows the running frequency of Cloud Config data.
Replace operating system: Runs automatically.
Re-initialize system disk: Runs automatically.
ImportantThe script does not automatically run in the following cases:
If you use a custom image that is created from the source instance to replace the operating system, the system determines that the instance is not starting for the first time and does not run the script.
If you use a custom image to create an instance, the system disk of the instance already contains data. When you initialize the system disk, the system determines that the instance is not starting for the first time and does not run the script.
Format
The first line is
Content-Type: multipart/mixed; boundary="****". The boundary can be customized, and there must be no space at the beginning of the line.The second line specifies the version
MIME-Version: 1.0. This field is usually required in every MIME message.
Sample MIME multi-part file
Content-Type: multipart/mixed; boundary="//" MIME-Version: 1.0 --// Content-Type: text/cloud-config; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="cloud-config.txt" #cloud-config runcmd: - [ mkdir, /test-cloudinit ] write_files: - path: /test-cloudinit/cloud-init.txt content: | Created by cloud-init append: true --// Content-Type: text/x-shellscript; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="userdata.txt" #!/bin/bash mkdir test-userscript touch /test-userscript/userscript.txt echo "Created by bash shell script" >> /test-userscript/userscript.txt --//--The sample MIME multi-part file contains cloud-init instructions and a Bash shell script:
The cloud-init instructions create a file (
/test-cloudinit/cloud-init.txt) and writeCreated by cloud-initto it.The Bash shell script creates a file (
/test-userscript/userscript.txt) and writesCreated by bash shell scriptto it.
Windows instances
Windows instances run user data scripts using the Plugin_Main_CloudinitUserData plugin of the Vminit tool. This plugin supports running scripts only when the instance is first started. The plugin supports both Bat and PowerShell scripts.
Bat scripts
Running frequency
Start instance: Runs only once when the instance is first started. The script does not run again when the instance is restarted.
Replace operating system: Runs automatically.
Re-initialize system disk: Runs automatically.
ImportantThe script does not automatically run in the following cases:
If you use a custom image that is created from the source instance to replace the operating system, the system determines that the instance is not starting for the first time and does not run the script.
If you use a custom image to create an instance, the system disk of the instance already contains data. When you initialize the system disk, the system determines that the instance is not starting for the first time and does not run the script.
Format
The first line must be
[bat], with no spaces before it.Use only half-width characters. Do not enter extra characters.
Do not write data to the
C:\Usersdirectory. Otherwise, the user data fails to run.NoteIn Windows,
C:\Usersand its subdirectories are the default storage locations for user profiles and data, which can be accessed only after you log on to the system. User data is executed during system initialization before you log on. Therefore, any attempt to write data to theC:\Usersdirectory fails.
Sample Bat script
Run a custom script
[bat] echo "bat test" > C:\userdata_test.txtThis sample Bat script writes
"bat test"to the userdata_test.txt file when the instance is first started.
PowerShell scripts
Running frequency
Start instance: Runs only once when the instance is first started. The script does not run again when the instance is restarted.
Replace operating system: Runs automatically.
Re-initialize system disk: Runs automatically.
ImportantThe script does not automatically run in the following cases:
If you use a custom image that is created from the source instance to replace the operating system, the system determines that the instance is not starting for the first time and does not run the script.
If you use a custom image to create an instance, the system disk of the instance already contains data. When you initialize the system disk, the system determines that the instance is not starting for the first time and does not run the script.
Format
The first line must be
[powershell], with no spaces before it.Use only half-width characters. Do not enter extra characters.
Do not write data to the
C:\Usersdirectory. Otherwise, the user data fails to run.NoteIn Windows,
C:\Usersand its subdirectories are the default storage locations for user profiles and data, which can be accessed only after you log on to the system. User data is executed during system initialization before you log on. Therefore, any attempt to write data to theC:\Usersdirectory fails.
Sample PowerShell script
Run a custom script
[powershell] write-output "powershell test" | Out-File C:\userdata_test.txtThis sample PowerShell script writes
powershell testto the userdata_test.txt file when the instance is first started.
2. Use user data when you create an instance
Create an instance in the console
On the instance buy page, expand the Advanced Options section. In the User Data section, enter the user data.
ImportantIf your user data is already Base64-encoded, select The user data is Base64-encoded. The original, unencoded data must not exceed 32 KB. If you provide plain text, do not select this option. The system automatically encodes the content for you.
Create an instance by calling an API
If you create an instance by calling an API, specify the
UserDataparameter in the RunInstances or CreateInstance operation.
3. Verify that the user data is run as expected
You must verify that a custom script runs as expected based on its content. The following example shows how to verify the execution of a User-Data script passed to a Linux instance.
#!/bin/sh
echo "Hello World. The time is now $(date -R)!" | tee /root/userdata_test.txtIn this example, the User-Data script writes the system time to the userdata_test.txt file when the instance is first started. To verify the script execution, run the cat userdata_test.txt command to check the result. The system time is written to the userdata_test.txt file.

If an issue occurs while a User-Data script is running, you can run the common Cloud Assistant command ACS-ECS-UserData-Check-for-linux.sh to obtain the error logs. If an error message is returned, the script failed to run. If no error message is returned, the script ran without errors, and you must investigate other potential issues. For more information about common Cloud Assistant commands, see View and run public commands.
Other operations
View the user data of an existing instance
After user data is passed to an instance, you can view the user data using the metadata service or in the console.
Obtain user data from the metadata service (security-hardened mode)
Linux instance
TOKEN=`curl -X PUT "http://100.100.100.200/latest/api/token" -H "X-aliyun-ecs-metadata-token-ttl-seconds:180"` curl -H "X-aliyun-ecs-metadata-token: $TOKEN" http://100.100.100.200/latest/user-dataWindows instance
$token = Invoke-RestMethod -Headers @{"X-aliyun-ecs-metadata-token-ttl-seconds" = "180"} -Method PUT -Uri http://100.100.100.200/latest/api/token Invoke-RestMethod -Headers @{"X-aliyun-ecs-metadata-token" = $token} -Method GET -Uri http://100.100.100.200/latest/user-data
In the preceding examples, the validity period of the token is 180 seconds. You can adjust the validity period based on your scenario.
This example uses the security-hardened mode of the metadata service to retrieve metadata. For more information about how to retrieve information from the metadata service, see Instance metadata.
For more information about metadata, see Instance metadata.
Obtain from the console
Make sure that the instance is in the Stopped state.
ImportantIf the instance is pay-as-you-go and in a VPC, we recommend that you set Stop Mode to Standard Mode when you stop the instance. If you select Economical Mode, the compute resources (vCPU and memory) are released. As a result, the instance may fail to restart because of insufficient stock. For more information, see Economical mode.
Click the ID of the target instance to go to the instance details page. Click All Actions to expand the operations panel. Search for and click . Then, in the User Data section, view the configured user data.
Obtain by calling an API
You can call the DescribeUserData operation to query the user data of an ECS instance. For more information, see DescribeUserData.
Modify the user data of an existing instance
To modify the user data of an existing instance, perform the following operations in the console.
Make sure that the instance is in the Stopped state.
ImportantIf the instance is pay-as-you-go and in a VPC, we recommend that you set Stop Mode to Standard Mode when you stop the instance. If you select Economical Mode, the compute resources (vCPU and memory) are released. As a result, the instance may fail to restart because of insufficient stock. For more information, see Economical mode.
Click the ID of the target instance to go to the instance details page. Click All Actions to expand the operations panel. Search for and click . Then, in the User Data section, enter the user data.
After you modify the user data of an existing instance, whether the user data script runs after the instance starts depends on the user data format and running frequency. Clarify your requirements before you modify the user data. For more information, see User data formats and running frequencies.
References
You can also use the user data feature of Auto Scaling to allow multiple ECS instances to automatically run configured scripts or commands at startup. This ensures the consistency of ECS instance configurations and simplifies operations and maintenance (O&M). For more information, see Use instance user data to automatically configure ECS instances.
If you want a service or script to recover promptly when it is interrupted by a program exception, server restart, or power failure, use the
ecs-tool-servicekeepaliveCloud Assistant plugin. For more information, see Use a Cloud Assistant plugin to keep services alive.For more information about how to manage instance initialization, see Introduction to initialization tools.