Controlling Amazon EC2 instances with Elixir

Had a need to start, stop, create, and terminate EC2 instances from my Elixir-based Phoenix Framework app.
While there isn’t yet a solid EC2 management library for Elixir, there’s a full-on solid one for Erlang called Erlcloud which does just about anything you need to do.

Most of the examples I found out for using the library were in Erlang, but I was lucky enough to stumble upon some gists of people making equivalent calls in Elixir.

After including erlcloud in your project, configure your ec2 creds somewhere in your module.

@ec2'your access key', 'your secret key')

If you plan to spawn new instances, you will need to import the ec2_instance_spec:

Record.defrecord :ec2_instance_spec, Record.extract(:ec2_instance_spec, from: "deps/erlcloud/include/erlcloud_ec2.hrl")

If there is an image you’d like to use as the basis for your newly-spawned server (as I will show in the example below), set it as a constant also. NOTE THE SINGLE QUOTES. Normally Elixir libraries would use double-quoted strings, but Erlang libraries generally prefer single-quoted character strings.

@image_id 'instance-id'

Then follow the example of these methods to make the calls. Keep in mind that since this is an Erlang library, it very much likes to receive char lists instead of strings. Thankfully, calling to_char_list on a char list returns itself, so you don’t need to worry about what you’re passing in all that much.

  def start_instances(aws_ids) do
:erlcloud_ec2.start_instances(, fn x -> to_char_list x end), @ec2)

def stop_instances(aws_ids) do
:erlcloud_ec2.stop_instances(, fn x -> to_char_list x end), @ec2)

def create_new_instances(number) do
spec = ec2_instance_spec(image_id: @image_id,
instance_type: 'c4.xlarge',
key_name: 'your-ssh-key',
group_set: ['default', 'some_other_security_group'],
min_count: number,
max_count: number)
:erlcloud_ec2.run_instances(spec, @ec2)

def terminate_instances(aws_ids) do
:erlcloud_ec2.terminate_instances(, fn x -> to_char_list x end), @ec2)

Posted in Elixir, Phoenix

Leave a Reply

Your email address will not be published. Required fields are marked *