Introduction
This is an Ansible playbook written in YAML format that automates the creation of Amazon Elastic Compute Cloud (EC2) instances and collects the host data.
The playbook has three tasks:
1. The first task, named “find ami,” uses the amazon.aws.ec2_ami_info module to find an Amazon Machine Image (AMI) based on the specified filters and store the result in the ec2_ami_facts_result variable.
2. The second task, named “instances,” uses the amazon.aws.ec2_instance module to create EC2 instances based on the specified parameters, including the AMI ID obtained from the previous task. It loops through a list of instances defined in the aws_instances variable, and stores the output in the aws_ec2_instance_output variable.
3. The third task, named “collect host data”, uses the ansible.builtin.set_fact module to extract the relevant data from the aws_ec2_instance_output variable and stores it in the aws_ec2_instance_data variable.
4. The fourth task, named “fetch host keys”, uses the ansible.builtin.shell module to run a command that retrieves the host keys from the instances. It loops through the instances in the aws_ec2_instance_data variable and stores the output in the aws_ec2_host_keys variable. It will keep retrying the command until it gets non-empty output or exceeds the maximum number of retries specified. The output will be discarded as it's not registered in a variable.
Links
- [
amazon.aws.ec2_ami_info](https://docs.ansible.com/ansible/latest/collections/amazon/aws/ec2_ami_info_module.html)
- [amazon.aws.ec2_instance](https://docs.ansible.com/ansible/latest/collections/amazon/aws/ec2_instance_module.html)
code
- ec2.yml
```yaml
---
- name: Create EC2 instance
- hosts: all
become: yes
vars:
aws_region: us-east-1
aws_ubuntu_owner: "099720109477"
aws_ubuntu_image: "ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-20220420"
tasks:
- name: Find AMI
amazon.aws.ec2_ami_info:
region: '{{ aws_region }}'
owners: "{{ aws_ubuntu_owner }}"
filters:
name: "{{ aws_ubuntu_image }}"
register: ec2_ami_facts_result
- name: Create instance
amazon.aws.ec2_instance:
region: "{{ aws_region }}"
name: "{{ item.key }}"
key_name: "aws_key"
instance_type: "{{ item.value.instance_type }}"
image_id: "{{ ec2_ami_facts_result['images'][0]['image_id'] }}"
network:
assign_public_ip: yes
private_ip_address: "{{ item.value.ip }}"
source_dest_check: no
loop: "{{ aws_instances | dict2items }}"
register: aws_ec2_instance_output
- name: Collect host data
ansible.builtin.set_fact:
aws_ec2_instance_data: "{{ aws_ec2_instance_output | json_query('results[].instances[0].[tags.Name, public_ip_address, instance_id]') }}"
- name: Fetch host keys
ansible.builtin.shell: aws ec2 get-console-output --region {{ aws_region }} --instance-id {{