본문으로 건너뛰기

ChatGPT 잠재력 활용해 DevOps 워크플로 개선하기

Chad
· 약 23분

OpenAI에서 개발한 ChatGPT가 출시된 지 반년이 조금 지났습니다. 반년 동안 ChatGPT를 필두로 여러 인공지능(AI) 모델이 하루가 멀다하고 등장하는 중이며, 다양한 산업에서 파동을 일으키고 있습니다. 우리는 이를 견뎌내기 위해 빠르게 대처하고 있지만, 마치 빠르게 달리는 열차를 쫓는 느낌을 받습니다.

이렇게 끊임없이 학습과 적응이 필요한 상황에서, 생산성 향상을 위해 많은 사람이 ChatGPT를 사용하고 있습니다. 마케팅 팀은 ChatGPT로 새로운 인사이트를 얻고, 고객 서비스(CS) 팀은 ChatGPT를 이용하여 고객 질문에 답변을 더욱 빠르게 제공할 수 있습니다.

DevOps 엔지니어도 ChatGPT를 업무에 활용할 줄 알아야 합니다. 엔지니어는 그 누구보다도 발빠르게 새로운 기술을 학습하고 변화하는 환경에 적응해야 하기 때문입니다. ChatGPT가 바로 그 ‘새로운 기술’입니다. DevOps 엔지니어가 ChatGPT로 효율적이고, 생산적인 작업 흐름을 만들려면 어떻게 해야 할까요?

ChatGPT 사용법

ChatGPT는 전용 UI를 사용해 대화형으로 상호작용할 수도 있고, OpenAI 플랫폼에서 제공하는 API를 활용해 상호작용할 수도 있습니다. 이 글에서는 API를 사용해 ChatGPT를 활용하는 방법을 알아보겠습니다.(API의 자세한 사항은 OpenAI ChatGPT Documentation을 참조하세요.)

아래의 코드는 ChatGPT API를 사용해 코드를 생성해달라는 요청을 보내고 응답을 파일로 저장하는 간단한 Python 스크립트입니다. 메시지는 입력으로 받은 prompt 파라미터를 사용합니다. 텍스트를 제외한 format 형식의 코드만 요청하고, 응답받아 file_name 이름의 파일로 저장합니다. 모델text-davinci-003을 사용합니다.

  • code_generate.py
    • OPENAI_API_KEY: OpenAI에서 발급받은 API Key를 사용합니다.
import os
import requests
import argparse

def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--prompt", type=str, help="The prompt to send to the OpenAI API")
parser.add_argument("--format", type=str, help="file format of response from OpenAI API")
parser.add_argument("--file_name", type=str, help="Name of the file to save script")

return parser.parse_args()

def create_request_headers(api_key):
return {
"Content-Type": "application/json",
"Authorization": "Bearer " + api_key
}

def create_request_data(args):
return {
"model": "text-davinci-003",
"prompt": f"{args.prompt} in {args.format} script. Provide only code, no text",
"max_tokens": 3000,
"temperature": 0.5
}

def write_to_file(file_name, text):
with open(file_name, "w") as file:
file.write(text)

def main():
args = parse_args()

api_endpoint = "https://api.openai.com/v1/completions"
api_key = os.getenv("OPENAI_API_KEY") # User > View API Keys > Create New secret key

request_headers = create_request_headers(api_key)
request_data = create_request_data(args)

response = requests.post(api_endpoint, headers=request_headers, json=request_data)

if response.status_code == 200:
response_text = response.json()["choices"][0]["text"]
write_to_file(args.file_name, response_text)
else:
print(f"Request failed with status code: {str(response.status_code)}")

if __name__ == "__main__":
main()

아래는 두 번째 스크립트입니다. 이미 존재하는 파일이나 code_generate.py로 생성한 코드에 ChatGPT를 적용하는 Python 스크립트입니다. prompt 형식이 조금 달라진 것을 제외하면 요청 부분은 거의 비슷합니다. 또한, input, output 파라미터로 입출력 파일을 지정할 수 있습니다.

  • file_process.py
    • OPENAI_API_KEY: OpenAI에서 발급받은 API Key를 사용합니다.
import os
import requests
import argparse

def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--input', type=str, required=True, help='The input file to translate')
parser.add_argument('--output', type=str, required=True, help='The output file to save translation')
parser.add_argument("--prompt", type=str, help="The prompt to send to the OpenAI API")

return parser.parse_args()

def create_request_headers(api_key):
return {
"Content-Type": "application/json",
"Authorization": "Bearer " + api_key
}

def create_request_data(args):
with open(args.input, 'r') as file:
document = file.read()

return {
"model": "text-davinci-003",
"prompt": f"{document}\n{args.prompt} ",
"max_tokens": 3000,
"temperature": 0.5
}

def write_to_file(file_name, text):
with open(file_name, "w") as file:
file.write(text)

def main():
args = parse_args()

api_endpoint = "https://api.openai.com/v1/completions"
api_key = os.getenv("OPENAI_API_KEY")

request_headers = create_request_headers(api_key)
request_data = create_request_data(args)

response = requests.post(api_endpoint, headers=request_headers, json=request_data)

if response.status_code == 200:
response_text = response.json()["choices"][0]["text"]
write_to_file(args.output, response_text)
else:
print(f"Request failed with status code: {str(response.status_code)}")

if __name__ == "__main__":
main()

스크립트가 준비되었으니 이제 ChatGPT로 무엇을 할 수 있는지 살펴보겠습니다.

DevOps 워크플로에 ChatGPT 적용하기

1. 문서화

DevOps 팀은 많은 문서를 작성합니다. ChatGPT를 활용하면 문서화 프로세스를 자동화하여 문서를 더 빨리 만들 수 있습니다. 예를 들어, ChatGPT에 “DevOps 초급자용 튜토리얼 문서를 작성해달라”고 요청하는 상황을 가정해봅시다. 이때 “write a detailed tutorial for DevOps beginners”라는 프롬프트를 사용하고, 출력되는 파일 형식은 “markdown”으로 지정합니다. 저장될 파일 이름은 “tutorial.md”로 지정합니다. 명령어는 다음과 같습니다.

  • CLI 명령어
python3 code_genetate.py --prompt "write a detailed tutorial for devops beginners" --format "markdown" --file_name "tutorial.md"
  • 위의 결과로 아래와 같은 tutorial.md 파일이 만들어졌습니다.
# Introduction to DevOps

DevOps is a set of practices that combines software development (Dev) and IT operations (Ops). It is a culture, movement, or practice that emphasizes the collaboration and communication of both software developers and other information-technology (IT) professionals while automating the process of software delivery and infrastructure changes.

# Prerequisites

Before you get started with DevOps, you should have a basic understanding of the following:

* Linux/Unix command line
* Basic scripting (Bash, Python, etc.)
* Version control systems (Git, SVN, etc.)
* Continuous Integration/Continuous Delivery (CI/CD)
* Infrastructure as Code (IaC)

# Setting Up a DevOps Environment

## Step 1: Install a Virtual Machine

First, you will need to install a virtual machine on your computer. This will allow you to run a Linux operating system and use it to set up a DevOps environment.

### Installing VirtualBox

1. Download and install [VirtualBox](https://www.virtualbox.org/wiki/Downloads).
2. Launch the VirtualBox application.
3. Click on the “New” button in the top left corner.
4. Enter a name for your virtual machine and select the type of operating system you want to install.
5. Allocate RAM and hard disk space for the virtual machine.
6. Click on the “Create” button to finish the installation.

## Step 2: Install DevOps Tools

Once you have installed a virtual machine, you can start installing the necessary DevOps tools.

### Installing Git

1. Download and install [Git](https://git-scm.com/downloads).
2. Open a terminal window and type `git --version` to verify the installation.

### Installing Jenkins

1. Download and install [Jenkins](https://jenkins.io/download/).
2. Open a terminal window and type `java -jar jenkins.war` to start the Jenkins server.
3. Go to `http://localhost:8080` in your web browser to access the Jenkins dashboard.

### Installing Docker

1. Download and install [Docker](https://docs.docker.com/get-docker/).
2. Open a terminal window and type `docker --version` to verify the installation.

### Installing Ansible

1. Download and install [Ansible](https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html).
2. Open a terminal window and type `ansible --version` to verify the installation.

## Step 3: Configure the DevOps Environment

Once you have installed all the necessary DevOps tools, you can start configuring your environment.

### Setting Up a Git Repository

1. Create a directory for your project: `mkdir my-project`.
2. Initialize a Git repository in the directory: `git init`.
3. Add the files to the repository: `git add .`.
4. Commit the files: `git commit -m "Initial commit"`.

### Setting Up Jenkins

1. Log in to your Jenkins dashboard.
2. Create a new job for your project.
3. Configure the job to pull the code from the Git repository.
4. Set up the job to run automated tests and deployments.

### Setting Up Docker

1. Create a `Dockerfile` for your project.
2. Build the Docker image: `docker build -t my-project .`.
3. Run the Docker container: `docker run -d --name my-project my-project`.

### Setting Up Ansible

1. Create an `ansible.cfg` file for your project.
2. Create an `inventory` file to define the hosts.
3. Create a `playbook.yml` file to define the tasks.
4. Run the playbook: `ansible-playbook -i inventory playbook.yml`.

# Conclusion

By following these steps, you should now have a working DevOps environment. You can now start automating your software delivery and infrastructure changes.

2. 실시간 번역

ChatGPT는 다양한 언어를 지원합니다. 따라서, ChatGPT는 서로 다른 사일로 사이에서 지능형 중개자 역할을 할 수 있습니다. 위에서 만든 tutorial.md 파일을 한국어로 번역해 한국어용 tutorial-kr.md 파일을 만들도록 하겠습니다. 명령어는 아래와 같습니다.

  • CLI 명령어
python3 file_process.py --input tutorial.md --output tutorial-kr.md --prompt "translate the above file into Korean"
  • 위의 결과로 아래와 같은 tutorial-kr.md 파일이 만들어졌습니다.
# DevOps에 대한 소개

DevOps는 소프트웨어 개발(Dev)과 IT 운영(Ops)을 결합한 실천으로서 모두가 소프트웨어 개발자뿐만 아니라 기타 정보 기술(IT) 전문가들과의 협업과 소통을 강조하면서 소프트웨어 배포 및 인프라 변경의 프로세스를 자동화하는 문화, 운동 또는 실천입니다.

# 사전 요건

DevOps를 시작하기 전에 다음과 같은 기본 지식이 있어야 합니다.

* Linux/Unix 명령줄
* 기본 스크립팅 (Bash, Python 등)
* 버전 관리 시스템 (Git, SVN 등)
* 연속 통합/연속 배포 (CI/CD)
* 인프라를 코드로 (IaC)

# DevOps 환경 설정

## 단계 1: 가상 머신 설치

우선 가상 머신을 컴퓨터에 설치해야 합니다. 이를 통해 Linux 운영 체제를 실행하고 DevOps 환경을 설정할 수 있습니다.

### VirtualBox 설치

1. [VirtualBox](https://www.virtualbox.org/wiki/Downloads)를 다운로드하고 설치합니다.
2. VirtualBox 응용 프로그램을 실행합니다.
3. 왼쪽 상단의 “새로 만들기” 버튼을 클릭합니다.
4. 가상 머신에 대한 이름을 입력하고 설치하려는 운영 체제의 종류를 선택합니다.
5. 가상 머신에 RAM과 하드 디스크 공간을 할당합니다.
6. “만들기” 버튼을 클릭하여 설치를 완료합니다.

## 단계 2: DevOps 도구 설치

가상 머신을 설치하면 필요한 DevOps 도구를 설치할 수 있습니다.

### Git 설치

1. [Git](https://git-scm.com/downloads)을 다운로드하고 설치합니다.
2. 터미널 창을 열고 `git --version`을 입력하여 설치를 확인합니다.

### Jenkins 설치

1. [Jenkins](https://jenkins.io/download/)를 다운로드하고 설치합니다.
2. 터미널 창을 열고 `java -jar jenkins.war`을 입력하여 Jenkins 서버를 시작합니다.
3. 웹 브라우저를 열고 `http://localhost:8080`에 접속하여 Jenkins 대시보드에 접근합니다.

### Docker 설치

1. [Docker](https://docs.docker.com/get-docker/)를 다운로드하고 설치합니다.
2. 터미널 창을 열고 `docker --version`을 입력하여 설치를 확인합니다.

### Ansible 설치

1. [Ansible](https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html)을 다운로드하고 설치합니다.
2. 터미널 창을 열고 `ansible --version`을 입력하여 설치를 확인합니다.

## 단계 3: DevOps 환경 구성

필요한 모든 DevOps 도구를 설치한 후 환경을 구성할 수 있습니다.

### Git 저장소 설정

1. 프로젝트에 대한 디렉토리를 만듭니다: `mkdir my-project`.
2. 디렉토리에 Git 저장소를 초기화합니다: `git init`.
3. 파일을 저장소에 추가합니다: `git add .`.
4. 파일을 커밋합니다: `git commit -m "Initial commit"`.

### Jenkins 설정

1. Jenkins 대시보드에 로그인합니다.
2. 프로젝트에 대한 새 작업을 만듭니다.
3. 작업을 구성하여 Git 저장소에서 코드를 가져옵니다.
4. 작업을 설정하여 자동화된 테스트 및 배포를 실행합니다.

### Docker 설정

1. 프로젝트에 대한 `Dockerfile`을 만듭니다.
2. Docker 이미지를 빌드합니다: `docker build -t my-project .`.
3. Docker 컨테이너를 실행합니다: `docker run -d --name my-project my-project`.

### Ansible 설정

1. 프로젝트에 대한 `ansible.cfg` 파일을 만듭니다.
2. 호스트를 정의하기 위해 `inventory` 파일을 만듭니다.
3. 작업을 정의하기 위해 `playbook.yml` 파일을 만듭니다.
4. Playbook을 실행합니다: `ansible-playbook -i inventory playbook.yml`.

# 결론

이러한 단계를 따라하면 이제 작동하는 DevOps 환경이 완성됩니다. 이제 소프트웨어 배포 및 인프라 변경을 자동화할 수 있습니다.

3. 코드 생성

위의 내용을 기반으로 ChatGPT를 사용하여 Ansible 코드를 생성해 보겠습니다. 명령어는 다음과 같습니다.

  • CLI 명령어
python3 write_with_chatgpt.py --prompt "having public and private subnet, attach internet gateway and nat gateway to the subnets also launch an instance inside the public subnet" --format "ansible" --file_name "ansible.yaml"
  • 위의 결과로 아래와 같은 ansible.yaml 파일이 만들어졌습니다.
---
- name: Create VPC
ec2_vpc:
region: "{{ region }}"
cidr_block: 10.0.0.0/16
resource_tags:
Name: "{{ vpc_name }}"
instance_tenancy: default
enable_dns_support: yes
enable_dns_hostnames: yes
wait: yes
register: vpc

- name: Create Public Subnet
ec2_vpc_subnet:
region: "{{ region }}"
cidr: 10.0.0.0/24
vpc_id: "{{ vpc.vpc.id }}"
resource_tags:
Name: "{{ public_subnet_name }}"
map_public_ip_on_launch: yes
wait: yes
register: public_subnet

- name: Create Private Subnet
ec2_vpc_subnet:
region: "{{ region }}"
cidr: 10.0.1.0/24
vpc_id: "{{ vpc.vpc.id }}"
resource_tags:
Name: "{{ private_subnet_name }}"
map_public_ip_on_launch: no
wait: yes
register: private_subnet

- name: Create Internet Gateway
ec2_vpc_igw:
region: "{{ region }}"
vpc_id: "{{ vpc.vpc.id }}"
resource_tags:
Name: "{{ igw_name }}"
wait: yes
register: igw

- name: Attach Internet Gateway to VPC
ec2_vpc_igw_attachment:
region: "{{ region }}"
vpc_id: "{{ vpc.vpc.id }}"
igw_id: "{{ igw.igw.id }}"
wait: yes

- name: Create NAT Gateway
ec2_vpc_nat_gateway:
region: "{{ region }}"
subnet_id: "{{ public_subnet.subnet.id }}"
resource_tags:
Name: "{{ nat_gateway_name }}"
wait: yes
register: nat_gateway

- name: Create Route Table
ec2_vpc_route_table:
region: "{{ region }}"
vpc_id: "{{ vpc.vpc.id }}"
resource_tags:
Name: "{{ route_table_name }}"
routes:
- dest: 0.0.0.0/0
gw: "{{ igw.igw.id }}"
wait: yes
register: route_table

- name: Associate Public Subnet to Route Table
ec2_vpc_subnet_route_table_association:
region: "{{ region }}"
subnet_id: "{{ public_subnet.subnet.id }}"
route_table_id: "{{ route_table.route_table.id }}"
wait: yes

- name: Create Route Table for Private Subnet
ec2_vpc_route_table:
region: "{{ region }}"
vpc_id: "{{ vpc.vpc.id }}"
resource_tags:
Name: "{{ private_route_table_name }}"
routes:
- dest: 0.0.0.0/0
gw: "{{ nat_gateway.nat_gateway.id }}"
wait: yes
register: private_route_table

- name: Associate Private Subnet to Route Table
ec2_vpc_subnet_route_table_association:
region: "{{ region }}"
subnet_id: "{{ private_subnet.subnet.id }}"
route_table_id: "{{ private_route_table.route_table.id }}"
wait: yes

- name: Launch Instance in Public Subnet
ec2:
region: "{{ region }}"
key_name: "{{ key_name }}"
instance_type: t2.micro
image: "{{ image }}"
wait: yes
vpc_subnet_id: "{{ public_subnet.subnet.id }}"
assign_public_ip: yes
count: 1
instance_tags:
Name: "{{ instance_name }}"
register: instance

4. 코드 검토 및 이해

위의 Ansible 코드를 이해하기 위해 ChatGPT의 도움을 받을 수 있습니다. 명령어는 아래와 같습니다.

  • CLI 명령어
python3 file_process.py --input ansible.yaml --output report.txt --prompt "explain the above code in detail"
  • 위의 결과로 report.txt 파일이 생성되었습니다.
The above code is an Ansible playbook that creates a Virtual Private Cloud (VPC) with two subnets, one public and one private, and launches an instance in the public subnet. 

The code begins by creating the VPC using the ec2_vpc module. It sets the region, the CIDR block, the resource tags, the instance tenancy, and enables DNS support and DNS hostnames. It then registers the VPC as a variable.

Next, the code creates the public subnet using the ec2_vpc_subnet module. It sets the region, the CIDR, the VPC ID, the resource tags, and enables public IPs to be assigned on launch. It then registers the public subnet as a variable.

The code then creates the private subnet using the same ec2_vpc_subnet module. It sets the region, the CIDR, the VPC ID, the resource tags, and disables public IPs from being assigned on launch. It then registers the private subnet as a variable.

The code then creates an Internet Gateway (IGW) using the ec2_vpc_igw module. It sets the region, the VPC ID, the resource tags, and registers the IGW as a variable.

The code then attaches the IGW to the VPC using the ec2_vpc_igw_attachment module. It sets the region, the VPC ID, and the IGW ID.

The code then creates a NAT Gateway using the ec2_vpc_nat_gateway module. It sets the region, the subnet ID, the resource tags, and registers the NAT Gateway as a variable.

The code then creates a route table using the ec2_vpc_route_table module. It sets the region, the VPC ID, the resource tags, and adds a route to the IGW. It then registers the route table as a variable.

The code then associates the public subnet to the route table using the ec2_vpc_subnet_route_table_association module. It sets the region, the subnet ID, and the route table ID.

The code then creates a route table for the private subnet using the ec2_vpc_route_table module. It sets the region, the VPC ID, the resource tags, and adds a route to the NAT Gateway. It then registers the route table as a variable.

The code then associates the private subnet to the route table using the ec2_vpc_subnet_route_table_association module. It sets the region, the subnet ID, and the route table ID.

Finally, the code launches an instance in the public subnet using the ec2 module. It sets the region, the key name, the instance type, the image, the VPC subnet ID, enables public IPs to be assigned, sets the count, and sets the instance tags. It then registers the instance as a variable.

내용이 길어지는 관계로 아래부터는 시나리오만 제시하도록 하겠습니다.

5. 오류 감지 및 해결

“위의 코드에서 하드코딩된 비밀 키가 있다면 알려줘”와 같은 질문을 사용해 오류를 감지하고 해결할 수 있습니다.

6. 개념 증명(PoC)

“하루 평균 10000명의 유저가 사용할 node.js 애플리케이션을 배포하려고 하는데 AWS에서 어떤 인스턴스 타입이 괜찮은가?”라는 질문을 사용해 PoC 방향 설정과 제안을 받을 수 있습니다.

7. 리팩토링

“작성한 코드 리팩토링 해줘”와 같은 질문으로 코드 리팩토링을 제안받을 수 있습니다.

맺음말

지금까지 DevOps 분야의 ChatGPT 사용 사례로 문서화, 실시간 번역, 코드 생성, 코드 검토 및 이해, 그리고 오류 감지 및 해결, PoC, 리팩토링을 소개해 보았습니다. 결론적으로 DevOps 워크플로에서 ChatGPT를 사용해 코드를 생성하고, 문서화를 자동화하며, 오류 가능성을 줄일 수 있습니다. 이로써 효율성과 생산성을 높일 수 있습니다. 아울러 AI가 생성한 제안에서 새로운 통찰력을 얻으며, 다양한 관점에서 PoC 능력을 향상할 수 있습니다. 또한 ChatGPT는 노련한 개발자의 입장이 되어 문제를 신속하게 해결할 뿐만 아니라 더 나은 팀 커뮤니케이션을 촉진할 수 있습니다. 나아가 ChatGPT를 Slack과 연동하면 팀에 실시간 알림과 피드백을 제공할 수 있습니다. 아울러 로그를 분석하여 문제를 감지하고 해결하는 데 이를 활용할 수도 있습니다. 이 밖에 ChatGPT를 CS 챗봇에 도입하여 일상적인 업무를 자동화하는 등 다양한 방법으로 이용할 수 있을 것입니다.

하지만 ChatGPT는 정답만 제공하는 것이 아니라, 사실이 아닌 것도 사실이라고 주장할 때가 있습니다. ChatGPT의 도움으로 공부해야 할 필요성이 줄어들었다고 생각할 수 있습니다. 그러나, 인프라를 다루는 DevOps 엔지니어는 더 엄격하게 정보를 걸러내기 위해 더 많이 공부해야 합니다. 또한, ChatGPT와 같은 범용 AI는 제한된 도메인 지식을 가지고 있습니다. DevOps와 같이 전문화된 작업에는 도메인별 AI 모델이 더 적합할 수 있습니다. 또한, 질문하는 과정에서 엔지니어가 실수로 내부의 중요한 소스 코드를 ChatGPT에 올려 유출하는 등 보안 및 개인 정보 보호 문제가 발생할 수 있습니다. 그러므로 AI가 많은 작업을 자동화할 수 있지만 ‘인간의 감독과 전문 지식을 모두 대체할 수는 없다’라는 점을 명심해야 할 것입니다.

참고자료

Python Automation with ChatGPT

How to Leverage ChatGPT for DevOps Automation

5 EFFECTIVE ways to use ChatGPT as a DevOps Engineer