How do I specify user data scripts for EC2 instance initialization?
When launching an EC2 instance, you can pass user data scripts to perform common automated tasks during the instance’s initialization. For example, you might want to install a web server, apply system updates, configure settings, or any other custom operation. Here’s an example demonstrating how to use user data scripts for EC2 instances in AWS.
The code below will create an EC2 instance with user data that installs Apache web server on boot. The instance will be in the specified region with the given AMI and instance type. An SSH key pair is used to connect to the instance securely.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const example = new aws.ec2.Instance("example", {
ami: "ami-0c55b159cbfafe1f0",
instanceType: aws.ec2.InstanceType.T2_Micro,
keyName: "my-key",
userData: `#!/bin/bash
sudo yum update -y
sudo yum install -y httpd
sudo systemctl start httpd
sudo systemctl enable httpd
echo "Hello, World!" > /var/www/html/index.html
`,
tags: {
Name: "example-instance",
},
});
export const instanceId = example.id;
export const publicIp = example.publicIp;
Explanation
- Provider Configuration: Specifies the AWS region to deploy the EC2 instance.
- aws_instance Resource: Defines the EC2 instance resource with the following configurations:
- AMI: Amazon Linux 2 AMI ID.
- Instance Type: Instance type as
t2.micro
which is free-tier eligible. - Key Name: Named
my-key
, allowing SSH access with this key. - User Data: A script that is executed during the first boot of the instance. The script updates the package repositories, installs Apache HTTP Server, starts, and enables it to run at every boot, and creates a simple index.html file.
- Tags: Tags the instance with a given name.
The outputs instance_id
and public_ip
provide the instance ID and public IP of the newly created instance, making it easier to locate and access.
In conclusion, we have created an EC2 instance on AWS with a user data script that automates the installation and configuration of an Apache web server. This setup is useful for provisioning and configuring instances automatically as they start.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.