All Products
Search
Document Center

Elastic Compute Service:Instance user data

Last Updated:Jun 07, 2024

Instance user data refers to data uploaded to an instance, such as scripts, instructions, and configuration files. You can use instance user data to initialize or configure an instance. For example, the first time an instance is started, the instance automatically runs service startup scripts, installs software, and prints logs. This topic describes how to pass user data to Elastic Compute Service (ECS) instances, modify user data, and view user data.

The first time an instance is started, the instance automatically runs user data. User data in specific formats can also be run each time a Linux instance is started. For more information, see the Formats and running frequencies of user data section of this topic.

Limits

  • The instances must be deployed in virtual private clouds (VPCs).

  • The instances must be created from public images of the following operating systems or custom images that are derived from the public images:

    • Alibaba Cloud Linux, CentOS, CentOS Stream, Ubuntu, SUSE Linux Enterprise Server, Red Hat Enterprise Linux, openSUSE, Debian, AlmaLinux, Rocky Linux, and Fedora

    • Windows Server 2008 R2 or later

  • For retired instance types, I/O optimized instances support user data and non-I/O optimized instances do not support user data. For more information, see Retired instance types.

Use instance user data

Pass user data to an ECS instance

  1. Prepare user data.

    For information about the supported formats, running frequencies, and descriptions of user data, see the Formats and running frequencies of user data section of this topic.

    Important

    Before user data is encoded in Base64, the user data can only be up to 32 KB in size.

  2. Pass user data to an ECS instance.

    • If you pass user data when you create an instance, the user data is run the first time the instance is started, when the operating system running on the instance is changed, or when the system disk attached to the instance is re-initialized.

    • If you modify user data on an existing instance, the new user data is run when you change the operating system running on the instance or re-initialize the system disk attached to the instance.

      User data in specific formats can be run each time a Linux instance is started. For more information, see the Formats and running frequencies of user data section of this topic.

  3. Pass user data when you create an instance

    On the Custom Launch tab of the ECS instance buy page, click the Advanced Settings(Optional) section. In the User Data field, enter the user data of the instance.

    If you select Enter Base64 Encoded Information, make sure that the user data is encoded in Base64 and does not exceed 32 KB in size before the Base64 encoding. If you do no select Enter Base64 Encoded Information, the system automatically encodes the user data in Base64.

    Modify the user data of an existing instance

    1. Make sure that the instance is in the Stopped state.

      Important

      If the instance is billed by using the pay-as-you-go billing method and resides in a VPC, we recommend that you select Standard Mode in the Stop Mode section when you stop the instance. If you select Economical Mode, the computing resources (vCPUs and memory) of the instance are recycled. As a result, the instance may fail to be restarted due to insufficient resources. For more information, see Economical mode.

    2. On the Instance page, choose icon1 > Instance Settings > Set User Data. In the Set User Data dialog box, enter user data in the User Data field. Then, click Confirm.

  4. Check whether the user data is run as expected.

    Note

    If an issue occurs when a user-data script is run, you can run the following common Cloud Assistant command to obtain the error logs: ACS-ECS-UserData-Check-for-linux.sh. If an error message appears in the logs, an error occurred when the script was run. If no error message appears in the logs, no error occurred when the script was run. Check the script from other aspects to identify the cause of the issue. For information about common Cloud Assistant commands, see View and run common commands.

    For example, the following user-data script is passed to a Linux instance:

    #!/bin/sh
    echo "Hello World. The time is now $(date -R)!" | tee /root/userdata_test.txt

    Run the cat userdata_test.txt command to check whether the script is run as expected. The following command output shows that the system time is written to the userdata_test.txt file.

    view-result

View the user data of an instance

After user data is passed to an instance, you can view the user data in the metadata of the instance or in the ECS console.

View user data in the metadata (normal mode)

  • Linux instance

    curl http://100.100.100.200/latest/user-data
  • Windows instance

    Invoke-RestMethod http://100.100.100.200/latest/user-data

View user data in the metadata (security hardening mode)

For example, you set the validity period of credentials used to access a metadata server to 180 seconds.

  • 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-data
  • Windows 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

View user data in the ECS console

  1. Make sure that the instance is in the Stopped state.

    Important

    If the instance is billed by using the pay-as-you-go billing method and resides in a VPC, we recommend that you select Standard Mode in the Stop Mode section when you stop the instance. If you select Economical Mode, the computing resources (vCPUs and memory) of the instance are recycled. As a result, the instance may fail to be restarted due to insufficient resources. For more information, see Economical mode.

  2. On the Instance page, choose icon1 > Instance Settings > Set User Data. In the User Data field of the dialog box that appears, view the user data that you configured.

For more information, see Obtain instance metadata.

Examples on how to use Linux scripts in user data

Example 1: Use user-data scripts to specify custom YUM repositories and NTP and DNS services

When an instance is started, the system configures the default Yellowdog Updater Modified (YUM) repository, Network Time Protocol (NTP) service, and Domain Name System (DNS) service. You can use user data on the instance to change the default YUM repository, NTP service, and DNS service that are configured. Take note of the following items:

  • If you use a custom YUM repository, Alibaba Cloud no longer provides YUM repository support.

  • If you use a custom NTP service, Alibaba Cloud no longer provides time synchronization services.

The following sample code provides an example of a user-data script that you can apply to an instance that runs CentOS 7.2:

#!/bin/sh
# Modify DNS
echo "nameserve 8.8.X.X" | tee /etc/resolv.conf
# Modify yum repo and update
rm -rf /etc/yum.repos.d/*
touch myrepo.repo
echo "[base]" | tee /etc/yum.repos.d/myrepo.repo
echo "name=myrepo" | tee -a /etc/yum.repos.d/myrepo.repo
echo "baseurl=https://mirror.centos.org/centos" | tee -a /etc/yum.repos.d/myrepo.repo
echo "gpgcheck=0" | tee -a /etc/yum.repos.d/myrepo.repo
echo "enabled=1" | tee -a /etc/yum.repos.d/myrepo.repo
yum update -y
# Modify NTP Server
echo "server ntp1.aliyun.com" | tee /etc/ntp.conf
systemctl restart ntpd.service
Note
  • Replace 8.8.X.X with the actual DNS server address, https://mirror.centos.org/centos with the actual YUM repository address of CentOS, and server ntp1.aliyun.com with the actual NTP server address of Alibaba Cloud.

  • You can also use cloud-config data to change the YUM repository. However, cloud-config data is less flexible than user-data scripts and is unsuitable for scenarios in which specific YUM repositories are pre-configured by Alibaba Cloud. We recommend that you use user-data scripts.

Pass user data to an instance when you create the instance. After the instance is started, log on to the instance to check whether the user data is run as expected and whether the YUM repository, NTP service, and DNS service are configured as expected. The following sample code indicates that the configurations are changed as expected:

[root@iZbp1csxtw7jo9zp12s**** ~]# cat /etc/yum.repos.d/myrepo.repo
[base]
name=myrepo
baseurl=https://mirror.centos.org/centos
gpgcheck=0
enabled=1
[root@iZbp1csxtw7jo9zp12s**** ~]# cat /etc/resolv.conf
nameserver 8.8.X.X
[root@iZbp1csxtw7jo9zp12s**** ~]# ping www.baidu.com
PING www.a.shifen.com (14.215.XX.XX) 56(84) bytes of data.
64 bytes from 14.215.XX.XX (14.215.XX.XX): icmp_seq=1 ttl=52 time=26.3 ms
64 bytes from 14.215.XX.XX (14.215.XX.XX): icmp_seq=2 ttl=52 time=26.3 ms
64 bytes from 14.215.XX.XX (14.215.XX.XX): icmp_seq=3 ttl=52 time=26.2 ms
^Z
[2]+  Stopped                 ping www.baidu.com
[root@iZbp1csxtw7jo9zp12s**** ~]# cat /etc/ntp.conf
server ntp1.aliyun.com
[root@iZbp1csxtw7jo9zp12s**** ~]# systemctl status ntpd.service
● ntpd.service - Network Time Service
   Loaded: loaded (/usr/lib/systemd/system/ntpd.service; enabled; vendor preset: disabled)
   Active: active (running) since Mon 2021-09-06 14:53:19 CST; 13min ago
 Main PID: 5795 (ntpd)
   CGroup: /system.slice/ntpd.service
           └─5795 /usr/sbin/ntpd -u ntp:ntp -g

Sep 06 14:53:19 iZbp1cjdaurreftzgpgvqoZ ntpd[5795]: Listen and drop on 1 v6wildcard :: UDP 123
Sep 06 14:53:19 iZbp1cjdaurreftzgpgvqoZ ntpd[5795]: Listen normally on 2 lo 127.0.XX.XX UDP 123
Sep 06 14:53:19 iZbp1cjdaurreftzgpgvqoZ ntpd[5795]: Listen normally on 3 eth0 192.168.XX.XX UDP 123
Sep 06 14:53:19 iZbp1cjdaurreftzgpgvqoZ ntpd[5795]: Listening on routing socket on fd #20 for interface updates
Sep 06 14:53:19 iZbp1cjdaurreftzgpgvqoZ ntpd[5795]: 0.0.XX.XX c016 06 restart
Sep 06 14:53:19 iZbp1cjdaurreftzgpgvqoZ ntpd[5795]: 0.0.XX.XX c012 02 freq_set kernel 0.000 PPM
Sep 06 14:53:19 iZbp1cjdaurreftzgpgvqoZ ntpd[5795]: 0.0.XX.XX c011 01 freq_not_set
Sep 06 14:56:34 iZbp1cjdaurreftzgpgvqoZ ntpd[5795]: 0.0.XX.XX c61c 0c clock_step +0.464773 s
Sep 06 14:56:35 iZbp1cjdaurreftzgpgvqoZ ntpd[5795]: 0.0.XX.XX c614 04 freq_mode
Sep 06 14:56:36 iZbp1cjdaurreftzgpgvqoZ ntpd[5795]: 0.0.XX.XX c618 08 no_sys_peer

Example 2: Use user-data scripts to specify the administrator account

By default, Linux instances use the root account as the administrator account. You can use user data on an instance to specify another account as the administrator account.

The following sample code provides an example of a user-data script that you can apply to an instance that runs CentOS 7.2:

#!/bin/sh
useradd test
echo "test   ALL=(ALL)        NOPASSWD:ALL" | tee -a /etc/sudoers
mkdir /home/test/.ssh
touch /home/test/.ssh/authorized_keys
echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCRnnUveAis****" | tee -a /home/test/.ssh/authorized_keys
Note

Replace ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCRnnUveAis**** in the preceding code with your actual public key.

You can run the sample user-data script to obtain the following results:

  • An account named test is created and used as the administrator account.

  • The account can use only SSH key pairs to log on to the instance and cannot use passwords for logon.

  • Before you use the account to perform operations that require administrative permissions, run the sudo command to grant administrative permissions to the account. You do not need to enter the password when you grant the permissions.

Pass user data to an instance when you create the instance. After the instance is started, log on to the instance by using the test account and an SSH key pair. If you attempt to use a password for logon, an error is reported. After you log on to the instance, you can run the sudo command to grant administrative permissions to the test account. Then, you can use the test account to perform operations that require administrative permissions. Example:

[test@iZbp1csxtw7jo9zp12s**** ~]$ cd /root
-bash: cd: /root: Permission denied
[test@iZbp1csxtw7jo9zp12s**** ~]$ sudo cd /root
[test@iZbp1csxtw7jo9zp12s**** ~]$ 

Formats and running frequencies of user data

Linux instance

Linux instances use cloud-init to manage the startup behavior of the instances. During the first instance startup, the system automatically runs user data. Whether to run the user data on instance restart is determined by the format of the user data.

Check whether a Linux instance is started for the first time

On instance startup, operating system replacement, or system disk re-initialization, cloud-init checks whether the current boot is the first boot of an instance. Cloud-init checks for a cache directory that stores the internal status of cloud-init for use across stages and boots. If a cache directory exists, cloud-init checks whether the instance ID in the cache is the same as the actual ID of the instance. If the instance IDs are the same, the system is started for the first time. If the instance IDs are different, the system is not started for the first time. For more information, see Boot stages.

The following section describes the common formats of user data on Linux instances.

Note
  • For more information about user data formats, see User data formats of the cloud-init documentation.

  • If the size of a user-data script, cloud-config data, or include file exceeds 32 KB, we recommend that you select Gzip compressed content as the data type.

  • If you want to run a user-data script each time an instance is started, we recommend that you select cloud-config data or Upstart job as the data type.

User-data script

  • Introduction

    After a user-data script is passed to a Linux instance, the script is executed as a shell script and is run only once the first time the instance is started.

  • Running frequency

    • Instance boot: The user-data script is run only once the first time an instance is started. The script is not run on instance restart.

    • Operating system replacement: The script is automatically run.

    • System disk re-initialization: The script is automatically run.

    Important

    The script is not automatically run in the following scenarios:

    • If you use a custom image to replace the operating system of the source instance from which the custom image was created, the system determines that the instance is not started 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 stores data. When you initialize the system disk, the system determines that the instance is not started for the first time and does not run the script.

  • Format

    The first line starts with a number sign and an exclamation mark (#!).

  • Sample user-data script

    #!/bin/sh
    echo "Hello World. The time is now $(date -R)!" | tee /root/userdata_test.txt

    The sample user-data script is run only once the first time the instance is started and writes the system time to the userdata_test.txt file.

Cloud-config data

  • Introduction

    Cloud-init defines a series of functional modules to execute specific tasks and perform configurations, such as installing software packages and configuring network settings. Cloud-init obtains cloud-config data from vendor data, custom data, and kernel parameters. The cloud-config data determines which modules are involved in tasks and which actions to take. Before you create an ECS instance, you can configure custom cloud-config data by specifying the modules and tasks, and pass the cloud-config data to the instance as user data. When the instance is started, cloud-init reads and parses cloud-config data to run the modules as instructed in the configuration file and execute tasks to configure and deploy the instance.

  • Running frequency

    • Instance boot: Whether to execute the tasks in the cloud-config data is determined by the running frequency of the modules corresponding to the tasks. For information about the modules, see Modules.

      • Once-per-instance: A module is run only once the first time the instance is started. For example, modules such as Apt and Set Passwords are configured and run at a frequency of Once-per-instance. The modules are not run when the instance is restarted.

      • Always: A module is run each time an instance is started. For example, when modules such as Bootcmd and Update Etc Hosts are run at a frequency of Always, the modules are run each time the instance is started.

    • Operating system replacement: A module is automatically run.

    • System disk re-initialization: A module is automatically run.

      Important

      The script is not automatically run in the following scenarios:

      • If you use a custom image to replace the operating system of the source instance from which the custom image was created, the system determines that the instance is not started 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 stores data. When you initialize the system disk, the system determines that the instance is not started for the first time and does not run the script.

  • Format

    • The first line starts with #cloud-config, and the header does not contain spaces.

    • Cloud-config data must follow the Yet Another Markup Language (YAML) syntax.

  • Sample cloud-config data

    #cloud-config
    apt:
     primary:
     - arches: [default]
     uri: https://us.archive.ubuntu.com/ubuntu/
    bootcmd:
    - echo "Hello World. The time is now $(date -R)!" | tee /root/userdata_test.txt

    In this example, cloud-config data is run each time an instance is started to change the default repository and write the latest system time to the userdata_test.txt file.

Include file

  • Introduction

    An include file contains one or more links to user-data scripts or cloud-config data. Each link occupies a separate line. When an instance is started, cloud-init reads and parses the links one by one. If an error occurs when cloud-init reads a link, cloud-init stops reading the remaining links.

    Note

    You can use Alibaba Cloud Object Storage Service (OSS) to upload user-data scripts or cloud-config data to an instance, obtain links, and specify the validity period of links. For more information, see Get started by using the OSS console.

  • Running frequency

    • Instance boot: The running frequency varies based on the content to which a link is directed. For example, if a link is directed to a user-data script, the script is run only once the first time an instance is started. If the link is directed to cloud-config data, the running frequency of cloud-config data prevails.

    • Operating system replacement: The include file is automatically run.

    • System disk re-initialization: The include file is automatically run.

      Important

      The script is not automatically run in the following scenarios:

      • If you use a custom image to replace the operating system of the source instance from which the custom image was created, the system determines that the instance is not started 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 stores data. When you initialize the system disk, the system determines that the instance is not started for the first time and does not run the script.

  • Format

    The first line starts with #include, and the header does not contain spaces.

  • Sample include file

    #include
    https://ecs-image-test.oss-cn-hangzhou.aliyuncs.com/userdata/myscript.sh

    In this example, the include file contains a link to a user-data script, and the script is run only once the first time the instance is started.

    Note

    If you use an include file or Gzip compressed content, use a storage service to upload the script, obtain the script link, and specify the validity period of the link. We recommend that you use Alibaba Cloud OSS. For more information, see Get started by using the OSS console.

Gzip compressed content

  • Introduction

    If the size of a user-data script, cloud-config data, or an include file exceeds 32 KB, you can use Gzip to compress the content in an include file in the .gz format, generate a corresponding link, and then pass the include file to an instance. Cloud-init automatically decompresses the Gzip compressed content. The result of running the decompressed content is the same as the result of running uncompressed content that is passed directly to an instance.

    Note

    You can also use Alibaba Cloud OSS to upload user-data scripts or cloud-config data to an instance, obtain links, and specify the validity period of links. For more information, see Get started by using the OSS console.

  • Running frequency

    • Instance boot: The running frequency varies based on the script type and module type. For example, if a link is directed to Gzip compressed content that is a user-data script, the Gzip compressed content is run only once the first time the instance is started.

    • Operating system replacement: Gzip compressed content is automatically run.

    • System disk re-initialization: Gzip compressed content is automatically run.

      Important

      The script is not automatically run in the following scenarios:

      • If you use a custom image to replace the operating system of the source instance from which the custom image was created, the system determines that the instance is not started 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 stores data. When you initialize the system disk, the system determines that the instance is not started for the first time and does not run the script.

  • Format

    The first line starts with #include, and the header does not contain spaces.

  • Sample code for Gzip compressed content

    #include
    https://ecs-image-test.oss-cn-hangzhou.aliyuncs.com/userdata/myscript.gz

    In this example, an include file contains a link to Gzip compressed content that is a user-data script. After cloud-init reads the user-data script that is Gzip compressed, the script is automatically decompressed and run only once the first time the instance is started.

Upstart job

Note

To use an Upstart job on an instance, install the Upstart service on the instance. The instance must run one of the following operating systems: CentOS 6, Ubuntu 10, Ubuntu 12, Ubuntu 14, Debian 6, and Debian 7.

  • Introduction

    Upstart is an event-driven initialization system. An Upstart job is a configuration file that defines when to start or stop and how to run a service or task. An Upstart job file has a file extension of .conf and is located in the /etc/init/ directory.

  • Running frequency

    • Instance boot: The Upstart job is automatically run each time an instance is started.

    • Operating system replacement: An Upstart job is automatically run.

    • System disk re-initialization: An Upstart job is automatically run.

      Important

      The script is not automatically run in the following scenarios:

      • If you use a custom image to replace the operating system of the source instance from which the custom image was created, the system determines that the instance is not started 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 stores data. When you initialize the system disk, the system determines that the instance is not started for the first time and does not run the script.

  • Format

    The first line starts with #upstart-job, and the header does not contain spaces.

  • Sample Upstart job

    #upstart-job
    description "upstart test"
    start on runlevel [2345] #Starts at run levels 2, 3, 4, and 5.
    stop on runlevel [!2345] #Stops at run levels other than 2, 3, 4, and 5.
    exec echo "Hello World. The time is now $(date -R)!" | tee /root/output.txt

    The sample Upstart job returns a message that contains a timestamp when the system runs at the specified run level and adds the message to the /root/output.txt file. The Upstart job stops when the system runs at a run level that is different from the preceding specified run levels.

Windows instance

A Windows instance uses Plugin_Main_CloudinitUserData of the Vminit component to run user-data scripts. This plug-in is run only once the first time the instance is started. Windows user-data scripts support the batch and PowerShell formats.

Batch script

  • Running frequency

    • Instance boot: The script is run only once the first time an instance is started. The script is not run on instance restart.

    • Operating system replacement: The script is automatically run.

    • System disk re-initialization: The script is automatically run.

      Important

      The script is not automatically run in the following scenarios:

      • If you use a custom image to replace the operating system of the source instance from which the custom image was created, the system determines that the instance is not started 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 stores data. When you initialize the system disk, the system determines that the instance is not started for the first time and does not run the script.

  • Format

    • The first line is [bat], and the header does not contain spaces.

    • Only half-width characters can be entered.

  • Sample batch script

    [bat]
    echo "bat test" > C:\userdata_test.txt

    In this example, a batch script is run only once the first time the instance is started and writes "bat test" to the userdata_test.txt file.

PowerShell script

  • Running frequency

    • Instance boot: The script is run only once the first time an instance is started. The script is not run on instance restart.

    • Operating system replacement: The script is automatically run.

    • System disk re-initialization: The script is automatically run.

      Important

      The script is not automatically run in the following scenarios:

      • If you use a custom image to replace the operating system of the source instance from which the custom image was created, the system determines that the instance is not started 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 stores data. When you initialize the system disk, the system determines that the instance is not started for the first time and does not run the script.

  • Format

    • The first line is [powershell], and the header does not contain spaces.

    • Only half-width characters can be entered.

  • Sample PowerShell script

    [powershell]
    write-output "powershell test" | Out-File C:\userdata_test.txt

    In this example, a PowerShell script is run only once the first time the instance is started and writes powershell test to the userdata_test.txt file.

References

  • To query the user data of an ECS instance, you can call an API operation. For more information, see DescribeUserData.

  • You can use the User Data feature of Auto Scaling to allow multiple ECS instances to automatically run configured scripts or commands when the instances are started. This ensures the consistency of ECS instance configurations and simplifies O&M. For more information, see Use the Instance User Data feature to automatically configure ECS instances.

  • If you want a service or a script to rapidly recover when the service or script is interrupted due to issues such as a program exception, server restart, or a power failure, use the Cloud Assistant plug-in named ecs-tool-servicekeepalive. For more information, see Automatic service restoration.