Post

Jenkins ant script to ssh and chef servers by passing credentials

Jenkins ant script to ssh and chef servers by passing credentials

This extends the basic SSH restart script to handle multiple servers and pass credentials through for Chef runs. The propertyselector trick for pulling server hostnames from Maven properties is what makes it scale — add a new server to the profile and the loop picks it up automatically.

  • Call target from pom.xml
1
2
3
4
5
6
7
<configuration>
    <target>
        <ant antfile="${basedir}/build.xml">
            <target name="deploy" />
        </ant>
    </target>
</configuration>
  • Setup profile and add servers for that environment
1
2
3
4
5
6
7
8
9
10
<profile>
    <id>dev</id>
    <properties>
        <classifier.type>DEV</classifier.type>
        <server1.hostname>server1</server1.hostname>
        <server2.hostname>server2</server2.hostname>
        <server3.hostname>server3</server3.hostname>
        <server4.hostname>server4</server4.hostname>
    </properties>
</profile>
  • Ant sort server host names to list
1
 <propertyselector property="hostnames" match="server([^\.]*)\.hostname"/>
  • Ant Loop command
1
2
<for list="${sorted.hostnames}" param="hostname">
</for>
  • Ant if else condition
1
2
3
4
5
6
7
8
9
<if>
    <equals arg1="${stop.server}" arg2="true" />
    <then>	
       ....
    </then>
    <else>
       ....
    </else>
</if>
  • Ant ssh and execute commands on remote
1
2
3
4
5
6
7
<sshexec 
    host="${node}"
    username="${windows.username}" 
    password="${windows.password}"
    command="cd /tmp/vagrant;
             sudo chef-solo -c solo.rb -j app_node.json -E ${@{hostname}}"
    trust="true" />

Source

This post is licensed under CC BY 4.0 by the author.