Ansible automation baseline
Currently, I am working on a project to automate all the tasks related to managing on-premises applications. Ansible seems to be the good choice.
The list of steps, includes:
- ssh keys used for secure connection with the remote hosts
- Ansible configuration with host inventory
- Dockerfile to build docker image
- Gitlab CI pipeline.
Creating the SSH keys
To connect to remote hosts, I will authenticate using SSH keys pair.
ssh-keygen -t rsa -b 4096 -f id_rsa -N "" -C "ansible"
Above generates public and private keys. The private one will be stored as a CI/CD variable and in docker image, and the public one will be copied to all of the remote hosts.
ssh-copy-id -i id_rsa.pub remote_host1
Ansible Configuration
I like to keep my Ansible configuration simple, especially at this stage of the project.
ansible.cfg:
[defaults]
ansible_home = /root/.ansible
ansible_debug = false
ansible_nocolor = true
ansible_nocows = true
host_key_checking = false
Inventory file includes all the hosts I'll be connecting to.
hosts.yml:
all:
hosts:
my-server
children:
production:
hosts:
my-server:
ansible_host: ip_address_or_hostname
ansible_port: 22
ansible_user: root
ansible_ssh_private_key_file: /root/.ssh/id_rsa
ansible_python_interpreter: /usr/bin/python3
Dockerfile
The docker image will include the private SSH key. This way I will not be forced to configure SSH keys for every job in the pipeline.
I will not share this image to the public, so it shouldn't be a security issue.
Dockerfile:
FROM alpine:3.17
RUN apk add --nocache --update \
ansible-core \
python3 \
openssh
RUN mkdir -p /root/.ssh && \
chmod 0700 /root/.ssh
COPY id_rsa /root/.ssh
RUN chmod 600 /root/.ssh/id_rsa
I can now build docker image with following command:
docker build -t ansible-alpine:1.0 .
This creates the image which is about 100MB in size, and it has all I need to work with ansible playbooks.
Let's test it:
docker run ansible-alpine:1.0 ansible --version
To be able to use the image in the pipeline, I have to push it to the registry:
docker tag ansible-alpine:1.0 \
my.remote.registry.com/ansible-alpine:1.0
docker push my.remote.registry.com/ansible-alpine:1.0
Git repository and the pipeline
In the git repository, I will store following files:
- Dockerfile
- ansible.cfg
- hosts.yml
- .gitlab-ci.yml
Pipeline
.gitlab-ci.yml:
image: my.remote.registry.com/ansible-alpine:1.0
.setup
before_script:
- mv -f ansible.cfg /root/.ansible.cfg
ansible:ping:
extends: .setup
script:
- ansible all -i ${CI_PROJECT_DIR}/hosts.yml -m ping
This should be a good baseline for running my playbooks.
Resources
There is an RSS feed for this blog.