All Products
Search
Document Center

Elastic Compute Service:Instance user data

Last Updated:Mar 19, 2024

You can use the user data of Elastic Compute Service (ECS) instances to manage startups of the instances or pass data to the instances. This topic describes how to pass user data to ECS instances.

Introduction

Linux and Windows instances support the user data feature. You can use the user data feature in the following ways:

  • Add scripts to user data to run on instance boot to automate instance configurations such as automatically obtaining software resource packages, enabling services, printing logs, installing dependencies, and initializing web environments.

  • Pass regular data that you want to use in an instance as user data to the instance.

You can use different types of scripts to prepare user data and then enter the prepared data in the User Data field to pass the data to an instance during instance creation. For more information, see the Pass user data to a Linux instance and Pass user data to a Windows instance sections in this topic.

You can view the user data that is passed to an instance by using instance metadata. For more information, see Obtain instance metadata.

Limits

  • Only instances that are deployed in virtual private clouds (VPCs) support the user data feature.

  • To support the user data feature, the instances must be created from the public images for 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 and later

  • All available instance types support the user data feature. For retired instance types, only I/O-optimized instances support the user data feature. For more information, see Retired instance types.

Pass user data to a Linux instance

Procedure

  1. Prepare user data.

    You can use the following types of scripts to prepare user data for Linux instances.

    Note
    • On instance restart, operating system replacement, or system disk re-initialization, cloud-init checks whether the current boot is the first boot of a new instance before cloud-init run an appropriate script. Cloud-init checks for a cache that stores the internal status of cloud-init for use across stages and boots. If the cache exists, cloud-init compares the instance ID in the cache against the instance ID that cloud-init obtains at runtime to check whether the current boot is the first boot of the instance. For more information, see https://cloudinit.readthedocs.io/en/latest/explanation/boot.html#first-boot-determination.

      • On the first boot of an instance, cloud-init runs once-per-instance configurations. The once-per-instance configurations are run per instance only on the first boot.

      • On a subsequent boot of the instance, cloud-init runs always configurations. The always configurations are run on every boot.

    • If you want to use include files or gzip compressed content to prepare user data, upload script files to available storage services, obtain the links to the files, and then specify validity periods for the links. We recommend that you use Object Storage Service (OSS). For more information, see the OSS documentation and Lifecycle rules based on the last modified time. You can also learn more about how to prepare user data from the cloud-init documentation. For more information, see User-Data Formats.

    User-data scripts

    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.

    • Characteristics

      User-data scripts are directly run as shell scripts after the scripts are passed to Linux instances. User-data scripts have the following characteristics:

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

      • User-data scripts are run only once the first time an instance starts.

    • Sample script

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

      The preceding sample script can be run to write the system time to the userdata_test.txt file the first time an instance starts.

    • Running frequency

      • Instance restart: Scripts are run only once the first time an instance starts and are not automatically run when the instance restarts.

      • Operating system replacement: Scripts are automatically run.

      • System disk re-initialization: Scripts are automatically run.

      Note

      If you replace the operating system of an instance by using a custom image that was created from the instance or re-initialize the system disk of an instance that stores data from a source instance, the system determines that this is not the first boot of the instance. In this case, user-data scripts are not automatically run.

    Cloud-config data

    Important

    Cloud-config allows you to easily perform specific tasks by using user data. When you use cloud-init to perform specific tasks, we recommend that you use cloud-config to complete configurations.

    • Characteristics

      Cloud-config allows you to pre-configure specific services, such as YUM repository update, SSH key import, and dependency installation, for instances in a convenient manner. Cloud-config data has the following characteristics:

      • The first line is #cloud-config, and the header cannot include spaces.

      • Cloud-config data must follow the YAML syntax.

    • Sample script

      #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

      The preceding sample script can be run to modify the default software repository and write the latest system time to the userdata_test.txt file every time an instance starts.

    • Running frequency

      • Instance restart: The running frequency is determined based on the module. For example, the apt module is configured to run only once per instance, and the Bootcmd module is configured to run every time an instance starts.

      • Operating system replacement: Cloud-config data is automatically run.

      • System disk re-initialization: Cloud-config data is automatically run.

      Note

      If you replace the operating system of an instance by using a custom image that was created from the instance or re-initialize the system disk of an instance that stores data from a source instance, the system determines that this is not the first boot of the instance. In this case, user-data scripts are not automatically run.

    Include files

    • Characteristics

      An include file contains one or more script links. Each line contains one script link. When an instance starts, cloud-init reads each script link and script content. If an error occurs when the content of a script is being read, the remaining scripts are not read. Include files have the following characteristics:

      • The first line is #include, and the header cannot include spaces.

      • Each script cannot exceed 16 KB in size before the script is encoded in Base64.

    • Sample script

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

      The preceding sample script indicates that the include file contains a script link. The running frequency is determined based on the script type. For example, if the script is a user-data script, the script is run only once the first time an instance starts.

    • Running frequency

      • Instance restart: The running frequency is determined based on the script type and module type. For example, if an include file contains a link to a user-data script, the script is run only once the first time an instance starts.

      • Operating system replacement: Scripts are automatically run.

      • System disk re-initialization: Scripts are automatically run.

        If you replace the operating system of an instance by using a custom image that was created from the instance or re-initialize the system disk of an instance that stores data from a source instance, the system determines that this is not the first boot of the instance. In this case, user-data scripts are not automatically run.

      Note

      If you replace the operating system of an instance by using a custom image that was created from the instance or re-initialize the system disk of an instance that stores data from a source instance, the system determines that this is not the first boot of the instance. In this case, user-data scripts are not automatically run.

    Gzip compressed content

    • Characteristics

      If the user-data script, cloud-config data, or include file is more than 16 KB in size, you can compress the user-data script, cloud-config data, or include file into gzip compressed content (.gz), create a link to the content, and then pass the link in an include file. 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 directly passed. Gzip compressed content has the following characteristics:

      • The first line is #include, and the header cannot include spaces.

      • The size of the gzip compressed content cannot exceed 16 KB before the content is encoded in Base64.

    • Sample script

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

      The preceding sample script indicates that the include file contains a link to the gzip compressed content. Cloud-init reads the gzip compressed content, decompresses the content, and then runs the decompressed content. The running frequency is determined based on the type of the decompressed content. For example, if a user-data script is compressed into gzip compressed content, the content is run only once the first time an instance starts.

    • Running frequency

      • Instance restart: The running frequency is determined based on the type of the content that is compressed and the module type. For example, if a user-data script is compressed into gzip compressed content, the content is run only once the first time an instance starts.

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

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

      Note

      If you replace the operating system of an instance by using a custom image that was created from the instance or re-initialize the system disk of an instance that stores data from a source instance, the system determines that this is not the first boot of the instance. In this case, user-data scripts are not automatically run.

    Upstart Job scripts

    Note

    To use Upstart Job scripts on an instance, install the upstart service on the instance. You can install the upstart service on instances that run one of the following operating systems: CentOS 6, Ubuntu 10, Ubuntu 12, Ubuntu 14, Debian 6, and Debian 7.

    • Characteristics

      Upstart is an event-driven init system. An Upstart Job is the configuration file that defines when and how to start or stop a service or a job. The configuration file has an extension of .conf and is located in the /etc/init/ directory. Upstart Job scripts have the following characteristics: The first line is #upstart-job, and the header cannot include spaces.

    • Sample script

      #upstart-job
      description "upstart test"
      start on runlevel [2345] #Start at run levels 2, 3, 4, and 5.
      stop on runlevel [!2345] #Stop 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 preceding sample script can be run to display a message that includes a timestamp when the system enters specific run levels and write the message to the /root/output.txt file. When the system leaves the run levels, the job stops.

    • Running frequency

      • Instance restart: Scripts are run every time an instance starts.

      • Operating system replacement: Scripts are automatically run.

      • System disk re-initialization: Scripts are automatically run.

      Note

      If you replace the operating system of an instance by using a custom image that was created from the instance or re-initialize the system disk of an instance that stores data from a source instance, the system determines that this is not the first boot of the instance. In this case, user-data scripts are not automatically run.

  2. Pass the user data to an instance.

    • Pass the user data when you create an instance.

      On the instance buy page, click Advanced Settings(Optional) to view advanced options and then enter the user data in the User Data field. If the user data is already encoded in Base64, select Enter Based64 Encoded Information.

        Note
        • If you select Enter Base64 Encoded Information, make sure that the entered user data is encoded in Base64 and the user data does not exceed 16 KB in size before the data is encoded in Base64.

        • If you do not select Enter Base64 Encoded Information, you can enter user data that is not encoded in Base64. The entered user data is automatically encoded in Base64 in the ECS console.

      The following figure shows sample user data that is used to write the system time to a specific file the first time the instance starts.

      image

    • Modify the user data of an existing instance.

      On the Instance page, find the instance whose user data you want to modify and choose icon1 > Instance Settings > Set User Data in the Actions column. Enter the new user data in the User Data field.

      Note

      If you want to start a pay-as-you-go instance immediately after you modify its user data, we recommend that you set the stop mode of the instance to Standard Mode.

      The following figure shows sample user data that is used to write the system time to a specific file every time the instance starts.

      image

  3. View the user data that is passed to the instance and the result of running the data.

    1. Connect to the instance.

      For more information, see Connect to a Linux instance by using a password or key.

    2. Run the following command to view the user data by using the metadata of the instance:

      curl http://100.100.100.200/latest/user-data

      In this example, the user data that was passed during instance creation in Step 2 is used. If the user data included in the command output is the user data that you entered as shown in the following figure, the user data was passed as expected.view-user-data

    3. Run the following command to view the result of running the user data:

      cat userdata_test.txt

      The result of running user data is related to the content included in the data. The following figure shows a sample result of writing the system time to a specific file.

      view-result

Examples on how to use scripts in user data

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

When an instance starts, the system configures the default YUM repository, the Network Time Protocol (NTP) service, and the Domain Name System (DNS) service. You can use user data on the instance to change the default YUM repository and the NTP and DNS services 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 run on an instance that runs CentOS 7.2:

#!/bin/sh
# Modify DNS
echo "nameserve8.8.X.X.8" | 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
  • In the preceding code, the URL is only for reference. Replace the URL with the actual URL.

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

Pass the user data when you create an instance. After the instance starts, log on to the instance to view the result of running the user data and verify the configurations of the YUM repository, NTP service, and DNS service. 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 run on 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 permissions.

Pass user data when you create an instance. After the instance starts, 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 administrator permissions to the test account, as shown in the following figure. Then, you can use the test account to perform operations that require administrative permissions.

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

Pass user data to a Windows instance

  1. Prepare user data.

    You can use batch and PowerShell scripts to prepare user data for Windows instances.

    Batch scripts

    • Characteristics

      • The first line is [bat], and the header cannot have spaces.

      • You can enter only half-width characters. No other characters are allowed.

    • Sample script

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

      The preceding sample script can be run to write "bat test" to the userdata_test.txt file the first time an instance starts.

    • Running frequency

      • Instance restart: Scripts are run once only the first time an instance starts and are not automatically run when the instance restarts.

      • Operating system replacement: Scripts are automatically run.

      • System disk re-initialization: Scripts are automatically run.

      Note

      If you replace the operating system of an instance by using a custom image that was created from the instance or re-initialize the system disk of an instance that stores data from a source instance, the system determines that this is not the first boot of the instance. In this case, user-data scripts are not automatically run.

    PowerShell scripts

    • Characteristics

      • The first line is [powershell], and the header cannot have spaces.

      • You can enter only half-width characters. No other characters are allowed.

    • Sample script

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

      The preceding sample script can be run to write powershell test to the userdata_test.txt file the first time an instance starts.

    • Running frequency

      • Instance restart: Scripts are run once only the first time an instance starts and are not automatically run when the instance restarts.

      • Operating system replacement: Scripts are automatically run.

      • System disk re-initialization: Scripts are automatically run.

      Note

      If you replace the operating system of an instance by using a custom image that was created from the instance or re-initialize the system disk of an instance that stores data from a source instance, the system determines that this is not the first boot of the instance. In this case, user-data scripts are not automatically run.

  2. Pass the user data to an instance.

    • Pass the user data when you create an instance.

      On the instance buy page, click Advanced Settings(Optional) to view advanced options and then enter the user data in the User Data field. If the user data is already encoded in Base64, select Enter Based64 Encoded Information.

      Note
      • If you select Enter Base64 Encoded Information, make sure that the entered user data is encoded in Base64 and the user data does not exceed 16 KB in size before the data is encoded in Base64.

      • If you do not select Enter Base64 Encoded Information, you can enter user data that is not encoded in Base64. The entered user data is automatically encoded in Base64 in the ECS console.

      The following figure shows sample user data that is used to write content to a specific file.

      image

    • Modify the user data of an existing instance

      On the Instance page, find the instance whose user data you want to modify and choose icon1 > Instance Settings > Set User Data in the Actions column. Enter the new user data in the User Data field.

      Note

      If you want to start a pay-as-you-go instance immediately after you modify its user data, we recommend that you set the stop mode of the instance to Economical Mode.

      The following figure shows sample user data that is used to write content to a specific file.

      image

      Note

      After you modify the user data of a Windows instance, the new user data is not run when you start the instance.

  3. View the user data that is passed to the instance and the result of running the data.

    1. Connect to the instance.

      For more information, see Connect to a Windows instance by using a password or key.

    2. Run the following command to view the user data of the instance:

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

      In this example, the user data that was passed during instance creation in Step 2 is used. If the user data included in the command output is the user data that you entered as shown in the following figure, the user data is passed as expected.view-userdata

    3. Run the following command to view the result of running the user data:

      The result of running user data is related to the content included in the data. The following figure shows a sample result of writing content to a specific file.powershell-sample