Try out some IaC tools to provision EC2 instance on AWS.
Table of Contents
- Create EC2 instance
- Create Security Group and attach to EC2
- Generate ssh public key locally
- Upload ssh public key to AWS and attach it to EC2
- Install Docker on EC2
- Run Ngnix
Generate ssh key for SSH connection, after that update terraform.tfvars
with the correct key name and path to public key.
$ ssh-keygen
$ ssh -i ~/.ssh/<path-to-private-key> ec2-user@<EC2-IP>
See the official page for how to install terraform: Install terraform
$ terraform plan
$ terraform apply
See the official page for how to install: Install Ansible
- Set EDITOR for Ansible-Vault
export EDITOR=vim
(or any other editor) - edit ansible.cfg and set
host_key_checking = False
to avoid host key checking otherwise Ansible cannot connect to EC2 via SSH. - Ansible needs path to private key for SSH connection to EC2, two options are:
- set it in the
variables.yml
- run ansible playbook with
--private-key <path-to-private-key>
- set it in the
See .boto configuration for more options to set and use AWS tokens. Credentials
as default it will take it from ~/.aws/credentials
, another easy alternative is to export them, but the safest approach is to use ansible-vault
but then you have to inject the variables into the playbook for each necessary task, like:
- name: Upload public key to AWS
ec2_key:
aws_access_key: "{{ aws_access_key_id }}"
aws_secret_key: "{{ aws_secret_access_key }}
security_token: "{{ aws_session_token }}"
region: "{{ region }}"
name: "{{ key_name }}"
key_material: "{{ lookup('file', '~/.ssh/{{ key_name }}.pub') }}"
- Run command below to create and encrypt content of the file, it will ask you at first for password, remember it as we need it each time we run Ansible playbook.
$ ansible-vault create keys.yml
- copy & paste keys:
aws_access_key_id: <key> aws_secret_access_key: <key> aws_session_token: <key>
$ ansible-playbook -i hosts ec2.yml --tags create_ec2,configure_ec2 --ask-vault-pass
- First command will run ansible to get info about the running EC2.
- Second command uses tags to
create
or/andconfig
EC2.
$ ansible-playbook -i hosts play-role.yml
it will provision and configure EC2 and run Nginx docker container, after that just run below command to change or add new container.
$ ansible-playbook -i hosts play-role.yml --tags app