0803-docker,ansible,ansible

hyejin·2022년 8월 3일
0

SAA

one zone IA - 비용성 효율, 가용성 ↓

Ansible

인스턴스 생성

  • 이름 : ansible-server
  • 키 : docker-key
  • VPC : MY-VPC
  • 서브넷 : MYPUBLICSUBNET2A
  • 보안그룹 : dev-sg
  • 사용자데이터
#!/bin/bash
timedatectl set-timezone Asia/Seoul
hostnamectl set-hostname ansible-server
amazon-linux-extras install -y ansible2
amazon-linux-extras install docker -y
systemctl enable --now docker
curl https://raw.githubusercontent.com/docker/docker-ce/master/components/cli/contrib/completion/bash/docker -o /etc/bash_completion.d/docker.sh
usermod -a -G docker ec2-user

레코드 생성

  • ansible.hyejin36.shop으로 생성

암호방식으로 접속하기

sudo passwd ec2-user
sudo vi /etc/ssh/sshd_config
PasswordAuthentication yes
#PermitEmptyPasswords no
#PasswordAuthentication no
sudo systemctl restart sshd

ansible docker 통신

  • ansible
vi /etc/ansible/hosts
10.24.42.4        //docker ip 추가
// m은 모듈, 모듈 ping 사용, 
[ec2-user@ansible-server ~]$ ansible all -m ping
The authenticity of host '10.24.42.4 (10.24.42.4)' can't be established.
ECDSA key fingerprint is SHA256:RVLB6etDd7ZVbTmFoGfXrJvp33++L+GaqW8PXAqpSts.
ECDSA key fingerprint is MD5:1a:48:50:0a:a5:16:1e:a9:d7:ec:0c:a7:20:e2:af:12.
Are you sure you want to continue connecting (yes/no)? yes
10.24.42.4 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Warning: Permanently added '10.24.42.4' (ECDSA) to the list of known hosts.\r\nPermission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",
    "unreachable": true
} 

-> 키 x, 암호 x => -k(ask,passwd 묻는거)

[ec2-user@ansible-server ~]$ ansible all -m ping -k
SSH password:
[WARNING]: Platform linux on host 10.24.42.4 is using the discovered Python interpreter at /usr/bin/python, but future
installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
10.24.42.4 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

-> 암호방식 말고 키 방식으로

[ec2-user@ansible-server ~]$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ec2-user/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/ec2-user/.ssh/id_rsa.
Your public key has been saved in /home/ec2-user/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:KX5iETYHVw7vVk5F1b0Mdd/BbQ4unk3A1wKuVPVj2TM ec2-user@ansible-server
The key's randomart image is:
+---[RSA 2048]----+
|      . o...o+*=*|
|       o + ooo+o&|
|      + . + ++oE*|
|     . + + =. +o=|
|      o S +..=   |
|     . o .  o .  |
|      + .        |
|     . o         |
|                 |
+----[SHA256]-----+

[ec2-user@ansible-server ~]$ ssh-copy-id 10.24.42.4 //ansible을 이용해서 docker로 전송 가능
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/ec2-user/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
ec2-user@10.24.42.4's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '10.24.42.4'"
and check to make sure that only the key(s) you wanted were added.
  • command 방식 사용
[ec2-user@ansible-server ~]$ ansible all -m command -a uptime
[WARNING]: Platform linux on host 10.24.42.4 is using the discovered Python interpreter at /usr/bin/python, but future
installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
10.24.42.4 | CHANGED | rc=0 >>
 10:39:19 up 51 min,  2 users,  load average: 0.00, 0.00, 0.00
[ec2-user@ansible-server ~]$ ansible all -m command -a "docker ps -a"
[WARNING]: Platform linux on host 10.24.42.4 is using the discovered Python interpreter at /usr/bin/python, but future
installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
10.24.42.4 | CHANGED | rc=0 >>
CONTAINER ID   IMAGE                 COMMAND             CREATED       STATUS                     PORTS     NAMES
f7f792a82c9d   seoes/mytomcat:v1.0   "catalina.sh run"   9 hours ago   Exited (143) 9 hours ago             docker-container
$ sudo mkdir /opt/docker
$ sudo chown -R ec2-user:ec2-user /opt/docker/ #jenkins가 ansible을 달고 들어옴, ansible이 docker파일을 이용할거임=> 권한 필요
$ cd /opt/docker/  #여기에 저장될거임
  • jenkins가 ssh를 통해 ansible에 들어갈 수 있도록
  • jenkins 접속 (jenkins.hyejin36.shop) SSH 설정
  • jenkins 관리 > 시스템 설정 > SSH Servers
    • Name : ansible-server
    • hostname : ansible.hyejin36.shop
    • username : ec2-user
    • Use password authentication, or use a different key 체크
    • Passphrase / Password : kosa0401

새 아이템

  • name : Copy_Artifacts_onto_Ansible
  • Copy from : BuildAndDeployOnContainer
  • Git Repository URL : https://github.com/seo369/hello-world.git
  • Poll SCM 체크해제
  • 빌드 후 조치 : ansible-server
    • exec command 지우기
$ docker build -t seozzang3/mytomcat:v1.0 .
$ docker images
$ docker run -d -p 8080:8080 --name test-container seozzang3/mytomcat:v1.0
$ docker rm -f test-container
$ docker rmi -f 아이디//docke images 삭제 , 컨테이너 먼저 삭제하고 이미지 삭제해야함
  • ansible.hyejin36.shop:8080/webapp/ 접속
sudo vi /etc/ansible/hosts
[docker-host]   //docker ip
10.24.42.4

[ansible-server]  //ansible ip
10.24.5.15

[ec2-user@ansible-server docker]$ ssh-copy-id 10.24.5.15  
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/ec2-user/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
ec2-user@10.24.5.15's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '10.24.5.15'"
and check to make sure that only the key(s) you wanted were added.
vi build.yml
- hosts: ansible-server

  tasks:
  - name: create docker image
    command: docker build -t halilinux/mytomcat:v1.0 .
    args:
      chdir: /opt/docker

  - name: push docker image
    command: docker push halilinux/mytomcat:v1.0
ansible-playbook build.yml
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details

PLAY [ansible-server] ***************************************************************************************************

TASK [Gathering Facts] **************************************************************************************************
[WARNING]: Platform linux on host 10.24.5.15 is using the discovered Python interpreter at /usr/bin/python, but future
installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
ok: [10.24.5.15]

TASK [create docker image] **********************************************************************************************
changed: [10.24.5.15]

TASK [push docker image] ************************************************************************************************
changed: [10.24.5.15]

PLAY RECAP **************************************************************************************************************
10.24.5.15                 : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

[ec2-user@ansible-server docker]$ docker images
REPOSITORY           TAG       IMAGE ID       CREATED         SIZE
seozzang3/mytomcat   v1.0      72e020f857d6   4 minutes ago   502MB
tomcat               9         07bcfa45c644   5 days ago      496MB

프로젝트 > 구성 > 빌드 후 조치 > exec command

cd /opt/docker;
ansible-playbook build.yml

-> 지금빌드


-> a few minute ago로 바뀌어있으면 잘된것

vi deploy.yml
- hosts: docker-host

  tasks:
  - name: remove container
    command: docker rm -f docker-container
  - name: remove image
    command: docker rmi -f seozzang3/mytomcat:v1.0
  - name: create container
    command: docker run -d -p 8080:8080 --name docker-container seozzang3/mytomcat:v1.0
    
[ec2-user@ansible-server docker]$ ansible-playbook deploy.yml
  • docker.hyejin36.shop:8080/webapp 접속

  • docker 가서 컨테이너 삭제하면 안뜸
    -> 다시 ansible 가서 playbook 실행하고 확인하기

[ec2-user@docker-host ~]$ docker ps
CONTAINER ID   IMAGE                     COMMAND             CREATED              STATUS              PORTS                                       NAMES
fabb4f34e5e6   seozzang3/mytomcat:v1.0   "catalina.sh run"   About a minute ago   Up About a minute   0.0.0.0:8080->8080/tcp, :::8080->8080/tcp   docker-container
[ec2-user@docker-host ~]$ docker rm -f docker-container
docker-container
  • 프로젝트 > 구성 > 빌드유발
  • Poll SCM : * * * * * 추가
  • exec command
cd /opt/docker;
ansible-playbook build.yml;
sleep 10;   # 동시에 playbook 실행되지 않도록.
ansible-playbook deploy.yml

-> 지금빌드

검증(소스코드 변경)

git clone https://github.com/seo369/hello-world.git
cd hello-world/
cd webapp/src/main/webapp/
vi index.jsp
git add .
git commit -m "edit index.jsp"
git push origin master

0개의 댓글

관련 채용 정보