728x90

아키텍처

 

 

 

구성 순서

1. Vagrantfile

2. Ansible_env_ready.yml

3. add_ssh_auth.sh

4. vagrant up

  - Vagrantfile 실행

5. vagrant provision ansible-server

  - Ansible_env_ready.yml, add_ssh_auth.sh 실행

 

 

Vagrantfile 작성

Ansible-Node03, Ansible-Node04 부분 추가

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant_API_Version = "2"

Vagrant.configure(Vagrant_API_Version) do |config|

  # Ansible-Node01
  config.vm.define:"ansible-node01" do |cfg|
		cfg.vm.box = "centos/7"
		cfg.vm.provider:virtualbox do |vb|
			vb.name = "Ansible-Node01"
      vb.customize ["modifyvm", :id, "--cpus",1]
      vb.customize ["modifyvm", :id, "--memory",512]
		end
		cfg.vm.host_name = "ansible-node01"
		cfg.vm.synced_folder ".", "/vagrant", disabled: true
		cfg.vm.network "public_network", ip: "172.30.1.110"
		cfg.vm.network "forwarded_port", guest: 22, host: 19211, auto_correct: false, id: "ssh"
    cfg.vm.provision "shell", path: "bash_ssh_conf_4_CentOS.sh"
		
	end
  
  # Ansible-Node02
  config.vm.define:"ansible-node02" do |cfg|
		cfg.vm.box = "centos/7"
		cfg.vm.provider:virtualbox do |vb|
			vb.name = "Ansible-Node02"
      vb.customize ["modifyvm", :id, "--cpus",1]
      vb.customize ["modifyvm", :id, "--memory",512]
		end
		cfg.vm.host_name = "ansible-node02"
		cfg.vm.synced_folder ".", "/vagrant", disabled: true
		cfg.vm.network "public_network", ip: "172.30.1.120"
		cfg.vm.network "forwarded_port", guest: 22, host: 19212, auto_correct: false, id: "ssh"
    cfg.vm.provision "shell", path: "bash_ssh_conf_4_CentOS.sh"
		
	end  
 
  # Ansible-Node03
  config.vm.define:"ansible-node03" do |cfg|
		cfg.vm.box = "ubuntu/trusty64"
		cfg.vm.provider:virtualbox do |vb|
			vb.name = "Ansible-Node03"
      vb.customize ["modifyvm", :id, "--cpus",1]
      vb.customize ["modifyvm", :id, "--memory",512]
		end
		cfg.vm.host_name = "ansible-node03"
		cfg.vm.synced_folder ".", "/vagrant", disabled: true
		cfg.vm.network "public_network", ip: "172.30.1.130"
		cfg.vm.network "forwarded_port", guest: 22, host: 19213, auto_correct: false, id: "ssh"
    
		
	end
  
  # Ansible-Node04
  config.vm.define:"ansible-node04" do |cfg|
		cfg.vm.box = "ubuntu/trusty64"
		cfg.vm.provider:virtualbox do |vb|
			vb.name = "Ansible-Node04"
      vb.customize ["modifyvm", :id, "--cpus",1]
      vb.customize ["modifyvm", :id, "--memory",512]
		end
		cfg.vm.host_name = "ansible-node04"
		cfg.vm.synced_folder ".", "/vagrant", disabled: true
		cfg.vm.network "public_network", ip: "172.30.1.140"
		cfg.vm.network "forwarded_port", guest: 22, host: 19214, auto_correct: false, id: "ssh"
    
		
	end 
  
  
  # Ansible-Server
	config.vm.define:"ansible-server" do |cfg|
		cfg.vm.box = "centos/7"
		cfg.vm.provider:virtualbox do |vb|
			vb.name = "Ansible-Server"
		end
		cfg.vm.host_name = "ansible-server"
		cfg.vm.synced_folder ".", "/vagrant", disabled: true
		cfg.vm.network "public_network", ip: "172.30.1.100"
		cfg.vm.network "forwarded_port", guest: 22, host: 19210, auto_correct: false, id: "ssh"
		cfg.vm.provision "shell", path: "bootstrap.sh"
		cfg.vm.provision "file", source: "Ansible_env_ready.yml", destination: "Ansible_env_ready.yml"
		cfg.vm.provision "shell", inline: "ansible-playbook Ansible_env_ready.yml"
    cfg.vm.provision "shell", path: "add_ssh_auth.sh", privileged: false
    cfg.vm.provision "file", source: "Ansible_ssh_conf_4_CentOS.yml", destination: "Ansible_ssh_conf_4_CentOS.yml"
		cfg.vm.provision "shell", inline: "ansible-playbook Ansible_ssh_conf_4_CentOS.yml"
	end
  
end

 

 

Ansible_env_ready.yml 파일 수정

node03, node04 관련 코드 추가

---
- name: Setup for the Ansible's Environment
  hosts: localhost
  gather_facts: no
  
  tasks:
  
    - name: Add "/etc/hosts"
      blockinfile:  |
        path=/etc/hosts
        content="
          172.30.1.100  server
          172.30.1.110  node01
          172.30.1.120  node02
          172.30.1.130  node03
          172.30.1.140  node04"
          
    - name: Add "/etc/ansible/hosts"
      blockinfile:  |
        path=/etc/ansible/hosts
        content="
          [CentOS]
            node01
            node02
            
          [Ubuntu]
            node03
            node04"
            
    - name: Install sshpass for Authentication
      yum:
        name: sshpass
        state:  present
          
 
    - name: Install vim-enhanced
      yum:
        name: vim-enhanced
        state: present
        
    - name: Install git
      yum:
        name: git
        state: present

    - name: Download pathogen.vim
      shell: "curl -fLo /home/vagrant/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim"

    - name: Git clone vim-ansible-yaml
      git:
        repo: 'https://github.com/chase/vim-ansible-yaml.git'
        dest: /home/vagrant/.vim/bundle/vim-ansible-yaml

    - name: Configure vimrc
      lineinfile:
        path: /home/vagrant/.vimrc
        line: "{{ item }}"
      with_items:
        - "set number"
        - "execute pathogen#infect()"
        - "syntax on"
        - autocmd FileType yaml setlocal ts=2 sts=2 sw=2 et ai

    - name: Configure Bashrc
      lineinfile:
        path: /home/vagrant/.bashrc
        line: "{{ item }}"
      with_items:
        - "alias vi='vim'"
        - "alias ans='ansible'"
        - "alias anp='ansible-playbook'"

 

add_ssh_auth.sh 파일 수정

node03, node04 추가

#! /usr/bin/env bash

# ssh key 생성
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@node01
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@node02
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@node03
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@node04

 

vagrant up 실행

Vagrantfile이 실행됨

 

vagrant provision

Ansible_env_ready.yml 파일과 add_ssh_auth.sh 파일 실행

PS C:\HashiCorp\udemy-ansible> vagrant provision ansible-server

 

통신 확인

PS C:\HashiCorp\udemy-ansible> vagrant ssh ansible-server
Last login: Wed Jun  8 19:11:49 2022 from 10.0.2.2

[vagrant@ansible-server ~]$ ans all -m ping -k

 

728x90
728x90

실습 개요


실습 목적

- 하나의 플레이북으로 두 개의 작업 진행

 

실습 과정

1. 앤서블 서버에 공유 디렉토리를 생성

2. 앤서블 노드들이 공유 디렉토리에 접근할 수 있도록 설정

 - 로컬 디렉토리처럼 사용

 

아키텍처

 

 

 


nfs.yml 파일 생성


  1 ---
  2 - name: Setup for nfs server
  3   gather_facts: no
  4   hosts: localhost
  5
  6   tasks:
  7     - name: make nfs_shared directory
  8       file:
  9         path: /home/vagrant/nfs_shared
 10         state: directory
 11         mode: 0777
 12
 13     - name: configure /etc/exports
 14       become: yes
 15       lineinfile:
 16         path: /etc/exports
 17         line: /home/vagrant/nfs_shared 172.30.1.0/24(rw,sync)
 18
 19     - name: nfs service restart
 20       become: yes
 21       service:
 22         name: nfs
 23         state: restarted
 24
 25
 26 - name: Setup for nfs clients
 27   gather_facts: no
 28   hosts: CentOS
 29
 30   tasks:
 31     - name: make nfs_client directory
 32       file:
 33         path: /home/vagrant/nfs
 34         state: directory
 35
 36     - name: mount point directory as client
 37       become: yes
 38       mount:
 39         name: /home/vagrant/nfs
 40         src: 172.30.1.100:/home/vagrant/nfs_shared
 41         fstype: nfs
 42         opts: nfsvers=3
 43         state: mounted

 

 

nfs 서버 설정 확인


플레이북 실행 전: 설정 사항 없음

[vagrant@ansible-server ~]$ cat /etc/exports
[vagrant@ansible-server ~]$
[vagrant@ansible-server ~]$ exportfs
exportfs: could not open /var/lib/nfs/.etab.lock for locking: errno 13 (Permission denied)

 

플레이북 실행 후: 각각의 노드의 /home/vagrant/nfs 경로에 호스트 이름으로 파일 생성

# ansible-node01
PS C:\HashiCorp\udemy-ansible> vagrant ssh ansible-node01
[vagrant@ansible-node01 ~]$ ls
nfs
[vagrant@ansible-node01 ~]$ cd nfs
[vagrant@ansible-node01 nfs]$ ls
[vagrant@ansible-node01 nfs]$ touch $HOSTNAME
[vagrant@ansible-node01 nfs]$ ls
ansible-node01

# ansible-node02
PS C:\HashiCorp\udemy-ansible> vagrant ssh ansible-node02
[vagrant@ansible-node02 ~]$ ls
nfs
[vagrant@ansible-node02 ~]$ cd nfs
[vagrant@ansible-node02 nfs]$ ls
ansible-node01
[vagrant@ansible-node02 nfs]$ touch $HOSTNAME
[vagrant@ansible-node02 nfs]$ ls
ansible-node01  ansible-node02

 

앤서블 서버의 공유 디렉토리에 마운트 확인: 앤서블 서버의 nfs 공유 디렉토리에서 파일 확인

[vagrant@ansible-server nfs_shared]$ ls
ansible-node01  ansible-node02
728x90
728x90

앤서블 노드의 timezone 설정

1. timezone.yml 파일 생성

---
- name: Setup CentOS timezone
  hosts: CentOS
  gather_facts: no
  become: yes

  tasks:
    - name: set timezone to Asia/Seoul
      timezone: name=Asia/Seoul

 

2. 파일 실행

[vagrant@ansible-server ~]$ anp timezone.yml -k
SSH password:

PLAY [Setup CentOS timezone] *****************************************************************

TASK [set timezone to Asia/Seoul] ************************************************************
changed: [node01]
changed: [node02]

PLAY RECAP ***********************************************************************************
node01                     : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node02                     : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

 

3. 확인

- 이 때, 앤서블 서버의 timezone은 변경되지 않음

- 앤서블 노드의 timezone만 변경된 것을 확인할 수 있음

# ansible-node01의 timezone
[vagrant@ansible-server ~]$ ssh vagrant@172.30.1.110
vagrant@172.30.1.110's password:
Last login: Wed Jun  8 19:45:46 2022 from 172.30.1.100

[vagrant@ansible-node01 ~]$ date
Wed Jun  8 19:46:59 KST 2022

# ansible-node02의 timezone
[vagrant@ansible-server ~]$ ssh vagrant@172.30.1.120
vagrant@172.30.1.120's password:
Last login: Wed Jun  8 19:45:46 2022 from 172.30.1.100

[vagrant@ansible-node02 ~]$ date
Wed Jun  8 19:57:56 KST 2022

 

 

앤서블 서버의 timezone 설정

# timezone 변경 전
[vagrant@ansible-server ~]$ date
Wed Jun  8 10:45:49 UTC 2022

[vagrant@ansible-server ~]$ sudo ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime

# timezone 변경 후
[vagrant@ansible-server ~]$ date
Wed Jun  8 19:50:08 KST 2022

 

 

728x90
728x90

실습 과정

- 앤서블 서버에서 작업

1. 설치 (nginx_install.yml)

2. 파일 전송

3. 서비스 재시작

4. 삭제 (nginx_remove.yml)

 

앤서블 서버에서 nginx_install.yml 파일 생성

  1 ---
  2 - name: Install nginx on CentOS
  3   hosts: CentOS # node01, node02를 지칭함
  4   gather_facts: no
  5   become: yes # root 권한 부여
  6
  7   tasks:
  8     - name: install epel-release
  9       yum: name=epel-release state=latest
 10     - name: install nginx web server
 11       yum: name=nginx state=present
 12     - name: Upload default index.html for web server
 13       get_url: url=https://www.nginx.com dest=/usr/share/nginx/html/ mode=0644
 14     - name: Start nginx web server
 15       service: name=nginx state=started

 

앤서블 서버에서 nginx_remove.yml 파일 생성

  1 ---
  2 - name: Remove nginx on CentOS
  3   hosts: CentOS # node01, node02를 지칭함
  4   gather_facts: no
  5   become: yes # root 권한 부여
  6
  7   tasks:
  8     - name: remove epel-release
  9       yum: name=epel-release state=absent
 10     - name: remove nginx web server
 11       yum: name=nginx state=absent

 

플레이북을 이용해 각각의 노드에 nginx 설치

[vagrant@ansible-server ~]$ anp nginx_install.yml -k
SSH password: # vagrant

PLAY [Install nginx on CentOS] ***************************************************************

TASK [install epel-release] ******************************************************************
changed: [node02]
changed: [node01]

TASK [install nginx web server] **************************************************************
changed: [node01]
changed: [node02]

TASK [Upload default index.html for web server] **********************************************
changed: [node01]
changed: [node02]

TASK [Start nginx web server] ****************************************************************
changed: [node02]
changed: [node01]

PLAY RECAP ***********************************************************************************
node01                     : ok=4    changed=4    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node02                     : ok=4    changed=4    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

 

웹 브라우저에서 노드의 IP 주소로 접속하여 nginx 기본 페이지 확인

 

 

nginx 삭제

[vagrant@ansible-server ~]$ anp nginx_remove.yml -k
SSH password: # vagrant

PLAY [Remove nginx on CentOS] ****************************************************************

TASK [remove epel-release] *******************************************************************
changed: [node01]
changed: [node02]

TASK [remove nginx web server] ***************************************************************
changed: [node02]
changed: [node01]

PLAY RECAP ***********************************************************************************
node01                     : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node02                     : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

 

728x90
728x90

/etc/ssh/sshd_config 파일 설정


SSH 접속이 가능하도록 설정

- /etc/ssh/sshd_config 파일의 PasswordAuthentication no 를 yes로 변경

 

현재 SSH 접속이 안 됨

 

파일 수정 방법

1. 앤서블 플레이북

2. 배시 쉘 프로그래밍

 

앤서블 플레이북을 이용하여 SSH 접속 설정


Vagrantfile

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant_API_Version = "2"

Vagrant.configure(Vagrant_API_Version) do |config|

  # Ansible-Node01
  	config.vm.define:"ansible-node01" do |cfg|
		cfg.vm.box = "centos/7"
		cfg.vm.provider:virtualbox do |vb|
			vb.name = "Ansible-Node01"
      		vb.customize ["modifyvm", :id, "--cpus",1]
      		vb.customize ["modifyvm", :id, "--memory",512]
		end
		cfg.vm.host_name = "ansible-node01"
		cfg.vm.synced_folder ".", "/vagrant", disabled: true
		cfg.vm.network "public_network", ip: "172.30.1.110"
		cfg.vm.network "forwarded_port", guest: 22, host: 19211, auto_correct: false, id: "ssh"
    	cfg.vm.provision "shell", path: "bash_ssh_conf_4_CentOS.sh"
		
	end
  
  # Ansible-Node02
  	config.vm.define:"ansible-node02" do |cfg|
		cfg.vm.box = "centos/7"
		cfg.vm.provider:virtualbox do |vb|
			vb.name = "Ansible-Node02"
      		vb.customize ["modifyvm", :id, "--cpus",1]
      		vb.customize ["modifyvm", :id, "--memory",512]
		end
		cfg.vm.host_name = "ansible-node02"
		cfg.vm.synced_folder ".", "/vagrant", disabled: true
		cfg.vm.network "public_network", ip: "172.30.1.120"
		cfg.vm.network "forwarded_port", guest: 22, host: 19212, auto_correct: false, id: "ssh"
    	cfg.vm.provision "shell", path: "bash_ssh_conf_4_CentOS.sh"
		
	end  
  
  
  
  # Ansible-Server
	config.vm.define:"ansible-server" do |cfg|
		cfg.vm.box = "centos/7"
		cfg.vm.provider:virtualbox do |vb|
			vb.name = "Ansible-Server"
		end
		cfg.vm.host_name = "ansible-server"
		cfg.vm.synced_folder ".", "/vagrant", disabled: true
		cfg.vm.network "public_network", ip: "172.30.1.100"
		cfg.vm.network "forwarded_port", guest: 22, host: 19210, auto_correct: false, id: "ssh"
		cfg.vm.provision "shell", path: "bootstrap.sh"
		cfg.vm.provision "file", source: "Ansible_env_ready.yml", destination: "Ansible_env_ready.yml"
		cfg.vm.provision "shell", inline: "ansible-playbook Ansible_env_ready.yml"
    	cfg.vm.provision "shell", path: "add_ssh_auth.sh", privileged: false
    	cfg.vm.provision "file", source: "Ansible_ssh_conf_4_CentOS.yml", destination: "Ansible_ssh_conf_4_CentOS.yml"
		cfg.vm.provision "shell", inline: "ansible-playbook Ansible_ssh_conf_4_CentOS.yml"
	end
  
end

 

bash_ssh_conf_4_CentOS.sh

#! /usr/bin/env bash

now=$(data +"%m_%d_%Y")
cp /etc/ssh/sshd_config /etc/ssh/sshd_config_$now.backup
sed -i -e 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
systemctl restart sshd

 

 

Ansible_ssh_conf_4_CentOS.yml

---
- name: Ansible_ssh_conf_4_CentOS
  hosts: localhost
  gather_facts: no
  
  tasks:
    - name: PasswordAuthentication change from no to yes
      replace:
        dest: /etc/ssh/sshd_config
        regexp: 'PasswordAuthentication no'
        replace: 'PasswordAuthentication yes'
        backup: yes
        
    - name: sshd restart to apply "PasswordAuthentication"
      service:
        name: sshd
        state: restarted

 

vagrant provision

ansible-server로 접속하여 통신 확인

SSH password: vagrant

 

설정 파일이 실제로 수정되었는지 확인: yes로 수정된 것을 확인할 수 있음

/etc/ssh/sshd_cofig

 

 

728x90
728x90

실습 개요


아키텍처

- Ansible-Server (control-node): 1대

- Ansible-Nodes (host-node): 2대

 

 

 

Vagrantfile 구성

1. 앤서블 노드 2개를 CentOS를 이용하여 구성

2. 기존과 동일한 방법으로 구성 파일 작성

  1) 베이그런트에서 인식하는 호스트 이름 지정

  2) 버추얼박스 설정 변경

    - 버추얼박스에서 구분하는 호스트 이름 지정

    - CPU와 메모리를 최소한으로 사용하도록 변경

  3) 가상 머신의 호스트 이름 변경

  4) 호스트 PC와 가상 머신의 공유 디렉토리 사용 X

  5) 인터넷에 연결되는 IP 설정

  6) 호스트 PC의 포트를 IP 주소와 유사하게 변경

  7) 앤서블 서버에서 add_ssh_auth.sh 실행

 

 

Ansible_env_ready.yml 구성

1. /etc/hosts에 서버와 노드 등록2. /etc/ansible/hosts에 앤서블을 통해 관리할 노드 등록3. yum을 통해서 앤서블 서버에 sshpass 설치

 

 

add_ssh_auth.sh 구성

1. sshpass를 이용해 앤서블 서버에 앤서블 노드의 ssh_key 등록2. 해당 파일의 목적: 노드의 ssh 키를 non-host에 등록하기 위함

 


Vagrantfile 구성


# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant_API_Version = "2"

Vagrant.configure(Vagrant_API_Version) do |config|

  # Ansible-Node01
  config.vm.define:"ansible-node01" do |cfg|
		cfg.vm.box = "centos/7"
		cfg.vm.provider:virtualbox do |vb|
			vb.name = "Ansible-Node01"
      vb.customize ["modifyvm", :id, "--cpus",1]
      vb.customize ["modifyvm", :id, "--memory",512]
		end
		cfg.vm.host_name = "ansible-node01"
		cfg.vm.synced_folder ".", "/vagrant", disabled: true
		cfg.vm.network "public_network", ip: "172.30.1.110"
		cfg.vm.network "forwarded_port", guest: 22, host: 19211, auto_correct: false, id: "ssh"
		
	end
  
  # Ansible-Node02
  config.vm.define:"ansible-node02" do |cfg|
		cfg.vm.box = "centos/7"
		cfg.vm.provider:virtualbox do |vb|
			vb.name = "Ansible-Node02"
      vb.customize ["modifyvm", :id, "--cpus",1]
      vb.customize ["modifyvm", :id, "--memory",512]
		end
		cfg.vm.host_name = "ansible-node02"
		cfg.vm.synced_folder ".", "/vagrant", disabled: true
		cfg.vm.network "public_network", ip: "172.30.1.120"
		cfg.vm.network "forwarded_port", guest: 22, host: 19212, auto_correct: false, id: "ssh"
		
	end  
  
  
  
  # Ansible-Server
	config.vm.define:"ansible-server" do |cfg|
		cfg.vm.box = "centos/7"
		cfg.vm.provider:virtualbox do |vb|
			vb.name = "Ansible-Server"
		end
		cfg.vm.host_name = "ansible-server"
		cfg.vm.synced_folder ".", "/vagrant", disabled: true
		cfg.vm.network "public_network", ip: "172.30.1.100"
		cfg.vm.network "forwarded_port", guest: 22, host: 19210, auto_correct: false, id: "ssh"
		cfg.vm.provision "shell", path: "bootstrap.sh"
		cfg.vm.provision "file", source: "Ansible_env_ready.yml", destination: "Ansible_env_ready.yml"
		cfg.vm.provision "shell", inline: "ansible-playbook Ansible_env_ready.yml"
    cfg.vm.provision "shell", path: "add_ssh_auth.sh", privileged: false
	end
  
end

 

 

 

Ansible_env_ready.yml 구성


blockinfile: 블록 단위로 수정, 파이프( | )를 필수로 입력

---
- name: Setup for the Ansible's Environment
  hosts: localhost
  gather_facts: no
  
  tasks:
  
    - name: Add "/etc/hosts"
      blockinfile:  |
        path=/etc/hosts
        content="
          172.30.1.100  server
          172.30.1.110  node01
          172.30.1.120  node02"
          
    - name: Add "/etc/ansible/hosts"
      blockinfile:  |
        path=/etc/ansible/hosts
        content="
          [CentOS]
            node01
            node02"
            
    - name: Install sshpass for Authentication
      yum:
        name: sshpass
        state:  present
          
 
    - name: Install vim-enhanced
      yum:
        name: vim-enhanced
        state: present
        
    - name: Install git
      yum:
        name: git
        state: present

    - name: Download pathogen.vim
      shell: "curl -fLo /home/vagrant/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim"

    - name: Git clone vim-ansible-yaml
      git:
        repo: 'https://github.com/chase/vim-ansible-yaml.git'
        dest: /home/vagrant/.vim/bundle/vim-ansible-yaml

    - name: Configure vimrc
      lineinfile:
        path: /home/vagrant/.vimrc
        line: "{{ item }}"
      with_items:
        - "set number"
        - "execute pathogen#infect()"
        - "syntax on"

    - name: Configure Bashrc
      lineinfile:
        path: /home/vagrant/.bashrc
        line: "{{ item }}"
      with_items:
        - "alias vi='vim'"
        - "alias ans='ansible'"
        - "alias anp='ansible-playbook'"

 

add_ssh_auth.sh 구성


 

StrictHostKeyChecking=no: ssh 접속 시 ssh 키 확인 경고창을 확인하지 않겠다는 옵션

#! /usr/bin/env bash

# ssh key 생성
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@node01
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@node02

 

 

vagrant up


기존의 앤서블 서버 삭제 후 진행

PS C:\HashiCorp\udemy-ansible> vagrant destroy ansible-server
    ansible-server: Are you sure you want to destroy the 'ansible-server' VM? [y/N] y
    
PS C:\HashiCorp\udemy-ansible> vagrant up

 

구성 완료

 

적용 사항 확인

# 노드 정보 확인
[vagrant@ansible-server ~]$ cat .ssh/known_hosts
node01,172.30.1.110 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBP5AG7RgArSxOru587iWE6EpQtq5AnVf/zkMng3s8CqEq8+SSzPTuroQylfCkIIun8tiErQtF5HbCjqqpuWCKV4=
node02,172.30.1.120 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLUjlCIUB5zGlm9CD240edVQUendXDjzjMSdl8sFie6Cy552TVXeBCTVwgGbCVeOEm8XzrdSpj2Tq1G4Hv3JF2E=

# 앤서블에서 관리하는 블록 정보 확인
[vagrant@ansible-server ~]$ cat .ssh/known_hosts
# BEGIN ANSIBLE MANAGED BLOCK

  172.30.1.100  server
  172.30.1.110  node01
  172.30.1.120  node02
# END ANSIBLE MANAGED BLOCK

[vagrant@ansible-server ~]$ cat /etc/ansible/hosts
# BEGIN ANSIBLE MANAGED BLOCK

  [CentOS]
    node01
    node02
# END ANSIBLE MANAGED BLOCK

 

앤서블 서버와 노드 간의 통신 확인

[vagrant@ansible-server ~]$ ans all -m ping -k
SSH password:
node01 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).",
    "unreachable": true
}
node02 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).",
    "unreachable": true

 

728x90
728x90

플레이북 환경 설정


 

Vagrantfile

1. Ansible_env_ready.yml 파일을 앤서블 서버로 전달

2. Ansible_env_ready.yml 파일을 앤서블 서버에서 실행

 

# -*- mode: ruby -*-
# vi: set ft=ruby :
# API 버전 명시
Vagrant_API_Version = "2"

Vagrant.configure(Vagrant_API_Version) do |config|
	config.vm.define:"ansible-server" do |cfg|
		cfg.vm.box = "centos/7"
		cfg.vm.provider:virtualbox do |vb|
			vb.name = "Ansible-Server"
		end
		cfg.vm.host_name = "ansible-server"
		cfg.vm.synced_folder ".", "/vagrant", disabled: true
		cfg.vm.network "public_network", ip: "172.30.1.100"
		cfg.vm.network "forwarded_port", guest: 22, host: 19210, auto_correct: false, id: "ssh"
		# path 옵션: 해당 파일을 전송하고 실행하는 것을 포함
        cfg.vm.provision "shell", path: "bootstrap.sh"
        # 앤서블 환경 준비 파일을 현재 디렉토리에서 원격지의 디렉토리로 전달
		cfg.vm.provision "file", source: "Ansible_env_ready.yml", destination: "Ansible_env_ready.yml"
		# inline 옵션: 실행만을 포함
        # ansible-playbook Ansible_env_ready.yml 명령어를 호출함
        cfg.vm.provision "shell", inline: "ansible-playbook Ansible_env_ready.yml"
	end
  
end

 

bootstarp.sh

1. vim plugin 관련 파일이 저장될 디렉토리 생성

  - /home/vagrant/.vim/autoload

  - /home/vagrant/.vim/bundle

2. vim과 bash의 환경 설정 파일 생성

 

#! /usr/bin/env bash

# 앤서블 설치
yum install -y epel-release
yum install -y ansible

# 환경 설정 초기 파일 구성 for vagrant only
mkdir -p /home/vagrant/.vim/autoload /home/vagrant/.vim/bundle
touch /home/vagrant/.vimrc
touch /home/vagrant/.bashrc

 

Ansible_env_ready.yml (앤서블 환경 준비 파일)

Ansible_env_ready.yml 파일 생성 후 저장

 

1. yum을 통한 vim-enhanced 설치

2. yum을 통한 git 설치

3. pathogen.vim 다운로드 (https://github.com/tpope/vim-pathogen)

4. vim-ansible-yaml을 git clone을 통해 다운로드

5. vim 환경 설정 수정 (vimrc)

6. Bash 환경 설정 수정 (bashrc)

 

---
- name: Setup for the Ansible's Environment
  hosts: localhost
  gather_facts: no
  
  tasks:
    - name: Install vim-enhanced
      yum:
        name: vim-enhanced
        state: present
        
    - name: Install git
      yum:
        name: git
        state: present

    - name: Download pathogen.vim
      shell: "curl -fLo /home/vagrant/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim"

    - name: Git clone vim-ansible-yaml
      git:
        repo: 'https://github.com/chase/vim-ansible-yaml.git'
        dest: /home/vagrant/.vim/bundle/vim-ansible-yaml

    - name: Configure vimrc
      lineinfile:
        dest: /home/vagrant/.vimrc
        line: "{{ item }}"
      with_items:
        - "set number"
        - "execute pathogen#infect()"
        - "syntax on"

    - name: Configure Bashrc
      lineinfile:
        dest: /home/vagrant/.bashrc
        line: "{{ item }}"
      with_items:
        - "alias vi='vim'"	# 주의: alias vi = 'vim' 과 같이 공백이 있으면 안됨
        - "alias ans='ansible'"
        - "alias anp='ansible-playbook'"

 

vagrant provision

현재 실행 중인 가상 머신에 변경 사항 적용

PS C:\HashiCorp> vagrant provision ansible-server

728x90
728x90

Vagrantfile 수정 및 bootstrap.sh 생성


Vagrantfile

1. 베이그런트에서 부르는 호스트 이름 작성

2. 버추얼박스에서 구분하는 호스트 이름 작성

3. 가상 머신의 호스트 이름 변경

4. 호스트 PC와 가상 머신 간에 공유 디렉토리는 사용하지 않음

5. 가상 머신에서 인터넷으로 연결되는 IP 설정

6. 호스트 PC의 포트를 IP 주소와 유사하게 변경

 

 

Vagrant.configure("2") do |config|
	# 1. 베이그런트에서 ssh 연결 시 사용할 호스트 이름
	config.vm.define:"ansible-server" do |cfg|
    	# 가상 머신에 import할 이미지
		cfg.vm.box = "centos/7"
        # 버추얼 박스에서 가상 머신 생성
		cfg.vm.provider:virtualbox do |vb|
        	# 2. 생성할 가상 머신의 이름
			vb.name = "Ansible-Server"
		end
        # 3. hostname 명령어 입력 시 출력되는 값
		cfg.vm.host_name = "ansible-server"
        # 4. 윈도우 호스트와 가상 머신 사이의 공유 디렉토리를 사용하지 않도록 설정
		cfg.vm.synced_folder ".", "/vagrant", disabled: true
        # 5. 인터넷 연결을 위한 설정 (public_network = 브릿지 네트워크, 호스트 PC의 IP 주소 확인 필요)
		cfg.vm.network "public_network", ip: "172.30.1.100"
		cfg.vm.network "forwarded_port", guest: 22, host: 19210, auto_correct: false, id: "ssh"
        # shell을 호출하여 bootstrap.sh 파일을 실행함
		cfg.vm.provision "shell", path: "bootstrap.sh"
	end
  
end

 

bootstrap.sh

1. YUM을 통한 EPEL 설치

2. YUM을 통한 ANSIBLE 설치

 

새 파일 생성

아래 명령어 입력

#! /usr/bin/env bash

yum install -y epel-release
yum install -y ansible

 

"bootstrap.sh" 이름으로 파일 저장

 

 

vagrant up

기존의 가상 머신을 삭제하고 작업 진행

PS C:\HashiCorp> vagrant up

 

에러 발생: umount: /mnt: not mounted

해결

PS C:\HashiCorp> vagrant plugin uninstall vagrant-vbguest
PS C:\HashiCorp> vagrant plugin install vagrant-vbguest --plugin-version 0.21

 

 

vagrant ssh

생성된 가상 머신에 접속

PS C:\HashiCorp> vagrant ssh ansible-server
[vagrant@ansible-server ~]$

 

설정된 IP 확인

[vagrant@ansible-server ~]$ ip add
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 52:54:00:4d:77:d3 brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global noprefixroute dynamic eth0
       valid_lft 86219sec preferred_lft 86219sec
    inet6 fe80::5054:ff:fe4d:77d3/64 scope link
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:f3:77:c3 brd ff:ff:ff:ff:ff:ff
    inet 172.30.1.100/24 brd 172.30.1.255 scope global noprefixroute eth1
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fef3:77c3/64 scope link
       valid_lft forever preferred_lft forever

 

ansible 설치 확인

[vagrant@ansible-server ~]$ ansible
usage: ansible [-h] [--version] [-v] [-b] [--become-method BECOME_METHOD]
               [--become-user BECOME_USER] [-K] [-i INVENTORY] [--list-hosts]
               [-l SUBSET] [-P POLL_INTERVAL] [-B SECONDS] [-o] [-t TREE] [-k]
               [--private-key PRIVATE_KEY_FILE] [-u REMOTE_USER]
               [-c CONNECTION] [-T TIMEOUT]
               [--ssh-common-args SSH_COMMON_ARGS]
               [--sftp-extra-args SFTP_EXTRA_ARGS]
               [--scp-extra-args SCP_EXTRA_ARGS]
               [--ssh-extra-args SSH_EXTRA_ARGS] [-C] [--syntax-check] [-D]
               [-e EXTRA_VARS] [--vault-id VAULT_IDS]
               [--ask-vault-pass | --vault-password-file VAULT_PASSWORD_FILES]
               [-f FORKS] [-M MODULE_PATH] [--playbook-dir BASEDIR]
               [-a MODULE_ARGS] [-m MODULE_NAME]
               pattern
ansible: error: too few arguments

 

728x90

+ Recent posts