Certainly! Here's a Python script that uses Pulumi to create an instance:
python
import pulumi
from pulumi_aws import ec2
# Configure the AWS provider
config = pulumi.Config()
aws_region = config.require('aws_region')
pulumi.set_default_provider(pulumi.providers.Aws(region=aws_region))
# Define the instance settings
instance_type = 't2.micro'
ami_id = 'ami-0c55b159cbfafe1f0' # Replace with the desired AMI ID
key_name = 'my-key-pair' # Replace with your key pair name
# Create a security group for the instance
security_group = ec2.SecurityGroup('instance-security-group',
description='Security group for the instance',
ingress=[
ec2.SecurityGroupIngressArgs(
protocol='tcp',
from_port=22,
to_port=22,
cidr_blocks=['0.0.0.0/0'],
description='Allow SSH access'
)
]
)
# Create the EC2 instance
instance = ec2.Instance('my-instance',
instance_type=instance_type,
ami=ami_id,
key_name=key_name,
vpc_security_group_ids=[security_group.id],
tags={
'Name': 'My Instance'
}
)
# Export the instance's public IP address
pulumi.export('instance_public_ip', instance.public_ip)
Here's a breakdown of the script:
We import the necessary Pulumi modules: pulumi and pulumi_aws.ec2.
We configure the AWS provider by specifying the AWS region. You can set the region using the Pulumi configuration system or by directly assigning it to aws_region.
We define the instance settings, such as the instance type, AMI ID, and key pair name. Replace the ami_id with the desired AMI ID for your instance, and key_name with the name of your key pair.
We create a security group for the instance using ec2.SecurityGroup. In this example, we allow inbound SSH access (port 22) from any IP address (0.0.0.0/0). You can modify the security group rules based on your requirements.
We create the EC2 instance using ec2.Instance. We specify the instance type, AMI ID, key pair name, and the security group ID. We also add a tag to assign a name to the instance.
Finally, we export the public IP address of the instance using pulumi.export. This allows you to easily retrieve the instance's public IP address after running the Pulumi program.
To run this script, make sure you have Pulumi installed and configured with your AWS credentials. Then, navigate to the directory containing the script and run the following commands:
bash
pulumi up
Pulumi will prompt you to confirm the changes and create the instance. Once the instance is created, you can access it using the exported public IP address.
Remember to replace the placeholders (aws_region, ami_id, key_name) with your actual values before running the script.