A practical way to provision instances on Amazon Web Service EC2 with Ansible.
The following steps will be performed along the article to demonstrate the power around the integration of Ansible and AWS Cloud:
- Create AWS user
- Install Ansible and Ansible EC2 module dependencies
- Create SSH keys
- Create Ansible structure
- Run Ansible to provision the EC2 instance
- Connect to the EC2 instance via SSH
Create AWS user
Open the AWS Console, search for IAM (Identity and Access Management) and follow this steps to create a user and take note of the Access Key and Secret Key that will be used by Ansible to set up the instances.
Install Ansible and the EC2 module dependencies
sudo apt install python
sudo apt install python-pip
pip install boto boto3 ansible
Create SSH keys to connect to the EC2 instance after provisioning
ssh-keygen -t rsa -b 4096 -f ~/.ssh/my_aws
Create the Ansible directory structure
mkdir -p AWS_Ansible/group_vars/all/
cd AWS_Ansible
touch playbook.yml
Create Ansible Vault file to store the AWS Access and Secret keys.
ansible-vault create group_vars/all/pass.yml
New Vault password:
Confirm New Vault password:
The password provided here will be asked every time the playbook is executed or when editing the pass.yml file.
This article will follow the approach above, however, if you don’t want to provide the password every time, an insecure approach can create the pass.yml file by specifying a hashed password file:
openssl rand -base64 2048 > vault.pass ansible-vault create group_vars/all/pass.yml --vault-password-file vault.pass
With hashed password file you must specify the vault-password-file argument when running Ansible playbook and won’t be asked for the password:
ansible-playbook playbook.yml --vault-password-file vault.pass
Edit the pass.yml file and create the keys global constants
Create the variables ec2_access_key and ec2_secret_key and set the values gathered after user creation (IAM).
ansible-vault edit group_vars/all/pass.yml Vault password: ec2_access_key: AAAAAAAAAAAAAABBBBBBBBBBBB ec2_secret_key: afjdfadgf$fgajk5ragesfjgjsfdbtirhf
Directory structure
➜ AWS_Ansible tree . ├── group_vars │ └── all │ └── pass.yml └── playbook.yml2 directories, 2 files
Open the playbook.yml file and past the following content
Running Ansible to provision instances
If you execute Ansible without the tags argument the creation tasks won’t be performed.
ansible-playbook playbook.yml --ask-vault-pass
Create the instance
ansible-playbook playbook.yml --ask-vault-pass --tags create_ec2
Connect to the EC2 instance via SSH
ssh -i ~/.ssh/my_aws ubuntu@ec2-10-228-108-227.us-east-2.compute.amazonaws.com