Managing EC2 instances in bulkΒΆ

If we are using EC2 for any non-trivial amount of time, we probably have more that just a few instances that we need to manage. Keeping our static inventory files in sync with the state in the EC2 can quickly become the weak point of our automation.

In this scenario, we will have a look at how we can update sendmail RPM package on a subset of our EC2 instances without needing to manually specify their IP address. In order to give a concrete example, we will assume that all of the EC2 instances that we need to update contain a kind tag, containing the backend value.

We will start with the update.yaml playbook:

---
- hosts: backends
  become: true

  tasks:
    - name: Update sendmail
      package:
        name: sendmail
        state: latest

This is a fairly straightforward playbook that will make sure that the sendmail package is up-to-date. Next, we need to prepare a configuration for the EC2 inventory plugin. Our playbook expects that there will be a backends group of hosts available at the execution time, and we can provide it by placing the following content to the inventory.ec2.yaml file:

---
plugin: steampunk.aws.ec2

groups:
  backends:
    tags:
      kind: backend

The configuration should be self-explanatory: we defined a single group that will contain EC2 instances that are tagged with the kind: backend tag. DO note that the inventory configuration file must end with the .ec2.yaml suffix.

Before we can run our update.yaml playbook, we also need to enable the steampunk.aws.ec2 inventory plugin. We will do that by creating an ansible.cfg file right next to our playbook. The ansible.cfg file should at minimum contain the following two lines:

[inventory]
enable_plugins = steampunk.aws.ec2, auto, ini

There can be other configuration options in the configuration, and we can also add or remove some plugin names from the enable_plugins option, but the steampunk.aws.ec2 must be there.

Now we can update our backend instances by running:

$ ansible-playbook -i inventory.ec2.yaml update.yaml