-
Notifications
You must be signed in to change notification settings - Fork 0
/
portainer.js
109 lines (93 loc) · 2.6 KB
/
portainer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* Portainer functions
*/
const axios = require('axios').default;
/**
* Login into portainer
* @param {string} username User's username
* @param {string} password User's password
* @returns {string} Portainer access token
*/
const login = async function (username, password) {
const response = await axios.post(`${process.env.PORTAINER_API}/auth`, {
Username: username,
Password: password,
});
// React to portainer error
if (response.err)
throw new Error(response.err);
return response.data.jwt;
};
/**
* Get stack descriptor by name
* @param {string} token Portainer access token
* @param {string} name Stack name
* @returns {Stack} Stack descriptor
*/
const getStack = async function (token, name) {
const response = await axios.get(`${process.env.PORTAINER_API}/stacks`, {
headers: {
'Authorization': `Bearer ${token}`,
},
});
// React to portainer error
if (response.err)
throw new Error(response.err);
// Check if stack list was returned
if (!response.data || !Array.isArray(response.data))
return null;
// Find in stack list
for (const stack of response.data) {
if (stack.Name === name)
return stack;
}
return null; // Stack not found
}
/**
* Get Stack Docker compose file content
* @param {string} token Portainer access token
* @param {number} stackId
*/
const getStackComposeFile = async function (token, stackId) {
// Get current stack file
const response = await axios.get(`${process.env.PORTAINER_API}/stacks/${stackId}/file`, {
headers: {
'Authorization': `Bearer ${token}`,
},
});
// React to portainer error
if (response.err)
throw new Error(response.err);
return response.data.StackFileContent;
}
/**
* Update stack descriptor
* @param {string} token Portainer access token
* @param {Stack} stack stack descriptor
* @param {string} composeFile docker compose file contents
*/
const updateStack = async function (token, stack, composeFile = null) {
if (!composeFile)
composeFile = await getStackComposeFile(token, stack.Id);
if (!composeFile || composeFile.trim().length === 0)
throw new Error('Docker compose file empty');
const response = await axios.put(`${process.env.PORTAINER_API}/stacks/${stack.Id}`, {
'StackFileContent': composeFile,
'Env': stack.Env,
}, {
headers: {
'Authorization': `Bearer ${token}`,
},
params: {
endpointId: stack.EndpointId,
},
});
// React to portainer error
if (response.err)
throw new Error(response.err);
}
module.exports = {
login: login,
getStack: getStack,
updateStack: updateStack,
};