EC2 is at the heart of AWS as the primary compute resource on the platform. Ansible provides several modules that allow us to interact with EC2 instances. Being able to provision and manipulate EC2 instances within Ansible allows for infrastructure automation to be built into a deployment strategy. This exercise will allow students to explore the EC2 functionality in Ansible.
Learning Objectives
Successfully complete this lab by achieving the following learning objectives:
- Create and Edit `/home/ansible/deploy.yml` and Add Ansible Tasks to Stop the Existing EC2 Instance, by Tag, Then Deploy a New EC2 Instance That Meets the Specification Described in the Instructions.
After logging into the EC2 instance, run
su - ansible
to become theansible
user. The password is the same as it is forcloud_user
.Create and edit the playbook (
/home/ansible/deploy.yml
) so that it resembles the following:- hosts: localhost gather_facts: no vars_files: - /home/ansible/keys.yml tasks: - name: Get Subnet ID and AMI ID from existing server. ec2_instance_facts: aws_access_key: "{{ AWS_ACCESS_KEY_ID }}" aws_secret_key: "{{ AWS_SECRET_ACCESS_KEY }}" region: "{{ AWS_REGION }}" filters: tag:Name: Leo register: ec2_facts - name: Stop Leo Instance ec2: aws_access_key: "{{ AWS_ACCESS_KEY_ID }}" aws_secret_key: "{{ AWS_SECRET_ACCESS_KEY }}" ec2_region: us-east-1 state: stopped instance_tags: Name: Leo - name: Deploy new EC2 Instance ec2: aws_access_key: "{{ AWS_ACCESS_KEY_ID }}" aws_secret_key: "{{ AWS_SECRET_ACCESS_KEY }}" ec2_region: us-east-1 instance_type: t2.micro image: "{{ ec2_facts.instances[0].image_id }}" assign_public_ip: yes vpc_subnet_id: "{{ ec2_facts.instances[0].subnet_id }}" instance_tags: Name: New
- Run the Playbook `/home/ansible/deploy.yml` to Perform the Required Tasks, Then Log into the AWS Console to Validate that Everything Works
- Run the following command:
ansible-playbook /home/ansible/deploy.yml
- Log into the AWS Console, and in the EC2 Dashboard (find it by searching for EC2 in the Find Services search box) confirm the new instance’s existence and state.
- It might be best to wait a bit before checking. Once everything is finished processing though, we’ll see a Leo instance that’s stopped, and a new one called New that is running.
- Run the following command: