Install & Configure Ansible
With Ansible you can automate the processes of installing packages or configuring applications.
To install Ansible on Ubuntu all you need to do is add the package to system and then apt install it.
$ sudo apt update
$ sudo apt install software-properties-common
$ sudo apt-add-repository --yes --update ppa:ansible/ansible
$ sudo apt install ansible
To check if it is installed successfully, you can run the command from command line.
$ ansible --version
ansible 2.5.1
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/$user/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.15+ (default, Oct 7 2019, 17:39:04) [GCC 7.4.0]
To specify the server which we will be configuring, we need to edit ansible hosts file at /etc/ansible/hosts
To get the IP address for EC2 instance, you can either use the AWS console or the terraform.tfstate file. This file stores our managed infrastructure and configuration and at default it is located in the directory which you run terraform apply. You can read more about it here
$ grep '\"public_ip' terraform.tfstate
> "public_ip": "18.194.17.171",
Now we need te edit hosts file to include our instances’ IP address.
By default, Ansible uses ssh-keys to connect remotely. Since we are created our instance with a key-pair, it is not needed to explicitly create another one. Let’s see if it is working as expected with an ad-hoc command.
$ ansible all -m ping -e "ansible_ssh_private_key_file=keys/terraform-key-pair"18.194.17.171 | UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: root@18.194.17.171: Permission denied (publickey).\r\n",
"unreachable": true
}
Ansible, tries to connect the instance with the root user. However, on AWS when you run an Ubuntu instance, the default user name is ubuntu. So we have to try to connect with the ubuntu user. Let’s edit our ansible hosts file to specify it.
18.194.17.171 ansible_user=ubuntusudo ansible all -m ping -e "ansible_ssh_private_key_file=keys/terraform-key-pair"18.194.17.171 | SUCCESS => {
"changed": false,
"ping": "pong"
}