파이문

gradle-ssh-plugin 사용하기 본문

TIL

gradle-ssh-plugin 사용하기

민Z 2021. 2. 18. 01:16

gradle-ssh-plugin

해당 플러그인의 장점은 병렬로 실행 된다는 것 정도

ssh example

session 은 병렬로 실행 되기 때문에 아래와 같은 경우 web01, web02 가 병렬로 실행된다.

순차적으로 실행하길 원하면 ssh.runInOrder 를 사용할 것

ssh.run {
  session(remotes.web01) {
    execute 'command1' 
  }
  session(remotes.web02) {
    execute 'command2' 
  }
}

session 함수 안에서 사용하는 객체는 Remote 라는 클래스 객체로 같은 사람이 개발한 groovy-ssh 에 있는 이거다.

 

서버가 다수고, 다른 환경 파일에서 관리하고 싶다면 (스크립트에서 하드 코딩하지 않고, 다른 환경 파일에 의존성을 갖고 싶다면) 파일 읽어 들이면서, Remote 객체를 아래 처럼 만들어주자. (groovy 문법임)

new Remote(host: 'host', user: 'user', identity: file('/my/key'))

 

그리고 만든 객체를 리스트에 넣은 후에 사용하면 될 것 같다.

ssh example with property

groovy 는 잘 몰라서 스택오버플로우 보면서 어떻게 어떻게 만들어 봄....

외부 파일을 읽어서 Remote 객체 만들어서 사용하는 방법인데, 참고로 버그가 있다. 

task doTask {
    def props = new Properties()
    List<Remote> remotes = new ArrayList<>()

    doFirst {
        def filePath = "/path/to/file"
        File propsFile = new File(filePath)

        propsFile.withInputStream {
            props.load(it)
        }
    }

    doLast {
        propsFile.each {
            host ->
                remotes.add(new Remote(host: host, user: 'user', identity: file('/my/key')))
        }
        
        ssh.run {
        	for (Remote remote : remotes) {
            	session(remote) { ... }
            }
        }   
 }

근데 bug 가 있음

여기서 (1) 이랑 (2) 가 다르다. (1) 로 ssh connection 이 맺어졌는데 (중요! connection 은 맺어짐!!) session scope 안에서 값이 달라지는 것이다. 참고로 runInOrder 로 해도 동일하다. (병렬 실행 때문인지 알았는데 아니였음)

ssh.run {  
    for (Remote source : remotes) {
        println "$source.host" // (1)
        session(source) {
            println "$source.host" // (2)
        }
    }
}

그래서 아래 처럼 야매로(?) 진행 했다.

변수 새로 생성하면 (1) 이 그대로 session 안 scope 까지 먹는다. (1과 2 동일)

ssh.run {  
    for (Remote source : remotes) {
        Remote target = source
        println "$source.host" // (1)
        session(target) {
            println "$target.host" // (2)
        }
    }
}

groovy 를 모르니까 코드를 봐도 잘 모르겠고, issue 는 남겼는데 (고마워요 구글 번역기!) 이 오픈 소스 자체가 그렇게 활발히 (?) 유지보수가 되고 있는 것 같진 않아 보인다.

 

그냥 비슷한 일은 ansible 을 쓰는게 맞아 보임

제발 한국인이라면 ansible 을 씁시다 (??)

scp example

ssh.run {
  session(remotes.web01) {
    put from: 'local_file', into: '/remote/file'
  }
}

기타 등등

dryRun 옵션을 주면 실제 ssh connection 은 맺지 않고 스크립트를 실행시켜준다. (스크립트가 정상 동작하는지 여부 확인 가능)

Comments