Skip to main content

Ansible in Gitlab CI Pipelines

Shenzhen, China

Preparing the Ansible Container

Downloading the Ansible Image

https://hub.docker.com/r/williamyeh/ansible/tags?page=1&ordering=last_updated

docker pull williamyeh/ansible:alpine3
docker run -ti  ID /bin/ash

Adding the SSH Key

apk add --no-cache --update openssh-keygen openssh-client
ssh-keygen -t rsa -b 2048
chmod 0400 $HOME/.ssh/id_rsa.pub
chmod 600 ~/.ssh/authorized_keys
chmod 0700 $HOME/.ssh/
ssh-copy-id root@SERVER-IP -p PORT

OR

cat ~/.ssh/id_rsa.pub //add to =>
nano /root/.ssh/authorized_keys //on destination server

Copying your Playbooks

docker cp /opt/ansible/playbooks/. CONTAINER-ID:/root/playbooks

Adding your Hosts

nano /etc/ansible/hosts
localhost

[webservers]
alpha.example.org

Test Ping

ansible webservers -m ping

alpha.example.org | SUCCESS => {
"changed": false,
"ping": "pong"
}

Using a Playbooks

Update Docker Container

ansible-playbook /root/playbooks/update_wiki_en.yml --vault-password-file /root/playbooks/vault_pass
---
- hosts: wiki
gather_facts: no

tasks:

- name: Include vault for registry login
include_vars:
file: login_vault.yml

- name: Log into Docker Registry and force re-authorization
docker_login:
registry: my.gitlab.de:12345
username: "{{ansible_gitlab_user}}"
password: "{{ansible_gitlab_pass}}"
reauthorize: yes

- name: Download the latest Wiki build images
shell: docker pull my.gitlab.de:12345/wiki/wiki_en_container

- name: Remove the EN Wiki Container
docker_container:
name: wiki_en
state: absent

- name: Rebuild the EN Wiki Container
docker_container:
name: wiki_en
image: my.gitlab.de:12345/wiki/wiki_en_container
state: started
restart_policy: unless-stopped
networks:
- name: gateway

Update Git Repositories

ansible-playbook /root/playbooks/update_wiki_downloads.yml --vault-password-file /root/playbooks/vault_pass
---
- hosts: wiki
gather_facts: no

tasks:

- name: Include vault for registry login
include_vars:
file: login_vault.yml

- name: Get updated files from git repository
git:
repo: https://{{ ansible_gitlab_user | urlencode }}:{{ ansible_gitlab_pass | urlencode }}@my.gitlab.de/wiki/wiki_downloads.git
dest: /opt/wiki_downloads

Committing your Changes

docker ps                                                                                                                               
CONTAINER ID IMAGE COMMAND
b0368c583033 4b5bd4d797fd "/bin/ash"
docker commit -m "Ansible Configured" -a "Mike Polinowski" b0368c583033 ansible-runner
docker images

REPOSITORY TAG IMAGE ID
ansible-runner latest 9e065e284b6f
docker run -ti ansible-runner /bin/ash