220707

HyeonKi Jo·2022년 7월 7일
0

복습

앤서블의 애드혹(Ad-Hoc)

vi /etc/ansible/hosts

[centos]
192.168.0.254
192.168.0.255

[ubuntu]
192.168.0.204
192.168.1.2

ping

  • ansible all -m ping : 모든 서버가 작동되는지 ping
  • ansible all -m ping -k: 비밀번호를 입력해서 ping 작동
  • ansible centos -m ping -k: centos 호스트그룹만 ping
  • ansible ubuntu -m ping -k: ubuntu 호스트그룹만

Centos 아파치 애드혹

  • ansible centos 192.168.0.140 -m yum -a "name=httpd state=present" -k : yum 모듈로 httpd를 present(설치, install)
  • curl https://www.nginx.com/ -o index.html
  • ansible centos -m copy -a "src=index.html dest=/var/www/html/index.html" -k: centos 그룹에 cp명령어 index.html을 /var/www/html/index.html로
  • ansible centos -m service -a "name=httpd state=started" -k
  • ansible centos -m shell -a "systemctl status firewalld" -k
  • ansible centos -m shell -a "systemctl start firewalld" -k
  • ansible centos -m shell -a "firewall-cmd --permanent --zone=public --add-service=http" -k
  • ansible centos -m shell -a "firewall-cmd --reload" -k
  • ansible centos -m service -a "name=httpd state=stopped" -k
  • ansible centos -m shell -a "systemctl stop firewalld" -k
  • ansible centos -m yum -a "name=httpd state=absent" -k

SSH KEY 활용

  • ssh-keygen -t rsa : ansible서버에서 key를 생성
  • ssh-copy-id root@192.168.0.140: 각서버에 key를 옮겨준다.
  • ssh-copy-id root@192.168.0.143
  • 이 작업을 거치면 -k 옵션을 거치지 않아도 된다.

Centos, Ubuntu 아파치 설치 플레이북

- name: Install apache on centos
  hosts: centos
  gather_facts: no

  tasks:
    - name: install apache web server
      yum: name=httpd state=present # ansible centos -m yum -a "name=httpd state=present" -k
    - name: upload default index.html for web server
      get_url: url=https://www.nginx.com dest=/var/www/html/ mode=0644
    - name: start apache web server
      service: name=httpd state=started enabled=yes

- name: Install apache on ubuntu
  hosts: ubuntu
  gather_facts: no

  tasks:
    - name: install apache web server
      apt: name=apache2 state=present
    - name: upload default index.html for web server
      get_url: url=https://www.nginx.com dest=/var/www/html/ mode=0644
    - name: start apache web server
      service: name=apache2 state=started

Ansible

Virtual Box 스냅샷 복원하기

  • Ansible-server부터 모든 nodeVM들까지 어제 생성한 스냅샷1로 복원시켜준다.

Ansible 설치

  • yum install epel-release -y: repository사용할 epel설치
  • yum --enablerepo=epel -y install ansible: epel을 사용하여, ansible설치
  • ansible --version: 설치되었는지 버전 확인, 잘 설치되었다.

Known hosts 설정

vi keyscan.yml

- name: Setup for the Ansible's Environment
  hosts: localhost			# server스스로
  gather_facts: no

  tasks:					# 작업
    - name: Generate sshkey				# 작업이름 sshkey생성
      shell: "{{ item }}"				# shell명령어, 반복문사용한다.
      with_items:						# 반복문의 내용
        - "ssh-keyscan 192.168.0.254 >> ~/.ssh/known_hosts"
        - "ssh-keyscan 192.168.0.255 >> ~/.ssh/known_hosts"
        - "ssh-keyscan 192.168.0.204 >> ~/.ssh/known_hosts"
        - "ssh-keyscan 192.168.1.2 >> ~/.ssh/known_hosts"

앤서블 환경

vi ansible_env.yaml

- name: Setup for the Ansible's Environment	# 작업할 때, 무슨작업을 하고있는지 출력되는 descript
  hosts: localhost						#hosts를 자기자신으로 한다.
  gather_facts: no						# gather_facts를 잡을 걸이냐, no == false

  tasks:								# 실제 작업
    - name: Add "/etc/ansible/hosts"	# 작업 설명
      blockinfile: 						# blockinfile 모듈을 사용한다. lineinfile은 한줄을 넣는거라면,blockinfile은 한 블록을 넣어준다.
        path: /etc/ansible/hosts		# /etc/ansible/hosts에 아래를 넣는다.
        block: |						# 블록: |은 엔터라고 생각하면 된다. 
          [centos]						# hosts를 넣어준다.
          192.168.0.254
          192.168.0.255

          [ubuntu]						# Ubuntu18버전부터는 python3를 사용해야 하기 때문에 아래 python3세팅을 걸어놓는다.
          192.168.0.204 ansible_python_interpreter=/usr/bin/python3
          192.168.1.2 ansible_python_interpreter=/usr/bin/python3

    - name: Configure Bashrc
      lineinfile:   					# lineinfile로 한줄을 파일에 입력해준다.
        path: /root/.bashrc				# /roor/.bashrc에 넣어준다.
        line: "{{ item }}"				# 반복문이다.
      with_items:						# items에 들어가있는 line들을 하나씩 실행시켜준다.
        - "alias ans='ansible'"			#alias(별칭) ansible을 ans로 사용하겠다.
        - "alias anp='ansible-playbook'"# ansible-playbook을 anp라고 사용하겠다.
  • ansible-playbook ansible_env.yml -k : 플레이북을 시작해준다.
  • 잘 진행 되었다.
  • /etc/ansible/hosts에 아래에 우리가 입력한 hosts들이 잘 들어가있다.

Keypair 생성

vi keypair_all.yml

- name: Create known_hosts between server and nodes
  hosts: all        # all host IP in inventory
  connection: local # -c option local, do all task in local, not use SSH
  serial: 1         # Do not skip any IP's, Do work all IP
  gather_facts: no

  tasks:
    - name: ssh-keyscan for known_hosts file
      command: /usr/bin/ssh-keyscan -t ecdsa {{ ansible_host }} # command is similar to shell, Do keyscan as ecdsa type all IPs (which is defined in hosts)
      register: keyscan  # register will save outputs of command module, and We can use this outputs in below

    - name: input key
      lineinfile:
        path: ~/.ssh/known_hosts
        line: "{{ item }}"
        create: yes     # if path in not exist, make the path
      with_items:
        - "{{ keyscan.stdout_lines }}"  #use keyscan outputs in register
                                        # So, we can reduce dirty outputs and write outputs in known_hosts

- name: Create authorized_keys between server and nodes
  hosts: all
  connection: local #not use SSH
  gather_facts: no
  vars:
    ansible_password: kosa0401    # Magic_varialbes

  tasks:
    - name: ssh-keygen for athorized_keys file
      openssh_keypair:
        path: ~/.ssh/id_rsa
        size: 2048
        type: rsa
        force: False    # Do not Overwrite
    - name: input key for each node
      connection: ssh  # Use SSH connection
      authorized_key:
        user: root
        state: present  # send keys to root
        key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}" #lookup: call files in ~/.ssh/id_rsa.pub

  • 에러가 출력되었다.
  • 같은 코드로 Centos7 VM들은 잘 구성이 되엇지만, Ubuntu에서는 실패했다.
  • centos그룹은 성공했다. 그러나 우분투 그룹은 안된다.
  • ...? 왜 되지??
  • 또 안된다...ㅎ
  • 일단 KEY전송에 문제가 잇으니 다음진행을 위해 KEY를 각각 보내준다.
  • ssh-copy-id root@192.168.0.204
  • ssh-copy-id root@192.168.1.2
  • ping이 잘 연결 되었다.

nginx 설치

vi nginx_install.yml

- name: install epel-release  # install package update (epel)
  hosts: centos
  gather_facts: no

  tasks:
    - name: install epel-relase
      yum:
        name: epel-release
        state: latest

    - name: install nginx web server
      yum:
        name:nginx
        statepresent  # We can write in one-line but not cool. it use `=` when in one-line

    - name: upload default index.html for web server
      get_url:
        url:httpd://www.nginx.com
        dest:/user/share/nginx/html/
        mode:0644

    - name: start nginx web server
      service:
        name:nginx
        state:started

- name: Install nginx on ubuntu
  hosts: ubuntu
  gather_facts: no

  tasks:
    - name: install nginx web server
      apt: apt=nginx state=present

    - name: Upload default index.html for web server
      get_url:
        url:https://www.nginx.com
        dest:/var/www/html/
        mode:0644
        validate_certs:no   #when getting index.html in Ubuntu, certification check  no

vi nginx_remove.yml

- name: remove nginx web server
  hosts: centos
  gather_facts: no

  tasks:
    - name: Remobe nginx on ubuntu
      yum:
        name: nginx
        state: absent  #delete

- name: Remove nginx on ubuntu
  hosts: ubuntu
  gather_facts: no

  tasks:
    - name: remove nginx web server
      apt:
        pkg: nginx*
        state: absent

  • 잘 삭제 된다.

Centos, Ubuntu NFS 설치 플레이북

vi nfs.yml

- name: Setup for nfs server
  hosts: localhost
  gather_facts: no

  tasks:
    - name: make nfs_shared directory
      file:						# directory 생성
        path: /root/nfs_shared
        state: directory
        mode: 0777

    - name: configure /etc/exports
      lineinfile:				# nfs_share를 만들어준다.
        path: /etc/exports
        line: /root/nfs_shared 192.168.0.0/20(rw,sync)

    - name: Install NFS			# NFS설치
      yum:
        name: nfs-utils
        state: present

    - name: nfs service start	#NFS 서비스 시작
      service:
        name: nfs-server
        state: restarted
        enabled: yes			# enable yes로 해준다.

- name: Setup for nfs clients	# centos 호스트 그룹에 실행한다.
  hosts: centos
  gather_facts: no

  tasks:
    - name: make nfs_client directory
      file:
        path: /root/nfs
        state: directory

    - name: Install NFS
      yum:
        name: nfs-utils
        state: present

    - name: mount point directory as client
      mount:
        path: /root/nfs
        src: 192.168.0.192:/root/nfs_shared
        fstype: nfs
        state: mounted

- name: Setup for nfs clients U
  hosts: ubuntu
  gather_facts: no

  tasks:
    - name: make nfs_client directory
      file:
        path: /root/nfs
        state: directory

    - name: Install NFS-U
      apt:
        pkg: nfs-common
        state: present
        update_cache: yes

    - name: mount point directory as client
      mount:
        path: /root/nfs
        src: 192.168.0.192:/root/nfs_shared
        fstype: nfs
        opts: nfsvers=3
        state: mounted

NFS연결 확인

  • 초록색으로 nfs_shared 폴더가 링크되어있다.
  • 아래 test.txt를 에코 명령어로 넣어준다.
  • 다른 VM에서도 nfs폴더가 링크되어 test.txt의 내용이 잘 나온다.

Wordpress 만들기

webserver, dbserver 호스트그룹 추가해주기

		  [centos]
          192.168.0.254
          192.168.0.255

          [ubuntu]
          192.168.0.204
          192.168.1.2

          [dbserver]
          192.168.0.254

          [webserver]
          192.168.0.255
  • vi ansible_env.yml에 위 호스트그룹을 추가해준다.
  • dbserver -> Ubuntu
  • webserver -> centos로 해준다.
  • 잘 추가되었다.

vi wordpress.yml

- name: Setup for webserver
  hosts: webserver
  gather_facts: no

  tasks:
    - name: Install http
      yum:
        name: "{{ item }}"		#반복문, 아래 items들을 다 다운로드 해준다.
        state: present
      with_items:
        - httpd
        - php
        - php-mysql
        - php-gd
        - php-mbstring
        - wget
        - unzip

    - name: Unarchive a file that needs to be downloaded (added in 2.0)
      ansible.builtin.unarchive:		# 압축을 푸는 모듈
      									# archive -> 압축
                                        # unarchive -> 압축해제
        src: https://ko.wordpress.org/wordpress-4.8.2-ko_KR.zip
        dest: /var/www/html
        remote_src: yes

    - name: chown
      file:
        path: /var/www/html/wordpress
        owner: "apache"
        group: "apache"
        recurse: "yes"

    - name: web service restart
      service:
        name: httpd
        state: restarted

- name: Setup for dbserver
  hosts: dbserver
  gather_facts: no

  tasks:
    - name: Install mariadb
      apt:
        pkg: mariadb-server
        state: present
        update_cache: yes

    - name: Install pymysql
      apt:
        pkg: python-pymysql
        state: present

    - name: Install pymysql
      apt:
        pkg: python3-pymysql
        state: present

    - name: set root password
      mysql_user:
        name: 'root'
        password: '{{ mysql_root_password }}'	# 비밀번호는 입력을 받는다.
        login_unix_socket: /var/run/mysqld/mysqld.sock
        state: present

    - name: edit file
      replace:		# path의 파일에 "bind-addrss"를 찾아서 "#bind-address"로 수정해주는 모듈이다.  
        path: /etc/mysql/mariadb.conf.d/50-server.cnf
        regexp: "bind-address"
        replace: "#bind-address"

    - name: db service restart
      service:
        name: mysql
        state: restarted

    - name: Create database
      mysql_db:
        db: wordpress						# db wordpress를 생성한다. 
        login_unix_socket: /var/run/mysqld/mysqld.sock
        state: present

    - name: Create database user
      mysql_user:
        user: wpuser					# 유저 계정생성
        password: wppass
        priv: "wordpress.*:ALL,GRANT"	# wordpress db의 모든 자원을 허용
        host: '%'						 # 어디서 들어오는 연결이든 허용
        login_unix_socket: /var/run/mysqld/mysqld.sock	# socket 연결해줌
        state: present
  • ansible-playbook wordpress.yml --extra-vars "mysql_root_password=kosa0401"
    • ansible-playbook을 실행한다. 또, extra-var로, mysql root password에 kosa0401로 추가 변수를 준다.
  • 잘 설치되었다.
  • 워드프레스도 잘 접속된다. 선인장 하이~

Docker & Container

Docker 컨테이너

  • 항구에서 일하는 사람
  • Docker는 컨테이너형 가상화 기술중에 하나이다.
  • 컨테이너란, 호스트 OS상에 논리적인 구획을 만들고, 애플리케이션을 작동시키기 위해 필요한 라이브러리나 애플리케이션등을 하나로 모아, 하나의 VM처럼 사용할 수 있게 만든 것이다.
  • 매우 빨라진 도구라고 볼 수 있다.
  • 컨테이너는 오버헤드가 적기때문에 가볍고 고속으로 작동한다.
  • Docker는 어플리케이션의 실행에 필요한 환경을 하나의 이미지로 모아두고,
  • 그 이미지를 활용하여 다양한 환경에서 환경을 구축 및 운용할 수 있다.

Docker의 세가지 기능

  • Docker이미지를 만드는 기능: docker image build
  • Docker 이미지를 공유하는 기능: docker image push/pull
    • ship (선적) 이라고 한다.
  • Docker 컨테이너를 작동시키는 기능: docker container run
    • 컨테이터 배포 -> 서버(web)

Docker 아키텍처

  • Docker HOST : HostPC, 여기서 이미지 및 컨테이너를 만들어준다.
  • Client : Host에서 build, pull, run을 통해 배포를 하게 된다.
  • Registry : Docker Hub이다. 여기서 사람들이 push한 이미지들을 Pull해서 사용할 수 있다.
profile
Talking Potato

0개의 댓글