Reputation: 3060
I have an AMI with some pre-installed software on it. When I create a new instance I have to SSH into the machine and run some script depending on the server's use case.
For example:
ssh [email protected] -i aws.pem && ./type1.sh
ssh [email protected] -i aws.pem && ./type2.sh
Is there a way to automate this process? I'm working with python. I know I can use boto to stand the server up but I'm unsure of the best practices in regards to connecting to the server and running a script.
Upvotes: 0
Views: 338
Reputation: 8435
Instead of building your own python-based solution, you can simply use the ability to run code after the first boot of an EC2 instance, which AWS already provides.
When creating an EC2 instance you can provide some so called "user data", which can contain code which gets executed after the first boot of the instance. That is possible for all ways to create an EC2 instance, be it the management console, CLI, API, boto3
or CloudFormation. The AWS documentation contains pretty extensive information how that works: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html
If you create your EC2 instance using the boto3
for example that would look like:
import boto3
ec2_client = boto3.client("ec2")
ec2_client.run_instances(ImageId="ami-abcd1234",
InstanceType="m3.medium",
SubnetId="subnet-abcd1234",
SecurityGroupIds=["sg-abcd1234"],
UserData="/home/ubuntu/type1.sh"
)
Upvotes: 4