How do I run a shell command on an EC2 instance in TypeScript?
To run a shell command on an AWS EC2 instance using Pulumi and TypeScript, you need to create an EC2 instance and use the userData
property to specify the shell commands that should be executed when the instance starts. The userData
property allows you to pass a script that will be run on the instance at launch.
Here is a complete Pulumi program written in TypeScript that creates an EC2 instance and runs a shell command on it:
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Create a new security group for the EC2 instance
const securityGroup = new aws.ec2.SecurityGroup("web-secgrp", {
description: "Enable SSH access",
ingress: [
{ protocol: "tcp", fromPort: 22, toPort: 22, cidrBlocks: ["0.0.0.0/0"] },
],
});
// Create an EC2 instance
const server = new aws.ec2.Instance("web-server", {
instanceType: "t2.micro",
ami: "ami-0c55b159cbfafe1f0", // Amazon Linux 2 AMI
keyName: "my-key-pair", // Replace with your key pair name
vpcSecurityGroupIds: [securityGroup.id],
userData: `#!/bin/bash
echo "Hello, World!" > /var/www/html/index.html
sudo systemctl start httpd
sudo systemctl enable httpd
`,
tags: {
Name: "web-server",
},
});
// Export the public IP of the instance
export const publicIp = server.publicIp;
export const publicHostName = server.publicDns;
Key Points:
- Security Group: We create a security group to allow SSH access to the EC2 instance.
- EC2 Instance: We create an EC2 instance with the specified AMI, instance type, and security group.
- User Data: We use the
userData
property to run a shell script that writes “Hello, World!” to an HTML file and starts the HTTP server. - Exports: We export the public IP and DNS name of the instance for easy access.
Summary:
In this program, we created an AWS EC2 instance and used the userData
property to run a shell command on it. The shell script writes “Hello, World!” to an HTML file and starts the HTTP server. We also created a security group to allow SSH access to the instance and exported the public IP and DNS name of the instance.
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.