|
| 1 | +import com.cloudbees.hudson.plugins.folder.Folder |
| 2 | +import com.cloudbees.hudson.plugins.folder.properties.FolderCredentialsProvider |
| 3 | +import com.cloudbees.plugins.credentials.SystemCredentialsProvider |
| 4 | +import com.cloudbees.plugins.credentials.domains.DomainCredentials |
| 5 | +import com.thoughtworks.xstream.converters.Converter |
| 6 | +import com.thoughtworks.xstream.converters.MarshallingContext |
| 7 | +import com.thoughtworks.xstream.converters.UnmarshallingContext |
| 8 | +import com.thoughtworks.xstream.io.HierarchicalStreamReader |
| 9 | +import com.thoughtworks.xstream.io.HierarchicalStreamWriter |
| 10 | +import com.trilead.ssh2.crypto.Base64 |
| 11 | +import hudson.util.Secret |
| 12 | +import hudson.util.XStream2 |
| 13 | +import jenkins.model.Jenkins |
| 14 | + |
| 15 | +def instance = Jenkins.get() |
| 16 | +def credentials = [] |
| 17 | + |
| 18 | +// Copy all domains from the system credentials provider |
| 19 | +def systemProvider = instance.getExtensionList(SystemCredentialsProvider.class) |
| 20 | +if (!systemProvider.empty) { |
| 21 | + def systemStore = systemProvider.first().getStore() |
| 22 | + for (domain in systemStore.domains) { |
| 23 | + credentials.add(new DomainCredentials(domain, systemStore.getCredentials(domain))) |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +// Copy all domains from all folders |
| 28 | +def folderExtension = instance.getExtensionList(FolderCredentialsProvider.class) |
| 29 | +if (!folderExtension.empty) { |
| 30 | + def folders = instance.getAllItems(Folder.class) |
| 31 | + def folderProvider = folderExtension.first() |
| 32 | + for (folder in folders) { |
| 33 | + def store = folderProvider.getStore(folder) |
| 34 | + for (domain in store.domains) { |
| 35 | + credentials.add(new DomainCredentials(domain, store.getCredentials(domain))) |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +// The converter ensures that the output XML contains the unencrypted secrets |
| 41 | +def converter = new Converter() { |
| 42 | + @Override |
| 43 | + void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext context) { |
| 44 | + writer.value = Secret.toString(object as Secret) |
| 45 | + } |
| 46 | + |
| 47 | + @Override |
| 48 | + Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { null } |
| 49 | + |
| 50 | + @Override |
| 51 | + boolean canConvert(Class type) { type == Secret.class } |
| 52 | +} |
| 53 | + |
| 54 | +def stream = new XStream2() |
| 55 | +stream.registerConverter(converter) |
| 56 | + |
| 57 | +// Marshal the list of credentials into XML |
| 58 | +def encoded = [] |
| 59 | +def sections = credentials.collate(25) |
| 60 | +for (section in sections) { |
| 61 | + def xml = Base64.encode(stream.toXML(section).bytes) |
| 62 | + encoded.add("\"${xml}\"") |
| 63 | +} |
| 64 | + |
| 65 | +println encoded.toString() |
0 commit comments