8 posts tagged

ansible

There are several ways to do this:

  1. Use template action and use template file
  2. Use array of entries and loop with lininfile command
  3. Use https://docs.ansible.com/ansible/latest/collections/community/general/htpasswd_module.html htpasswd module.

I decided to go with approach #2.
in variables

htpasswd:
  - user1:password1
  - user2:password2

in the playbook

- name: set password file
      lineinfile:
        path: "{{ webroot }}/shared/.htpasswd"
        line: "{{ item }}"
        create: yes
      when: oxid.configuration == "production"
      loop: "{{ htpasswd }}"
ansible
Mar 22, 2020, 10:06

ansible vault quick encryption

it was convenient for me to use zsh function for the string encryption:

add this to .zshrc

vault() {
	echo -n $1 | ansible-vault encrypt_string --vault-id=myvault
}

and use like this

vault my-password

output should be similar to this

Reading plaintext input from stdin. (ctrl-d to end input)
!vault |
          $ANSIBLE_VAULT;1.1;AES256
          39383538336133613537376463373062363639343761633365666530313363343766663662336530
          6637336536383438333038623865386636383737393165340a663236336463306261386466326262
          31333664393130313734303230356364626335346336363430303036633962343536353137376665
          3464363163346433350a653230336636643562363030383363336166636365313133343563393261
          38396530616261616338626161363133323430323361623164393466333038326637
Encryption successful
ansible

I struggled with deploying web services via Ansible to staging CoreOS host and that's something that looks like a hell!

I received one error, then another with just simple-simple steps like

- name: IT-Premium docker-compose deploy
  hosts: coreos
  tasks:
    - name: Install docker-py
      pip: name=docker-py executable=/home/core/bin/pip

    - name: Install PyYAML
      pip: name=PyYAML executable=/home/core/bin/pip

    - name: Install docker-compose
      pip: name=docker-compose executable=/home/core/bin/pip version=1.9.0

    - name: Creates it-premium directory
      file: path=/home/core/it-premium state=directory

    - name: copy docker-compose.yml
      copy: src=./docker-compose.yml dest=/home/core/it-premium/docker-compose.yml
      tags: deploy

    - name: copy sqlite
      copy: src=./sqlite dest=/home/core/it-premium/ mode=0644
      tags: deploy

    - name: docker registry login
      docker_login:
        registry: "registry.it-expert.com.ua"
        username: nexus
        password: "{{gitlab_password}}"

    - name: pull images
      docker_image:
        name: registry.it-expert.com.ua/nexus/it-premium
        state: present

    - name: launch it-premium docker-compose with 2 containers
      tags: step1
      docker_service:
        project_src: it-premium
        state: present
        build: no
      register: output

    - debug:
        var: output

You can notice version of docker-compose 1.9.0, which is supplied there. That's because of issue with
Error: cannot import name 'IPAMConfig'
thrown by docker_service.

And here is why https://github.com/ansible/ansible/issues/20492

This is due to your docker-compose version.
The docker-py package has been renamed into docker in version 2.0 (https://github.com/docker/docker-py/releases/tag/2.0.0). And in this version, Docker.Client has been renamed into docker.APIClient.
Docker-compose 1.10+ now requires docker instead of docker-py. And due to his name the docker package is before the docker-py one in the PYTHONPATH leading to the import error.
A workaround is to downgrade your docker-compose version to 1.9.0 the time the Ansible docker_container module updates its dependencies from docker-py to docker.

That's something like «piss on you, dirty user, because we do not care about backward compatibility».

Because when you change something, it is like delete old state and introduce new one instead. And when you delete something, that could broke anything that relies on state.

How to do instead? Just ADD something new without removal. Call it with new namespace, new function name and just use!

ansibledocker

You need to upgrade ansible to version 2.2.0.0

via brew:

brew update && brew upbrage ansible

or via pip:

pip install --upgrade ansible
ansible
- name: install docker-compose
  become: yes
  file: path=/opt/bin state=directory mode=0755

- name: get docker-compose url
  shell: curl -s https://api.github.com/repos/docker/compose/releases/latest | jq -r '.assets[].browser_download_url | select(contains("Linux") and contains("x86_64"))'
  register: url_info

- name: fetch docker-compose
  become: yes
  get_url: url="{{url_info.stdout}}" dest=/opt/bin/docker-compose mode=0755
ansibledocker

Вот простой рецепт:

- name: backup mysql from container
  gather_facts: no
  vars:
    - db_container: container_db_1
    - image: mysql:5.6
    - db:
        name: database_name
        user: root
        password: root
    - dump_file: ./dump-latest.sql
  tasks:
    - name: run backup container
      shell: "docker run --rm --link {{db_container}}:db --entrypoint \"/usr/bin/mysqldump\" {{image}} -hdb -u{{db.user}} -p{{db.password}} {{db.name}}"
      register: output

    - name: copy output
      local_action: copy content="{{ output.stdout }}" dest="{{dump_file}}"

Работает БЕЗ создания файлов на удаленном хосте, помимо, конечно, временного контейнера.

ansibledockermysql

Разработал для этого очень простой рецепт по мотивам предыдущей заметки:


- name: install docker-compose to coreos
  hosts: coreos
  gather_facts: no
  tasks:
    - name: install docker-compose
      become: yes
      file: path=/opt/bin state=directory mode=0755

    - name: get docker-compose url
      shell: curl -s https://api.github.com/repos/docker/compose/releases/latest | jq -r '.assets[].browser_download_url | select(contains("Linux") and contains("x86_64"))'
      register: url_info

    - name: fetch docker-compose
      become: yes
      get_url: url="{{url_info.stdout}}" dest=/opt/bin/docker-compose mode=0755
<code>

скрипт найдет url и скачает самую свежую версию и установит аттрибуты для корректного запуска из /opt/bin

напоминаю, /opt/bin переживает перезагрузки и является persistent каталогом в CoreOS.
ansiblecoreos

Ведь для использования Ansible необходимо иметь python интерпретатор

"module_stdout": "/bin/sh: /usr/bin/python: No such file or directory\r\n",

к счастью у ansible есть режим так называемой raw работы, без использования интерпретатора python, который и даст установить python и необходимые модули.

запускаем

ansible-galaxy install defunctzombie.coreos-bootstrap -p ./roles

и создаем рецепт bootstrap.yml

- hosts: coreos
  gather_facts: False
  roles:
    - defunctzombie.coreos-bootstrap

и запускаем для нужного хоста coreos

ansible-playbook bootstrap.yml

это загрузит соответствующую версию мини-питона и даст ansible возможность выполняться на хосте как обычно.

Я использую macOS, поэтому пришлось ствить ansible из pip пакетов командой

sudo pip install ansible
pip install --upgrade setuptools --user python
pip install --upgrade pyasn1 --user python

Update:
в новой версии ansible вместо пакета docker предлагается использовать docker-container и docker-image, поэтому https://coreos.com/blog/managing-coreos-with-ansible/ немного устарел.

Вот мой работоспособный site.yml

- name: Nginx Example
  hosts: coreos
  tasks:
    ##- name: Start etcd
      #service: name=etcd.service state=started

    - name: Install docker-py
      pip: name=docker-py executable=/home/core/bin/pip

    - name: Install PyYAML
      pip: name=PyYAML executable=/home/core/bin/pip

    - name: Install docker-compose
      pip: name=docker-compose executable=/home/core/bin/pip

    - name: launch nginx container
      docker_container:
        name: "nginx-proxy"
        image: "jwilder/nginx-proxy"
        ports: "80:80"
        restart_policy: always
        state: started
        volumes:
          - /var/run/docker.sock:/tmp/docker.sock:ro

    - name: copy docker-compose.yml
      copy: src=./Sites/it-premium/docker-compose.prod.yml dest=/home/core/it-premium/docker-compose.yml
      tags: deploy

    - name: copy sqlite
      copy: src=./Sites/it-premium/sqlite dest=/home/core/it-premium/ directory_mode=yes mode=0644
      tags: deploy

    - name: launch it-premium docker-compose with 2 containers
      docker_service:
        project_src: it-premium
        build: no
      register: output

    - debug: var=output
    - assert:
        that: "not output.changed "

здесь я копирую docker-compose.yml подготовленный для продакшена и sqlite3 продакшен базу из бекапа.

ansiblecoreos