We have seen in the past how to use Terraform to deploy AWS EC2 instance. But, this is also possible using Ansible. In this blog post, we will focus on the deployment of AWS EC2 instance using Ansible. I assume that you have already been to the basics installation of Ansible and basic playbook creation. Here are some links on tunnelix.com on Ansible. Please consider visiting them if you have any doubt. I assume that you have already install Ansible on your machine and know the basics of Ansible Playbook creation.
Setup the AWS IAM Account
1. Start by creating an AWS user account through the AWS IAM. Go to IAM, then click on USER, then click on ADD USER:
2. Once you have click on the ADD USER, Enter a name and tick on PROGRAMMATIC ACCESS, click on NEXT: PERMISSIONS
3. On the following page, Create a group, I have created one called ‘Ansible’ then attached the user to the group. After that click on ATTACH EXISTING POLICIES DIRECTLY’, then search for AMAZONEC2FULLACCESS and tick it and click on NEXT: TAGS.
4. Click on Next, add the tags and click on ‘CREATE USER’.
5. Consider downloading the credential.csv file by clicking on Download .csv
6. Consider also creating a key pair
Some installations and configurations on the Ansible controller
7. Now, on your Linux controller, we will need some Python modules to interact with AWS. Assuming you have already installed Ansible, consider installing python-pip:
yum install python-pip
8. Let’s now install the AWS CLI
yum install awscli
9. Sync the clock of the VM to prevent any error
10. Configure your AWS CLI
It will prompt you to enter the AWS Access Key ID, secret key, etc. Just enter the information. Example:
[[email protected] ~]# aws configure AWS Access Key ID [****************GYGY]: AKIA5xxxxxxxxxx AWS Secret Access Key [****************458q]: EvEd55xxxxxxxxxx Default region name [us-east-1]: Default output format [json]:
11. Create the following file: /home/.boto
[Credentials] aws_access_key_id = AKIAxxxxxxxxxxxxx aws_secret_access_key = xc3xxxxxxxxxxx
12. The following command should test your AWS credentials
aws get sts-caller-identity
13. Install the boto Python module. The boto python module will talk with the AWS CLI to authenticate on aws.
pip install boto
Creating the Playbook and Deploying the AWS EC2 Instance
14. Now, let’s create a playbook as follows in /home/AWSTask.yml
- name: EC2 Instance creation hosts: localhost connection: local tasks: - name: Launching the EC2 instance ec2: instance_type: t2.nano key_name: ansible image: ami-0b69ea66ff7391e80 region: us-east-1 group: default count: 1 vpc_subnet_id: subnet-ef9179a4 wait: yes assign_public_ip: yes
You can also access it on my Ansible Github repository.
15. Simply launch the Playbook
16. As you can see below, the EC2 instance has been created.