Start Project
This Ansible project is specifically for working with dynamic AWS EC2 instance inventory, create the following three directories (assuming your already in ~/ansible
from the previous page):
AWS EC2 Plugin
Add the following file plugins/aws_ec2.yaml
:
plugin: aws_ec2
aws_access_key: "{{ lookup('env', 'AWS_ACCESS_KEY') }}"
aws_secret_key: "{{ lookup('env', 'AWS_SECRET_KEY') }}"
regions:
- eu-west-1
keyed_groups:
- key: tags
prefix: tag
Configuration
Under playbooks
, create another subdirectory aws
and change into it:
Add the following ansible.cfg
file with the correct path to your AWS private key:
[defaults]
inventory = ../../plugins
roles_path = ../../roles
host_key_checking = False
retry_files_enabled = False
command_warnings = False
remote_user = ec2-user
private_key_file = <PATH_TO_PRIVATE_KEY>
deprecation_warnings=False
[privilege_escalation]
become = true
become_method = sudo
become_user = root
become_ask_pass = false
Testing
With this configuration and plugin in place, test to see if your EC2 instances are returned:
The plugin was configured with keyed_groups
, see how the inventory returns the tag groups using:
Then instances can be targeted using the tag group name, for example:
With everything working, test a basic playbook, for example smoke_test.yaml
. Notice that hosts:
is targeting the tag derived previously:
- name: smoke test playbook
hosts: tag_project_exampleforyou
become: yes
tasks:
- shell: echo 'Hello World' > /tmp/test.txt
And run the playbook:
SSH to the EC2 instance and check the result:
General Configuration
The best practice is to create an ansible.cfg
file in a directory from which you run Ansible commands. This directory would also contain any files used by your Ansible projects, such as inventories and playbooks. This is the most
common location used for the Ansible configuration file. It is unusual to use a
~/.ansible.cfg
or /etc/ansible/ansible.cfg
file in practice. You can also use the ANSIBLE_CONFIG
environment variable.
Run ansible --version
command to identify which version of Ansible is installed, and which configuration file is being used.
A typical ansible.cfg
file:
[defaults]
inventory = ./inventory
remote_user = user
ask_pass = false
[privilege_escalation]
become = true
become_method = sudo
become_user = root
become_ask_pass = false
An adhoc command is a way of executing a single Ansible task.
Use the ansible
command to run adhoc commands:
Example:
134.209.21.255 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
The ansible-doc -l
command lists all modules installed on a system.
Use ansible-doc
to view the documentation of the particular module,
for example ansible-doc ping
.
The following section provide a quick reference to the core concept's, but to jump into creating custom roles to deploy the FastAPI application skip to here: First Role