How do I execute a shell command on an AWS EC2 instance?
In this guide, we will walk through the steps to execute a shell command on an AWS EC2 instance using Pulumi. We will define an EC2 instance and use the user_data
parameter to run the desired shell commands at the instance startup.
Here’s a detailed explanation of what will be done:
- AWS Provider: Set up the AWS provider to manage resources on AWS.
- VPC and Security Group: Create a VPC and a security group to use for our EC2 instance.
- EC2 Instance: Define the EC2 instance resource.
- User Data: Pass shell commands using the
user_data
parameter which executes upon instance startup. - Outputs: Export essential details such as instance ID, public IP for reference.
Here’s the complete program:
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const exampleVpc = new aws.ec2.Vpc("example_vpc", {cidrBlock: "10.0.0.0/16"});
const exampleSg = new aws.ec2.SecurityGroup("example_sg", {
vpcId: exampleVpc.id,
ingress: [{
fromPort: 22,
toPort: 22,
protocol: "tcp",
cidrBlocks: ["0.0.0.0/0"],
}],
egress: [{
fromPort: 0,
toPort: 0,
protocol: "-1",
cidrBlocks: ["0.0.0.0/0"],
}],
});
const exampleInstance = new aws.ec2.Instance("example_instance", {
ami: "ami-0c55b159cbfafe1f0",
instanceType: aws.ec2.InstanceType.T2_Micro,
securityGroups: [exampleSg.name],
userData: `#!/bin/bash
echo "Hello, Pulumi!" > /home/ec2-user/welcome.txt
`,
tags: {
Name: "example-instance",
},
});
export const instanceId = exampleInstance.id;
export const publicIp = exampleInstance.publicIp;
Summary
In this example, we’ve set up an AWS environment with a VPC and a security group, and provisioned an EC2 instance. Using the user_data
parameter, we executed a shell command to create a file with a welcome message. This file will be created once the instance starts up. Finally, we exported the instance ID and public IP for easy reference.
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.