"""Jenkins 초기 설정 자동화""" import paramiko, sys, time, json sys.stdout.reconfigure(encoding='utf-8', errors='replace') client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect('101.79.17.164', username='root', password='1q2w3e!Q', timeout=30) def run(label, cmd, timeout=60): print(f'\n[{label}]') _, o, e = client.exec_command(cmd, timeout=timeout) out = o.read().decode('utf-8', errors='replace').strip() err = e.read().decode('utf-8', errors='replace').strip() if out: print(out[:500]) if err: bad = [l for l in err.splitlines() if not any(k in l.lower() for k in ['warn','info','downloading'])] if bad: print('ERR:', '\n'.join(bad[:3])) return out # 1. Jenkins CLI jar 다운로드 run('CLI jar 다운로드', """ if [ ! -f /tmp/jenkins-cli.jar ]; then curl -sf http://localhost:8080/jnlpJars/jenkins-cli.jar -o /tmp/jenkins-cli.jar 2>/dev/null test -f /tmp/jenkins-cli.jar && echo "다운로드 완료" || echo "실패" fi ls -la /tmp/jenkins-cli.jar 2>/dev/null """) # 2. Jenkins 설정 완료 여부 확인 run('Jenkins 웹 상태', """ HTTP=$(curl -sf -o /dev/null -w "%{http_code}" http://localhost:8080/ 2>/dev/null) echo "HTTP 상태: $HTTP" if [ "$HTTP" = "403" ] || [ "$HTTP" = "200" ]; then echo "Jenkins 웹 응답 정상" else echo "아직 초기화 중..." fi """) # 3. Groovy 스크립트로 Jenkins 설정 (초기 설정 우회) run('Groovy 초기 설정', """ INIT_PW=c753461ad51f4b85901e90bff6612f84 # Jenkins init.groovy.d로 초기 설정 mkdir -p /var/lib/jenkins/init.groovy.d cat > /var/lib/jenkins/init.groovy.d/00_setup.groovy << 'GROOVY' import jenkins.model.* import hudson.security.* import jenkins.install.InstallState def instance = Jenkins.getInstance() // 설정 완료 처리 (wizard 건너뛰기) if(!instance.installState.isSetupComplete()) { InstallState.INITIAL_SETUP_COMPLETED.initializeState() } // admin 계정 설정 def hudsonRealm = new HudsonPrivateSecurityRealm(false) hudsonRealm.createAccount('admin', 'admin') instance.setSecurityRealm(hudsonRealm) def strategy = new FullControlOnceLoggedInAuthorizationStrategy() strategy.setAllowAnonymousRead(false) instance.setAuthorizationStrategy(strategy) instance.save() println "Jenkins setup complete" GROOVY echo "Groovy 스크립트 생성" """) # 4. Jenkins 재시작 run('Jenkins 재시작', 'systemctl restart jenkins && sleep 10 && systemctl is-active jenkins') # 5. 상태 재확인 time.sleep(10) run('재시작 후 API 확인', """ for i in 1 2 3 4 5; do HTTP=$(curl -sf -o /dev/null -w "%{http_code}" http://localhost:8080/api/json -u admin:admin 2>/dev/null) echo "시도 $i: HTTP $HTTP" if [ "$HTTP" = "200" ]; then break; fi sleep 5 done """) run('플러그인 설치 (필수)', """ java -jar /tmp/jenkins-cli.jar -s http://localhost:8080 -auth admin:admin install-plugin \ git workflow-aggregator pipeline-stage-view credentials-binding \ ssh-agent nodejs timestamper ansicolor \ 2>/dev/null && echo "플러그인 설치 완료" || echo "플러그인 설치 실패 (수동 필요)" """, timeout=120) client.close() print('\n=== Jenkins 초기 설정 완료 ===')