본문 바로가기
IT & Tech 정보

ChatOps 워크플로우 끝판왕 가이드 Slack · Hubot · GitHub Webhook 자동화

by 지식과 지혜의 나무 2025. 5. 26.
반응형




1. 개요: ChatOps로 모든 것을 컨트롤하다

ChatOps는 채널 하나로 개발·운영·지원팀이 협업하고, 봇이 자동화된 워크플로우를 수행하게 하는 혁신적 패러다임입니다. Slack을 허브로 삼아 Hubot 스크립트와 GitHub Webhook, CI/CD API를 결합하면:
• 실시간 커맨드 실행: /deploy service env 한 줄로 배포
• 이벤트 알림: PR 동기화·코드 리뷰 요청·테스트 결과 즉시 공지
• 자동화 확장: 커스텀 스크립트·Slash Command·버튼 클릭으로 복잡 절차 단순화

실리콘밸리·심천 IT기업 톱티어 팀들이 채택한 끝판왕 ChatOps 구현법을 단계별로 정리합니다.



2. 아키텍처 스냅샷

GitHub ── Webhook ──▶ Hubot ──▶ Slack  
   │                           ▲  
   │                           │  
   └─── CI/CD API ──▶ Hubot ───┘  

1. GitHub Webhook: PR/Push/Issue 이벤트 발생
2. Hubot:
• Slack Adapter로 Slash Command·Action 처리
• GitHub Webhook Endpoint로 이벤트 수신
• CI/CD API(Jenkins, GitHub Actions) 호출
3. Slack:
• 사용자 인터페이스 (Slash, 버튼, 다이얼로그)
• Hubot 응답·알림 채널



3. Slack App & Bot 설정

3.1 OAuth 권한
• Bot Token Scopes
• commands, chat:write, chat:write.public,
• channels:read, groups:read, users:read
• Event Subscriptions
• message.im, app_mention, reaction_added 등 필요 이벤트 등록
• Slash Commands
• /deploy, /status, /rollout 등 커맨드마다 Request URL 지정
• Interactive Components
• 버튼·메뉴 클릭 → actions Request URL



4. Hubot 스크립팅

4.1 프로젝트 구조

hubot/
├── scripts/
│   ├── deploy.js         # /deploy handling
│   ├── pr_notify.js      # GitHub PR 알림
│   └── utils.js          # 공통 함수
└── external-scripts.json # Slack adapter 등록

4.2 Slash Command 예제

// scripts/deploy.js
module.exports = (robot) => {
  robot.respond(/deploy (\S+) to (\S+)/i, async (res) => {
    const service = res.match[1], env = res.match[2];
    await res.send(`🚀 배포 요청 접수: 서비스=${service}, 환경=${env}`);
    try {
      const resp = await robot.http(`https://ci.example.com/deploy`)
        .query({ service, env, token: process.env.CI_TOKEN })
        .post();
      res.send(`✅ CI/CD 응답: ${resp}`);
    } catch (e) {
      res.send(`❌ 배포 실패: ${e.message}`);
    }
  });
};

4.3 Interactive Button 핸들링

// scripts/actions.js
module.exports = (robot) => {
  robot.on('slack_action', async (msg) => {
    const { name, value } = msg.message.attachments[0].actions[0];
    if (name === 'approve') {
      await msg.send(`👍 승인 처리 중: ${value}`);
      // 승인 로직, 예: CI 승인 API 호출
    }
  });
};




5. GitHub Webhook 연동

5.1 Webhook 엔드포인트 구현

// scripts/github.js
module.exports = (robot) => {
  robot.router.post('/hubot/github', (req, res) => {
    const event = req.headers['x-github-event'], payload = req.body;
    if (event === 'pull_request' && payload.action === 'opened') {
      const title = payload.pull_request.title, url = payload.pull_request.html_url;
      robot.messageRoom('dev-team', `🔔 새 PR: ${title}\n${url}`);
    }
    res.sendStatus(200);
  });
};

• 시그니처 검증: req.headers['x-hub-signature']로 GITHUB_WEBHOOK_SECRET 검증



6. CI/CD 통합

6.1 Jenkins API 호출

// utils.js
async function triggerJenkins(service, env) {
  return robot.http('https://jenkins.example.com/job/deploy/buildWithParameters')
    .query({ token: process.env.JENKINS_TOKEN, SERVICE: service, ENV: env })
    .post();
}

6.2 GitHub Actions 트리거

// deploy.js 내
await robot.http(`https://api.github.com/repos/org/repo/actions/workflows/deploy.yml/dispatches`)
  .header('Authorization', `token ${process.env.GH_TOKEN}`)
  .post(JSON.stringify({ ref: 'main', inputs: { service, env } }));




7. 고급 팁
1. Ephemeral Responses

res.send({ text: '처리 중...', response_type: 'ephemeral' });


2. OAuth Installed App
• 사용자별 권한 확인, 개인 토큰 없이 Slack 인증 흐름 구현
3. Command Queueing
• async.queue 모듈로 동일 서비스 중복 요청 큐잉
4. Metrics & Monitoring
• prom-client로 명령 처리 시간·성공률 수집 → Grafana 연동
5. Auto Help 명령

robot.respond(/help/i, (res) => {
  res.send(`
  사용법:



/deploy <서비스> to <환경> – 배포 요청
/status <서비스> – 배포 상태
/approve <PR번호> – PR 승인
`);
});

---

## 8. 보안 고려사항  

- **Slack Signing Secret** 검증 미들웨어  
- **GitHub Signature** (`X-Hub-Signature-256`) 검증  
- **환경변수 관리**: Vault 연동 또는 Kubernetes Secrets 주입  
- **Rate Limiting**: Hubot 레이트 리미터 플러그인 사용  

---

## 9. 결론  
- **Slash Command**, **Interactive Components**, **Event Subscription**  
- **Hubot 스크립트**와 **GitHub Webhook** 결합  
- **CI/CD API** 활용한 자동 배포 및 모니터링  
- **보안·로그·메트릭**을 갖춘 완전 자동화 ChatOps  

“지구 최강 실리콘밸리·심천 IT기업 수준의 ChatOps”를 직접 구현해 보세요. Slack 한 채널에서 **모든 작업**이 실행되는 그날까지!

반응형