Saturday, December 15, 2018

Ansible Playbook for provisioning a new EC2 instance in AWS - Create a new EC2 Using Ansible Playbook

Please find the Ansible Playbook for provisioning a new EC2 instance. Execute the below steps in the machine where you installed Ansible.

Steps to create Ec2 instance using Ansible: 1. Login to AWS console, click on username and go to My security credentials. 2. Continue on security credentials, click on access keys 3. Create a new access key if you dont have one. Make sure you download the keys. 4. Login to EC2 instance using Git bash or ITerm where you installed Ansible, execute the below command and then enter the access keys and secret access keys as below: sudo vi ~/.boto

add below three lines in the above file, replace the ?? with access key and secret key values:
[Credentials] aws_access_key_id = ?? aws_secret_access_key = ??

5. Now edit the hosts file sudo vi /etc/ansible/hosts Add the below two lines in the end of the file:

6. cd ~
7. mkdir playbooks
8. cd playbooks
9. sudo vi create_jenkins_ec2.xml 
copy the below content in green color.
edit the create_jenkins_ec2.xml to make sure you update the key, region, AMI
--- - name: provisioning EC2 Lab Exercises using Ansible hosts: localhost connection: local gather_facts: False tags: provisioning vars: keypair: MyinfraCodeKey instance_type: t2.micro image: ami-916f59f4 wait: yes group: webserver count: 1 region: us-east-2 security_group: jenkins-security-group tasks: - name: Create a security group local_action: module: ec2_group name: "{{ security_group }}" description: Security Group for webserver Servers region: "{{ region }}" rules: - proto: tcp from_port: 22 to_port: 22 cidr_ip: - proto: tcp from_port: 8080 to_port: 8080 cidr_ip:   - proto: tcp from_port: 80 to_port: 80 cidr_ip: rules_egress: - proto: all cidr_ip: register: basic_firewall - name: Launch the new EC2 Instance local_action: ec2 group={{ security_group }} instance_type={{ instance_type}} image={{ image }} wait=true region={{ region }} keypair={{ keypair }} count={{count}} register: ec2 - name: Add the newly created EC2 instance(s) to the local host group (located inside the directory) local_action: lineinfile dest="/etc/ansible/hosts" regexp={{ item.public_ip }} insertafter="[webserver]" line={{ item.public_ip }} with_items: "{{ ec2.instances }}"

10. now execute the ansible playbook by
sudo ansible-playbook create_jenkins_ec2.xml

11. if everything is good, you should see the new instance on AWS console. make sure you are able to connect to that instance. 12. It will also make an entry in hosts file as well.

No comments:

Post a Comment

DevOps Bootcamp Aug 2024 Schedule | DevOps & AWS Azure Cloud Coaching by Coach AK | DevOps and Cloud Computing Online Classes

  (Lot of new topics covered like GitHub Actions, Helm and Monitoring..) The DevOps requirements in the IT market space is expected to grow ...