2.0 KiB
Here's a simple example of using cloud-init to automate the configuration of an instance on first boot:
#cloud-config
# Update packages on first boot
package_update: true
package_upgrade: true
# Install additional packages
packages:
- nginx
- php-fpm
# Write files to the system
write_files:
- path: /var/www/html/index.php
content: |
<?php
phpinfo();
?>
# Run commands on first boot
runcmd:
- systemctl start nginx
- systemctl enable nginx
# Create a user
users:
- name: webadmin
groups: sudo
shell: /bin/bash
sudo: ['ALL=(ALL) NOPASSWD:ALL']
ssh_authorized_keys:
- ssh-rsa AAAAB3NzaC1yc2EAA...your_public_ssh_key_here
# Configure SSH access
ssh_pwauth: false
disable_root: true
In this example:
-
The
package_updateandpackage_upgradedirectives ensure that the system packages are updated on first boot. -
The
packagessection specifies additional packages to be installed, in this case,nginxandphp-fpm. -
The
write_filessection is used to create a file on the system. Here, it creates a simple PHP script at/var/www/html/index.php. -
The
runcmdsection specifies commands to be executed on first boot. In this case, it starts and enables the Nginx service. -
The
userssection is used to create a user namedwebadminwith sudo privileges and an authorized SSH key. -
The
ssh_pwauthanddisable_rootdirectives are used to configure SSH access, disabling password authentication and root login.
To use this cloud-init configuration, you would save it as a YAML file (e.g., cloud-config.yaml) and provide it to your cloud provider or provisioning tool when launching a new instance.
Cloud-init will execute the specified configuration on the instance's first boot, automating the process of updating packages, installing software, creating files and users, and configuring SSH access.
This is just a simple example, but cloud-init supports a wide range of directives and modules for configuring various aspects of an instance, such as networking, storage, and more.