Referring to EC2 instances by their name

In this scenario, we will create a new EC2 instance and install HTTP server on it, but with a novel twist: we will not look at the instance data such as IP address and DNS name at all. And the magic sauce that will allow us to do this is the EC2 inventory plugin.

We will start by creating an EC2 instance. For the sake of brevity, we will assume that the VPC, security groups, and all other prerequisites already exist and that we have their ids at hand. The playbook launch.yaml for getting an instance up and running would look like this:

---
- hosts: localhost
  gather_facts: false

  tasks:
    - name: Launch an EC2 instance
      steampunk.aws.ec2_instance:
        name: my_instance
        type: t3.micro
        ami: ami-0e8286b71b81c3cc1
        key_pair: demo_key
        subnet: subnet-123-id
        security_groups:
          - sg-123-id

We can now run the playbook by executing the following command:

$ ansible-playbook launch.yaml

Next, we will write another playbook called httpd.yaml that will install Apache HTTP server on our host:

---
- hosts: my_instance
  become: true

  tasks:
    - name: Install Apache
      package:
        name: httpd

Notice how we used the instance’s name from the first playbook as a value for the hosts play keyword in the second playbook. But this will not work out of the box. We need to instruct Ansible that it should use the steampunk.aws.ec2 inventory plugin and then supply it with a suitable configuration.

We can persuade Ansible that it should use the EC2 inventory plugin by exporting the ANSIBLE_INVENTORY_ENABLED variable and setting its value to steampunk.aws.ec2. This will disable all other inventory plugins, but for our use case, this is perfectly fine.

Last thing we will do is write the EC2 inventory plugin configuration. Because we are not doing anything fancy, the minimal configuration will do just fine:

---
plugin: steampunk.aws.ec2

Note that we must save the configuration in a file whose name ends with the .ec2.yaml otherwise the plugin will reject it. And because our lack of imagination, we will call this configuration file inventory.ec2.yaml.

Now we are ready to execute the httpd.yaml playbook:

$ export ANSIBLE_INVENTORY_ENABLED=steampunk.aws.ec2
$ ansible-playbook -i inventory.ec2.yaml httpd.yaml

And we are done.