AWS SDK for Ruby
Developer Guide

Creating an Amazon EC2 Instance

The following example creates an Amazon EC2 instance MyGroovyInstance, with the tag Group and value MyGroovyGroup. The instance is created in Availability Zone us-west-2a. The instance has the machine image MACHINE_IMAGE for the account with ID ACCOUNT_ID, the security group with the ID SECURITY_GROUP_ID, and the subnet with the ID SUBNET_ID. Then it displays the instance's ID and public IP address.


In the empty script value, you can add instructions that your Amazon EC2 instance executes when it starts.

require 'aws-sdk-ec2' # v2: require 'aws-sdk' require 'base64' # User code that's executed when the instance starts script = '' encoded_script = Base64.encode64(script) ec2 = 'us-west-2') instance = ec2.create_instances({ image_id: 'IMAGE_ID', min_count: 1, max_count: 1, key_name: 'MyGroovyKeyPair', security_group_ids: ['SECURITY_GROUP_ID'], user_data: encoded_script, instance_type: 't2.micro', placement: { availability_zone: 'us-west-2a' }, subnet_id: 'SUBNET_ID', iam_instance_profile: { arn: 'arn:aws:iam::' + 'ACCOUNT_ID' + ':instance-profile/aws-opsworks-ec2-role' } }) # Wait for the instance to be created, running, and passed status checks ec2.client.wait_until(:instance_status_ok, {instance_ids: []}) # Name the instance 'MyGroovyInstance' and give it the Group tag 'MyGroovyGroup' instance.create_tags({ tags: [{ key: 'Name', value: 'MyGroovyInstance' }, { key: 'Group', value: 'MyGroovyGroup' }]}) puts puts instance.public_ip_address