Vagrant 및 ansible_local 프로비저너로 Docker 환경 준비
Vagrant has been in my toolbox since 2014 or so. It has been a long time and I am still happy to use it.
최근에는 프로젝트의 필요성에 따라 Ansible로 더 많이 작업하고 있습니다. 이전에는 설치 단계를 자동화하기 위해 셸 스크립트를 작성한 사람 중 한 명이었습니다. 하지만 도구 벨트에 Ansible을 추가하면 더 잘할 수 있습니다.
이 기사의 주요 목적은 Vagrant 및 ansible_local provisioner로 도커 환경을 준비한 방법을 공유하는 것입니다. 이 환경이 준비되면 기여하고 싶은 오픈 소스 프로젝트에서 작업할 수 있습니다.
전제 조건
Vagrant 를 사용할 것이라고 언급했습니까? 틀림없이. 따라서 하이퍼바이저가 필요합니다. Microsoft 운영 체제를 사용하므로 하이퍼바이저가 필요합니다. 현재 Oracle의 VirtualBox를 사용하고 있습니다.
내가 설치한 게스트 시스템은 Ubuntu Focal64입니다.
내가 말했듯이 작동하는 솔루션을 얻기 위해 여러 번 반복했습니다. 환경을 구축하려고 할 때 여러 번 오류가 발생했습니다. 내가 찾은 것은 환경을 갖기 위해 지정된 버전의 다음 도구가 필요하다는 것입니다.
Vagrantfile 초기화
Docker 환경은 Ubuntu Focal64를 기반으로 합니다. 다음 명령을 사용하여 Vagrant를 초기화합니다.
vagrant init ubuntu/focal64
PS D:\vagrant_projects\ubuntu_env> vagrant init ubuntu/focal64
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.
Vagrantfile의 내용
PS D:\vagrant_projects\ubuntu_env> type .\Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
# The most common configuration options are documented and commented below.
# For a complete reference, please see the online documentation at
# https://docs.vagrantup.com.
# Every Vagrant development environment requires a box. You can search for
# boxes at https://vagrantcloud.com/search.
config.vm.box = "ubuntu/focal64"
# Disable automatic box update checking. If you disable this, then
# boxes will only be checked for updates when the user runs
# `vagrant box outdated`. This is not recommended.
# config.vm.box_check_update = false
# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine. In the example below,
# accessing "localhost:8080" will access port 80 on the guest machine.
# NOTE: This will enable public access to the opened port
# config.vm.network "forwarded_port", guest: 80, host: 8080
# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine and only allow access
# via 127.0.0.1 to disable public access
# config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"
# Create a private network, which allows host-only access to the machine
# using a specific IP.
# config.vm.network "private_network", ip: "192.168.33.10"
# Create a public network, which generally matched to bridged network.
# Bridged networks make the machine appear as another physical device on
# your network.
# config.vm.network "public_network"
# Share an additional folder to the guest VM. The first argument is
# the path on the host to the actual folder. The second argument is
# the path on the guest to mount the folder. And the optional third
# argument is a set of non-required options.
# config.vm.synced_folder "../data", "/vagrant_data"
# Provider-specific configuration so you can fine-tune various
# backing providers for Vagrant. These expose provider-specific options.
# Example for VirtualBox:
#
# config.vm.provider "virtualbox" do |vb|
# # Display the VirtualBox GUI when booting the machine
# vb.gui = true
#
# # Customize the amount of memory on the VM:
# vb.memory = "1024"
# end
#
# View the documentation for the provider you are using for more
# information on available options.
# Enable provisioning with a shell script. Additional provisioners such as
# Ansible, Chef, Docker, Puppet and Salt are also available. Please see the
# documentation for more information about their specific syntax and use.
# config.vm.provision "shell", inline: <<-SHELL
# apt-get update
# apt-get install -y apache2
# SHELL
end
제공자 ansible_local
Ansible을 사용하여 환경을 설정하기로 결정했습니다. Vagrant는 두 가지 프로비저너를 제공합니다. 호스트 시스템이 Linux 기반이거나 [ansible_local]이 아닌 경우 다른 선택이 필요한 고전적인 [ansible]. 이 프로비저너를 사용하면 Vagrant가 자동으로 게스트 시스템에 Ansible을 설치하고 여기에서 직접 플레이북을 실행합니다.
공식documentation을 참조하십시오.
ansible_local에 대한 최소 구성은 현재 프로젝트 디렉토리에서 읽을 [playbook.yml] 파일을 정의하는 것입니다.
# Run Ansible from the Vagrant VM
config.vm.provision "ansible_local" do |ansible|
ansible.playbook = "playbook.yml"
end
약간의 반복 후에 몇 가지 구체적인 옵션을 추가해야 한다는 것을 알았습니다. Python 2.7로 pip를 설치하는 데 필요합니다. 다음 구성이 있어야 합니다.
# Run Ansible from the Vagrant VM
config.vm.provision "ansible_local" do |ansible|
ansible.playbook = "playbook.yml"
ansible.install_mode = "pip"
ansible.pip_install_cmd = "curl https://bootstrap.pypa.io/pip/2.7/get-pip.py | sudo python"
end
Docker용 플레이북
플레이북을 구축하기 위해 article에서 현재Digital Ocean를 따랐습니다. 이 기사는 저자Tony Tran 및 Erika Heidi 덕분에 잘 설명되어 있습니다.
전체 플레이북은 [Pull default Docker image] 작업까지 잘 작동했습니다. community.docker 컬렉션이 엉망이라는 오류가 발생했습니다. 몇 가지 추가 조사를 수행하고 article에서 XLAB SteamPunk과 Vagrant 및 Ansible에 대한 자세한 문서를 연구했습니다. 이 모든 정보를 통해 마침내 Vagrantfile을 정의하는 방법을 알아냈습니다.
config.vm.provision "ansible_local" do |ansible|
ansible.playbook = "playbook.yml"
ansible.install_mode = "pip"
ansible.pip_install_cmd = "curl https://bootstrap.pypa.io/pip/2.7/get-pip.py | sudo python"
ansible.galaxy_role_file = "requirements.yml"
ansible.galaxy_command = "ansible-galaxy collection install -r %{role_file}"
end
작업 구성
모든 것이 설정되면 명령으로 다음 결과를 얻을 수 있습니다.
vagrant up
PS D:\vagrant_projects\vagrant-ansible-docker-env> vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'ubuntu/focal64'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'ubuntu/focal64' version '20220804.0.0' is up to date...
==> default: Setting the name of the VM: vagrant-ansible-docker-env_default_1659985304505_52969
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
==> default: Forwarding ports...
default: 3000 (guest) => 3000 (host) (adapter 1)
default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2222
default: SSH username: vagrant
default: SSH auth method: private key
default: Warning: Connection reset. Retrying...
default: Warning: Connection aborted. Retrying...
default: Warning: Connection reset. Retrying...
default: Warning: Connection aborted. Retrying...
default:
default: Vagrant insecure key detected. Vagrant will automatically replace
default: this with a newly generated keypair for better security.
default:
default: Inserting generated public key within guest...
default: Removing insecure key from the guest if it's present...
default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
default: /vagrant => D:/vagrant_projects/vagrant-ansible-docker-env
==> default: Running provisioner: ansible_local...
default: Installing Ansible...
default: Installing pip... (for Ansible installation)
default: Running ansible-galaxy...
[DEPRECATION WARNING]: Ansible will require Python 3.8 or newer on the
controller starting with Ansible 2.12. Current version: 2.7.18 (default, Jul 1
2022, 12:27:04) [GCC 9.4.0]. This feature will be removed from ansible-core in
version 2.12. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.
/usr/local/lib/python2.7/dist-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 2 is no longer supported by the Python core team. Support for it is now deprecated in cryptography, and will be removed in the next release.
from cryptography.exceptions import InvalidSignature
Starting galaxy collection install process
Process install dependency map
Starting collection install process
Downloading https://galaxy.ansible.com/download/community-docker-2.7.0.tar.gz to /home/vagrant/.ansible/tmp/ansible-local-8337dY3egI/tmpOS1yA1/community-docker-2.7.0-wm2luu
Installing 'community.docker:2.7.0' to '/home/vagrant/.ansible/collections/ansible_collections/community/docker'
community.docker:2.7.0 was installed successfully
default: Running ansible-playbook...
[DEPRECATION WARNING]: Ansible will require Python 3.8 or newer on the
controller starting with Ansible 2.12. Current version: 2.7.18 (default, Jul 1
2022, 12:27:04) [GCC 9.4.0]. This feature will be removed from ansible-core in
version 2.12. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.
/usr/local/lib/python2.7/dist-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 2 is no longer supported by the Python core team. Support for it is now deprecated in cryptography, and will be removed in the next release.
from cryptography.exceptions import InvalidSignature
PLAY [all] *********************************************************************
TASK [Gathering Facts] *********************************************************
[DEPRECATION WARNING]: Distribution Ubuntu 20.04 on host default should use
/usr/bin/python3, but is using /usr/bin/python for backward compatibility with
prior Ansible releases. A future Ansible release will default to using the
discovered platform python for this host. See https://docs.ansible.com/ansible-
core/2.11/reference_appendices/interpreter_discovery.html for more information.
This feature will be removed in version 2.12. Deprecation warnings can be
disabled by setting deprecation_warnings=False in ansible.cfg.
ok: [default]
TASK [Install aptitude] ********************************************************
changed: [default]
TASK [Install required system packages] ****************************************
changed: [default]
TASK [Add Docker GPG apt Key] **************************************************
changed: [default]
TASK [Add Docker Repository] ***************************************************
changed: [default]
TASK [Update apt and install docker-ce] ****************************************
changed: [default]
TASK [Install Docker Module for Python] ****************************************
changed: [default]
TASK [Pull default Docker image] ***********************************************
changed: [default]
PLAY RECAP *********************************************************************
default : ok=8 changed=7 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
PS D:\vagrant_projects\vagrant-ansible-docker-env>
Docker 환경 검증
ssh를 사용하여 방랑 게스트에 연결하고 잘 알려진 [Hello World] 컨테이너 예제를 시작합니다.
Vagrant 게스트에 연결
vagrant와의 연결은 다음 명령으로 이루어집니다.
vagrant ssh
PS D:\vagrant_projects\vagrant-ansible-docker-env> vagrant ssh
Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 5.4.0-122-generic x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
System information as of Mon Aug 8 22:06:38 UTC 2022
System load: 0.08 Processes: 119
Usage of /: 8.0% of 38.70GB Users logged in: 0
Memory usage: 28% IPv4 address for docker0: 172.17.0.1
Swap usage: 0% IPv4 address for enp0s3: 10.0.2.15
2 updates can be applied immediately.
1 of these updates is a standard security update.
To see these additional updates run: apt list --upgradable
컨테이너 hello-world 실행
다음 명령을 사용하기만 하면 됩니다.
sudo docker run hello-world
vagrant@ubuntu-focal:~$ sudo docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
2db29710123e: Pull complete
Digest: sha256:53f1bbee2f52c39e41682ee1d388285290c5c8a76cc92b42687eecf38e0af3f0
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/get-started/
vagrant@ubuntu-focal:~$
결론
모든 파일은 내 GitHub 계정Here에서 사용할 수 있습니다.
나는 곧 사용된 Python 버전에 대한 경고를 제거하기 위해 설정을 개선하는 작업을 할 것입니다.
Reference
이 문제에 관하여(Vagrant 및 ansible_local 프로비저너로 Docker 환경 준비), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/sdeseille/preparing-docker-environment-with-vagrant-and-ansiblelocal-provisioner-18b8텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)