How do I execute a command remotely with Pulumi?
To execute commands remotely with Pulumi, it’s common to use SSH to connect to a remote instance and run the command. Here’s how you can achieve that by defining a cloud instance (like an AWS EC2 instance), setting up the appropriate security group, and then using Pulumi’s Command
API to run commands remotely.
Below is an example illustrating this setup:
import * as pulumi from "@pulumi/pulumi";
import * as _null from "@pulumi/null";
import * as aws from "@pulumi/aws";
// Create a new security group for allowing SSH access
const allowSsh = new aws.ec2.SecurityGroup("allow_ssh", {
namePrefix: "allow_ssh",
description: "Allow SSH inbound traffic",
ingress: [{
description: "SSH from anywhere",
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"],
}],
});
// Create a new EC2 instance
const example = new aws.ec2.Instance("example", {
ami: "ami-0c55b159cbfafe1f0",
instanceType: aws.ec2.InstanceType.T2_Micro,
securityGroups: [allowSsh.name],
tags: {
Name: "example-instance",
},
});
// Pulumi command to execute remote command
const exampleResource = new _null.Resource("example", {});
export const publicIp = example.publicIp;
export const instanceId = example.id;
In this program:
- We first define the AWS provider for the desired region.
- A security group is created to allow SSH access.
- An EC2 instance is provisioned using an Amazon Linux 2 AMI.
- A
null_resource
with aremote-exec
provisioner is used to run remote commands on the instance. - We create outputs to expose the public IP and instance ID for further use.
Using Pulumi’s Command
API, you can dynamically run commands on remote instances as part of your infrastructure deployment. This can be extremely powerful for bootstrapping instances, installing software, or running configurations as part of your deployment pipeline.
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.