Compare commits
570 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
69c3b90fea | ||
|
|
75309b4c93 | ||
|
|
433f13a7ed | ||
|
|
8896a1e73e | ||
|
|
54758b1692 | ||
|
|
375e00c79c | ||
|
|
e2454d91f1 | ||
|
|
6894f6f3bf | ||
|
|
d45501a129 | ||
|
|
def92e14ee | ||
|
|
11708d4189 | ||
|
|
2bc64bf419 | ||
|
|
3a3bdc62c8 | ||
|
|
72294b2a56 | ||
|
|
94940a20ef | ||
|
|
219ff2ef7d | ||
|
|
bc2de741b8 | ||
|
|
5eabd4e898 | ||
|
|
e8d6d5fe5c | ||
|
|
55bd93ff79 | ||
|
|
b34b2d779b | ||
|
|
103ed2be65 | ||
|
|
cc32c1be07 | ||
|
|
a3ba9817a3 | ||
|
|
6d5f1b17ad | ||
|
|
0d5d5fce46 | ||
|
|
375edffd15 | ||
|
|
d1982e64b2 | ||
|
|
cec8b5336c | ||
|
|
8f78263455 | ||
|
|
cb96bca6aa | ||
|
|
c18d0b9217 | ||
|
|
d1970185b9 | ||
|
|
794d3ee2f5 | ||
|
|
daeef98dfb | ||
|
|
4146df1f02 | ||
|
|
78f4dfa48d | ||
|
|
8b68d7d7e2 | ||
|
|
ba1bba17ad | ||
|
|
70f2b5028f | ||
|
|
4f4f0d70a4 | ||
|
|
9607b07e65 | ||
|
|
3570fab0f9 | ||
|
|
dd0f17d7a5 | ||
|
|
2290880389 | ||
|
|
351d287d88 | ||
|
|
eba6706f15 | ||
|
|
7f425efa6b | ||
|
|
d40685ab62 | ||
|
|
f795e3eeb8 | ||
|
|
d3944c0204 | ||
|
|
4086ab15fa | ||
|
|
446a367094 | ||
|
|
bd250c9871 | ||
|
|
91b3788362 | ||
|
|
658dbb9ea8 | ||
|
|
1257b9cbc8 | ||
|
|
0ae39d5a0a | ||
|
|
d8911e0c77 | ||
|
|
1be006a45f | ||
|
|
b95e75ddb4 | ||
|
|
15a5f75fe7 | ||
|
|
b01e27f50f | ||
|
|
b1a9583262 | ||
|
|
dd5e6377f8 | ||
|
|
fcb73554c9 | ||
|
|
5c4b3d1080 | ||
|
|
c98cd10621 | ||
|
|
e4af8ddcc8 | ||
|
|
b5ce02b8cf | ||
|
|
cd42b3fb44 | ||
|
|
6dedb767c3 | ||
|
|
4de3268f3b | ||
|
|
a72ff06d79 | ||
|
|
cf239deb3d | ||
|
|
8735229745 | ||
|
|
3f081ba2d9 | ||
|
|
3f613341cb | ||
|
|
4305b8a77d | ||
|
|
fab91d44c3 | ||
|
|
34484734d8 | ||
|
|
10c58bb007 | ||
|
|
1c1fd62a91 | ||
|
|
637ac1e3fe | ||
|
|
f52387e849 | ||
|
|
9efc4986f9 | ||
|
|
fdc366ec1c | ||
|
|
d455db444c | ||
|
|
17418c9858 | ||
|
|
5da7eb7d0d | ||
|
|
9da977ee7a | ||
|
|
8e4b2ead9b | ||
|
|
fd364828a1 | ||
|
|
afa58d8c08 | ||
|
|
179062876e | ||
|
|
a796f3609f | ||
|
|
b7c6db74d2 | ||
|
|
4f7b040405 | ||
|
|
34ca29830e | ||
|
|
78f1b634fa | ||
|
|
044bc64ad9 | ||
|
|
091f439498 | ||
|
|
a17b0a1ce0 | ||
|
|
354cd5e177 | ||
|
|
4e8f1221f7 | ||
|
|
6b179aa7d9 | ||
|
|
f748114dfa | ||
|
|
5de83f015a | ||
|
|
a6620e478a | ||
|
|
c7fcffdd8e | ||
|
|
160f59a984 | ||
|
|
d38d487c2a | ||
|
|
db28907543 | ||
|
|
c4261399b5 | ||
|
|
b4edb46269 | ||
|
|
a20ed0e630 | ||
|
|
cea869e285 | ||
|
|
e12db14d1e | ||
|
|
296bf3cc6c | ||
|
|
1789aa180d | ||
|
|
bd255800db | ||
|
|
1355962b3c | ||
|
|
bb0114e379 | ||
|
|
f9622a5b9e | ||
|
|
3a74fcd75c | ||
|
|
7265276cc2 | ||
|
|
b98027b528 | ||
|
|
b6ae7d2cdd | ||
|
|
aa887c61c3 | ||
|
|
700cef0989 | ||
|
|
3ed3e553e7 | ||
|
|
d68158ddc9 | ||
|
|
9f83a69242 | ||
|
|
bf69dbd43d | ||
|
|
465ea5ccfd | ||
|
|
92ef39e2ad | ||
|
|
0404790df9 | ||
|
|
f880e93df4 | ||
|
|
4697b1101d | ||
|
|
50ff2accd2 | ||
|
|
c7d876eb8f | ||
|
|
eda392dfcd | ||
|
|
3b91e14f6d | ||
|
|
17e3c57d7e | ||
|
|
1c744a0f97 | ||
|
|
99bdb20aeb | ||
|
|
fbe7050cb8 | ||
|
|
12ea028aa9 | ||
|
|
ea62cb5fc9 | ||
|
|
d27c2164b2 | ||
|
|
ef8f5cb87d | ||
|
|
378a2c2a0e | ||
|
|
2597ad0f73 | ||
|
|
0df34bed59 | ||
|
|
be65cf8052 | ||
|
|
8922753591 | ||
|
|
87e11ed653 | ||
|
|
ab34771b3d | ||
|
|
e733c4f55a | ||
|
|
37b60666c4 | ||
|
|
734d736bdf | ||
|
|
8ca65059f7 | ||
|
|
086f174463 | ||
|
|
48fd70fc09 | ||
|
|
606266e976 | ||
|
|
f7006a8172 | ||
|
|
653dcc8d78 | ||
|
|
8df140c713 | ||
|
|
089af9cc90 | ||
|
|
695fb55b13 | ||
|
|
ec21eedd56 | ||
|
|
5ba3774fd5 | ||
|
|
12a2100fcf | ||
|
|
68074d3543 | ||
|
|
18849e36c7 | ||
|
|
671fe274da | ||
|
|
af1d9102b9 | ||
|
|
9dc10ef7d1 | ||
|
|
86a3cf20e7 | ||
|
|
27a42ecd8e | ||
|
|
ae7a59fbb4 | ||
|
|
598dfc32e8 | ||
|
|
a40d124e23 | ||
|
|
9df3fcab18 | ||
|
|
b6ce969d1b | ||
|
|
6a37649ee6 | ||
|
|
8926095660 | ||
|
|
bd34870334 | ||
|
|
a56ce1f867 | ||
|
|
dab5bbd393 | ||
|
|
15ebfd7eb6 | ||
|
|
5ab8dd2557 | ||
|
|
9164914d16 | ||
|
|
c9e0bc0807 | ||
|
|
61439adf9b | ||
|
|
e4d7450643 | ||
|
|
0fbcfded57 | ||
|
|
fb3a434f95 | ||
|
|
4f66da84d6 | ||
|
|
b67e8aafab | ||
|
|
0b4f1d30a6 | ||
|
|
c494e6bf7e | ||
|
|
b8c57c7901 | ||
|
|
6aed4631e7 | ||
|
|
5df9118365 | ||
|
|
4a4af94d6c | ||
|
|
baa54fb84a | ||
|
|
cb6470f817 | ||
|
|
1a904e138f | ||
|
|
3b482529ff | ||
|
|
67997437db | ||
|
|
a5541eddca | ||
|
|
203157e525 | ||
|
|
655c2261ba | ||
|
|
45e446eb00 | ||
|
|
68abe37648 | ||
|
|
df6a0a3762 | ||
|
|
c35bae577f | ||
|
|
3567941eda | ||
|
|
3c95fe6380 | ||
|
|
d07f0d003c | ||
|
|
86774309db | ||
|
|
427f23e32d | ||
|
|
70cddde16c | ||
|
|
e86789b643 | ||
|
|
f52fec66bd | ||
|
|
f4926d1e45 | ||
|
|
2774c1a5cd | ||
|
|
8274bc0ea3 | ||
|
|
e9531e4d57 | ||
|
|
3a8aad7e5c | ||
|
|
ef079c5b58 | ||
|
|
50332aa2ee | ||
|
|
b47f3a57dc | ||
|
|
9a928744cc | ||
|
|
328d403507 | ||
|
|
76ffd76bd3 | ||
|
|
951589e652 | ||
|
|
7bb0704401 | ||
|
|
3aa45e72e7 | ||
|
|
67691e92e3 | ||
|
|
43388ec67b | ||
|
|
2fe3934491 | ||
|
|
f60ba95b4c | ||
|
|
4ecf541748 | ||
|
|
7994829765 | ||
|
|
ce14951436 | ||
|
|
a5ce8221a3 | ||
|
|
e6344ef18e | ||
|
|
99e60634ad | ||
|
|
6c656b7366 | ||
|
|
fc3a09b5ad | ||
|
|
b1484f2f24 | ||
|
|
7dcf884e38 | ||
|
|
b6d349da8c | ||
|
|
40ce3d50c2 | ||
|
|
68046067c5 | ||
|
|
e3b12a8a24 | ||
|
|
f123b9d3cb | ||
|
|
f4ce89ae26 | ||
|
|
ea451e7e49 | ||
|
|
d434575047 | ||
|
|
e627634184 | ||
|
|
e0dd12505f | ||
|
|
5a67f94380 | ||
|
|
5f9dd7a5a5 | ||
|
|
bce0da2806 | ||
|
|
a58c40f2d7 | ||
|
|
65d5cadf29 | ||
|
|
1ea5d4d2e3 | ||
|
|
719ef3c44c | ||
|
|
f4adfc3029 | ||
|
|
d8d08091cc | ||
|
|
de4b3ef3dc | ||
|
|
7bd6aedb73 | ||
|
|
fffe40fbd4 | ||
|
|
74feda73af | ||
|
|
8b5583930e | ||
|
|
466fdae70e | ||
|
|
054a62fb30 | ||
|
|
c694b570e0 | ||
|
|
4204ec1d43 | ||
|
|
6d4e37ccb2 | ||
|
|
eef06c993e | ||
|
|
58362fbbb9 | ||
|
|
b872e595ae | ||
|
|
18c3f79319 | ||
|
|
8f0cd35d7a | ||
|
|
c8bcf19f32 | ||
|
|
5bee3047ac | ||
|
|
0d2f6bf02d | ||
|
|
7481c6beb0 | ||
|
|
4ece12348b | ||
|
|
e65a5beaae | ||
|
|
ef576128e3 | ||
|
|
7f0bc2ada2 | ||
|
|
96c373d045 | ||
|
|
22648cae3b | ||
|
|
f57ce14754 | ||
|
|
1d3a381389 | ||
|
|
9055e753a9 | ||
|
|
6390812cbb | ||
|
|
fa46f05423 | ||
|
|
6b0ffe0b13 | ||
|
|
e724d90202 | ||
|
|
6129943685 | ||
|
|
d4e37cbda5 | ||
|
|
cccfb3a560 | ||
|
|
d0403038ed | ||
|
|
a5a7d7970f | ||
|
|
62b9377f15 | ||
|
|
ec2c71f9ef | ||
|
|
b54fd2c6b3 | ||
|
|
e5066c3712 | ||
|
|
fd1c038303 | ||
|
|
64e7a857b8 | ||
|
|
7da24932ab | ||
|
|
1a2ea8407b | ||
|
|
32f94bab97 | ||
|
|
dea4a67639 | ||
|
|
236ffd1767 | ||
|
|
1b2ffad2f1 | ||
|
|
4750d0d81c | ||
|
|
63a210a0b2 | ||
|
|
465eaa24d3 | ||
|
|
c23e8c7ee1 | ||
|
|
974f01cb46 | ||
|
|
16fa9b2753 | ||
|
|
9deab1c415 | ||
|
|
7c01eeb115 | ||
|
|
998f0c7d53 | ||
|
|
bd41406aaa | ||
|
|
f17801753d | ||
|
|
92891fd340 | ||
|
|
aa122455f7 | ||
|
|
880e70c19c | ||
|
|
968f249562 | ||
|
|
bb9f476be2 | ||
|
|
276f43fdeb | ||
|
|
150d1c2a5a | ||
|
|
1bf3814701 | ||
|
|
166181c745 | ||
|
|
bfff977d41 | ||
|
|
787d755261 | ||
|
|
acf7173959 | ||
|
|
e6132e36ba | ||
|
|
585b97c462 | ||
|
|
3dfd0bc2e1 | ||
|
|
10ff99542f | ||
|
|
2449030ab8 | ||
|
|
3e85901f40 | ||
|
|
73b1576f81 | ||
|
|
cdb5b7c9a2 | ||
|
|
d9331b0c91 | ||
|
|
b6a8163dd9 | ||
|
|
185252ba48 | ||
|
|
043d37921b | ||
|
|
02fb8d9958 | ||
|
|
cfa6c0a178 | ||
|
|
e8b52bf2fc | ||
|
|
85fbb780bf | ||
|
|
bd9f9bf518 | ||
|
|
077860fff1 | ||
|
|
d29a4ee4d2 | ||
|
|
6d2e34e9b2 | ||
|
|
0b6969537b | ||
|
|
dc6b0d0f0d | ||
|
|
b4dbb178fe | ||
|
|
4cf5290989 | ||
|
|
6ffd2222c2 | ||
|
|
e7725911a7 | ||
|
|
0c1664cd01 | ||
|
|
0239307d8e | ||
|
|
9f10b6be1b | ||
|
|
01f613b39e | ||
|
|
b775d11a70 | ||
|
|
022576697f | ||
|
|
065d0b2c06 | ||
|
|
ed4718205a | ||
|
|
a29d0c536d | ||
|
|
eaeb8ca5c1 | ||
|
|
2092c14aca | ||
|
|
69f38b8c77 | ||
|
|
d2cdd02a57 | ||
|
|
095c8323a1 | ||
|
|
accb4c915e | ||
|
|
242809f61d | ||
|
|
c4907cf6c6 | ||
|
|
a4b9191fa3 | ||
|
|
5fd3d0bd41 | ||
|
|
ba6da23323 | ||
|
|
0328bb14ce | ||
|
|
2b7a0f3fd4 | ||
|
|
527886bea0 | ||
|
|
98078a0c65 | ||
|
|
ca660b7ba5 | ||
|
|
ed93e93b81 | ||
|
|
80419f00db | ||
|
|
01946facb3 | ||
|
|
08c1bd7653 | ||
|
|
ebf9188c6a | ||
|
|
382c6d5885 | ||
|
|
384c60a988 | ||
|
|
0078147587 | ||
|
|
d79bedf2bc | ||
|
|
14b31b321c | ||
|
|
309b9b52f8 | ||
|
|
5d063e7390 | ||
|
|
e7ba9b5624 | ||
|
|
81f6fa598f | ||
|
|
d9eabcdbf7 | ||
|
|
bb3562427b | ||
|
|
8a5bba80bf | ||
|
|
ff2833c4d1 | ||
|
|
45ba845f23 | ||
|
|
771a14fcf6 | ||
|
|
c8ff861d00 | ||
|
|
0f05ce3605 | ||
|
|
38a3f3ba11 | ||
|
|
659a19cd80 | ||
|
|
baaa466c0f | ||
|
|
168c65bb6e | ||
|
|
6003d11156 | ||
|
|
1f16b6d639 | ||
|
|
54bb4b2efd | ||
|
|
f54770c21a | ||
|
|
1244a62deb | ||
|
|
2fe55bcdde | ||
|
|
9943690855 | ||
|
|
89c46a6379 | ||
|
|
a0d4530cc0 | ||
|
|
6db84269af | ||
|
|
2cd3c32ca7 | ||
|
|
9740fecc35 | ||
|
|
433492791b | ||
|
|
7d3c63ad74 | ||
|
|
a6538b117e | ||
|
|
d54e7559a5 | ||
|
|
bb9eca7232 | ||
|
|
b5027d8f3f | ||
|
|
00a134e23f | ||
|
|
aab3452773 | ||
|
|
5903dfc627 | ||
|
|
a5272b2b39 | ||
|
|
771fc20bb2 | ||
|
|
b5f48bee78 | ||
|
|
ff78af5808 | ||
|
|
7eab649abc | ||
|
|
1b5db157b1 | ||
|
|
0fa9aebf7a | ||
|
|
9fb9965ffe | ||
|
|
02c9f29499 | ||
|
|
c6243ad002 | ||
|
|
f4650c7a84 | ||
|
|
6df691598e | ||
|
|
26964b7f88 | ||
|
|
71712ae1c3 | ||
|
|
0b6c979e47 | ||
|
|
cc2cbc2519 | ||
|
|
8043ae961a | ||
|
|
b1d1d30cdb | ||
|
|
28d606cb0e | ||
|
|
e9c5b6e917 | ||
|
|
68f96235fc | ||
|
|
12f22ddeba | ||
|
|
9db5c644a6 | ||
|
|
ef6a1fb09b | ||
|
|
99002f92f4 | ||
|
|
298d6a1a15 | ||
|
|
5a21f50230 | ||
|
|
5263dabd22 | ||
|
|
9b649f6c72 | ||
|
|
b903cd5b68 | ||
|
|
890b5c5202 | ||
|
|
a14e88d04d | ||
|
|
58e09b4c68 | ||
|
|
631201d541 | ||
|
|
0fbeb6d2cd | ||
|
|
11f8e2ffde | ||
|
|
055eb4a61a | ||
|
|
30c1c5c3d3 | ||
|
|
e034ec3207 | ||
|
|
8edc4bd24b | ||
|
|
6e1672f73c | ||
|
|
5e1f6f7317 | ||
|
|
386780ba12 | ||
|
|
e785971ba8 | ||
|
|
daaae07649 | ||
|
|
6cd567dc66 | ||
|
|
a541a7ee85 | ||
|
|
43572bba04 | ||
|
|
2a3a4456c1 | ||
|
|
15f8e6369b | ||
|
|
cfad9a19eb | ||
|
|
e4c3136433 | ||
|
|
73b8a26850 | ||
|
|
aa533b28fb | ||
|
|
9d70e09a57 | ||
|
|
17e18985e6 | ||
|
|
7c39aaf463 | ||
|
|
bae5c125e8 | ||
|
|
1c84fa0d97 | ||
|
|
6f583f9f0e | ||
|
|
217574b75c | ||
|
|
1378530aeb | ||
|
|
0b10ed4d88 | ||
|
|
a2887f5776 | ||
|
|
0f1d27f1e6 | ||
|
|
850ab0942b | ||
|
|
f5ae8f44b4 | ||
|
|
7f98cfd506 | ||
|
|
bc45a79b92 | ||
|
|
5003cf674d | ||
|
|
bc9cbc387c | ||
|
|
60a1e78869 | ||
|
|
37f5587085 | ||
|
|
fa6e3d3706 | ||
|
|
bb8bc875b4 | ||
|
|
b3dca737be | ||
|
|
9094f85487 | ||
|
|
1256bbfbaf | ||
|
|
24fe74f2f6 | ||
|
|
908f501e03 | ||
|
|
35507c7854 | ||
|
|
eb7102ecac | ||
|
|
ade6bfcbca | ||
|
|
fa98403aa8 | ||
|
|
3f0cb1637c | ||
|
|
42011d028e | ||
|
|
307bb0dea1 | ||
|
|
ec2a8347d4 | ||
|
|
e99b1c3ed8 | ||
|
|
99825f2663 | ||
|
|
afffdfbc5c | ||
|
|
cd874acfd5 | ||
|
|
34edbf469e | ||
|
|
d9ed30e436 | ||
|
|
30008de400 | ||
|
|
a5fa731545 | ||
|
|
493ee3c956 | ||
|
|
3dd574ee51 | ||
|
|
5416c19b2e | ||
|
|
2f31d80c7a | ||
|
|
27d1833854 | ||
|
|
84ed716908 | ||
|
|
6c9c9c7578 | ||
|
|
cc7b7b0689 | ||
|
|
5df8e05d1a | ||
|
|
b3b224b0ca | ||
|
|
75ab28ee5d | ||
|
|
aa9ea2b4ab | ||
|
|
1e6be99c36 | ||
|
|
49fb396bf8 | ||
|
|
e055c9ddc1 | ||
|
|
c708e390a7 | ||
|
|
d5ad26c934 | ||
|
|
144b7cd922 | ||
|
|
9e86fbb311 | ||
|
|
b528428d02 | ||
|
|
b3d7730e79 | ||
|
|
f2ba567ca4 | ||
|
|
8342f77087 | ||
|
|
7cade1b98f | ||
|
|
ee4c1fb36c | ||
|
|
dbc4e537fe | ||
|
|
e28990b96c | ||
|
|
408cf92c04 | ||
|
|
425af2e0dc | ||
|
|
22df860eca | ||
|
|
f395044d65 |
46
.github/ISSUE_TEMPLATE/bug_report.md
vendored
46
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -1,46 +0,0 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve Flux v2
|
||||
title: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
<!--
|
||||
|
||||
Find out more about your support options and getting help at
|
||||
|
||||
https://fluxcd.io/support/
|
||||
|
||||
-->
|
||||
|
||||
### Describe the bug
|
||||
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
### To Reproduce
|
||||
|
||||
Steps to reproduce the behaviour:
|
||||
|
||||
1. Provide Flux install instructions
|
||||
2. Provide a GitHub repository with Kubernetes manifests
|
||||
|
||||
### Expected behavior
|
||||
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
### Additional context
|
||||
|
||||
- Kubernetes version:
|
||||
- Git provider:
|
||||
- Container registry provider:
|
||||
|
||||
Below please provide the output of the following commands:
|
||||
|
||||
```cli
|
||||
flux --version
|
||||
flux check
|
||||
kubectl -n <namespace> get all
|
||||
kubectl -n <namespace> logs deploy/source-controller
|
||||
kubectl -n <namespace> logs deploy/kustomize-controller
|
||||
```
|
||||
85
.github/ISSUE_TEMPLATE/bug_report.yaml
vendored
Normal file
85
.github/ISSUE_TEMPLATE/bug_report.yaml
vendored
Normal file
@@ -0,0 +1,85 @@
|
||||
---
|
||||
name: Bug report
|
||||
description: Create a report to help us improve Flux
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## Support
|
||||
Find out more about your support options and getting help at: https://fluxcd.io/support/
|
||||
- type: textarea
|
||||
validations:
|
||||
required: true
|
||||
attributes:
|
||||
label: Describe the bug
|
||||
description: A clear description of what the bug is.
|
||||
- type: textarea
|
||||
validations:
|
||||
required: true
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
description: |
|
||||
Steps to reproduce the problem.
|
||||
placeholder: |
|
||||
For example:
|
||||
1. Install Flux with the additional image automation controllers
|
||||
2. Run command '...'
|
||||
3. See error
|
||||
- type: textarea
|
||||
validations:
|
||||
required: true
|
||||
attributes:
|
||||
label: Expected behavior
|
||||
description: A brief description of what you expected to happen.
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Screenshots and recordings
|
||||
description: |
|
||||
If applicable, add screenshots to help explain your problem. You can also record an asciinema session: https://asciinema.org/
|
||||
- type: input
|
||||
validations:
|
||||
required: true
|
||||
attributes:
|
||||
label: OS / Distro
|
||||
description: The OS / distro you are executing `flux` on. If not applicable, write `N/A`.
|
||||
placeholder: e.g. Windows 10, Ubuntu 20.04, Arch Linux, macOS 10.15...
|
||||
- type: input
|
||||
validations:
|
||||
required: true
|
||||
attributes:
|
||||
label: Flux version
|
||||
description: Run `flux --version` to check. If not applicable, write `N/A`.
|
||||
placeholder: e.g. 0.16.1
|
||||
- type: textarea
|
||||
validations:
|
||||
required: true
|
||||
attributes:
|
||||
label: Flux check
|
||||
description: Run `flux check` to check. If not applicable, write `N/A`.
|
||||
placeholder: |
|
||||
For example:
|
||||
► checking prerequisites
|
||||
✔ kubectl 1.21.0 >=1.18.0-0
|
||||
✔ Kubernetes 1.21.1 >=1.16.0-0
|
||||
► checking controllers
|
||||
✔ all checks passed
|
||||
- type: input
|
||||
attributes:
|
||||
label: Git provider
|
||||
description: If applicable, add the Git provider you are having problems with, e.g. GitHub (Enterprise), GitLab, etc.
|
||||
- type: input
|
||||
attributes:
|
||||
label: Container Registry provider
|
||||
description: If applicable, add the Container Registry provider you are having problems with, e.g. DockerHub, GitHub Packages, Quay.io, etc.
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Additional context
|
||||
description: Add any other context about the problem here. This can be logs (e.g. output from `flux logs`), environment specific caveats, etc.
|
||||
- type: checkboxes
|
||||
id: terms
|
||||
attributes:
|
||||
label: Code of Conduct
|
||||
description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/fluxcd/.github/blob/main/CODE_OF_CONDUCT.md)
|
||||
options:
|
||||
- label: I agree to follow this project's Code of Conduct
|
||||
required: true
|
||||
19
.github/aur/flux-bin/PKGBUILD.template
vendored
19
.github/aur/flux-bin/PKGBUILD.template
vendored
@@ -8,18 +8,20 @@ pkgdesc="Open and extensible continuous delivery solution for Kubernetes"
|
||||
url="https://fluxcd.io/"
|
||||
arch=("x86_64" "armv6h" "armv7h" "aarch64")
|
||||
license=("APACHE")
|
||||
optdepends=("kubectl")
|
||||
optdepends=('kubectl: for apply actions on the Kubernetes cluster',
|
||||
'bash-completion: auto-completion for flux in Bash',
|
||||
'zsh-completions: auto-completion for flux in ZSH')
|
||||
source_x86_64=(
|
||||
"$pkgname-$pkgver.tar.gz::https://github.com/fluxcd/flux2/releases/download/v${pkgver}/flux_${pkgver}_linux_amd64.tar.gz"
|
||||
"${pkgname}-${pkgver}.tar.gz::https://github.com/fluxcd/flux2/releases/download/v${pkgver}/flux_${pkgver}_linux_amd64.tar.gz"
|
||||
)
|
||||
source_armv6h=(
|
||||
"$pkgname-$pkgver.tar.gz::https://github.com/fluxcd/flux2/releases/download/v${pkgver}/flux_${pkgver}_linux_arm.tar.gz"
|
||||
"${pkgname}-${pkgver}.tar.gz::https://github.com/fluxcd/flux2/releases/download/v${pkgver}/flux_${pkgver}_linux_arm.tar.gz"
|
||||
)
|
||||
source_armv7h=(
|
||||
"$pkgname-$pkgver.tar.gz::https://github.com/fluxcd/flux2/releases/download/v${pkgver}/flux_${pkgver}_linux_arm.tar.gz"
|
||||
"${pkgname}-${pkgver}.tar.gz::https://github.com/fluxcd/flux2/releases/download/v${pkgver}/flux_${pkgver}_linux_arm.tar.gz"
|
||||
)
|
||||
source_aarch64=(
|
||||
"$pkgname-$pkgver.tar.gz::https://github.com/fluxcd/flux2/releases/download/v${pkgver}/flux_${pkgver}_linux_arm64.tar.gz"
|
||||
"${pkgname}-${pkgver}.tar.gz::https://github.com/fluxcd/flux2/releases/download/v${pkgver}/flux_${pkgver}_linux_arm64.tar.gz"
|
||||
)
|
||||
sha256sums_x86_64=(
|
||||
${SHA256SUM_AMD64}
|
||||
@@ -33,7 +35,12 @@ sha256sums_armv7h=(
|
||||
sha256sums_aarch64=(
|
||||
${SHA256SUM_ARM64}
|
||||
)
|
||||
_srcname=flux
|
||||
|
||||
package() {
|
||||
install -Dm755 flux "$pkgdir/usr/bin/flux"
|
||||
install -Dm755 ${_srcname} "${pkgdir}/usr/bin/${_srcname}"
|
||||
|
||||
"${pkgdir}/usr/bin/${_srcname}" completion bash | install -Dm644 /dev/stdin "${pkgdir}/usr/share/bash-completion/completions/${_srcname}"
|
||||
"${pkgdir}/usr/bin/${_srcname}" completion fish | install -Dm644 /dev/stdin "${pkgdir}/usr/share/fish/vendor_completions.d/${_srcname}.fish"
|
||||
"${pkgdir}/usr/bin/${_srcname}" completion zsh | install -Dm644 /dev/stdin "${pkgdir}/usr/share/zsh/site-functions/_${_srcname}"
|
||||
}
|
||||
|
||||
28
.github/aur/flux-go/PKGBUILD.template
vendored
28
.github/aur/flux-go/PKGBUILD.template
vendored
@@ -12,32 +12,40 @@ provides=("flux-bin")
|
||||
conflicts=("flux-bin")
|
||||
replaces=("flux-cli")
|
||||
depends=("glibc")
|
||||
makedepends=("go")
|
||||
optdepends=("kubectl")
|
||||
makedepends=('go>=1.16', 'kustomize>=3.0')
|
||||
optdepends=('kubectl: for apply actions on the Kubernetes cluster',
|
||||
'bash-completion: auto-completion for flux in Bash',
|
||||
'zsh-completions: auto-completion for flux in ZSH')
|
||||
source=(
|
||||
"$pkgname-$pkgver.tar.gz::https://github.com/fluxcd/flux2/archive/v$pkgver.tar.gz"
|
||||
"${pkgname}-${pkgver}.tar.gz::https://github.com/fluxcd/flux2/archive/v${pkgver}.tar.gz"
|
||||
)
|
||||
sha256sums=(
|
||||
${SHA256SUM}
|
||||
)
|
||||
_srcname=flux
|
||||
|
||||
build() {
|
||||
cd "flux2-$pkgver"
|
||||
cd "flux2-${pkgver}"
|
||||
export CGO_LDFLAGS="$LDFLAGS"
|
||||
export CGO_CFLAGS="$CFLAGS"
|
||||
export CGO_CXXFLAGS="$CXXFLAGS"
|
||||
export CGO_CPPFLAGS="$CPPFLAGS"
|
||||
export GOFLAGS="-buildmode=pie -trimpath -ldflags=-linkmode=external -mod=readonly -modcacherw"
|
||||
go build -ldflags "-X main.VERSION=$pkgver" -o flux-bin ./cmd/flux
|
||||
export GOFLAGS="-buildmode=pie -trimpath -mod=readonly -modcacherw"
|
||||
./manifests/scripts/bundle.sh "${PWD}/manifests" "${PWD}/cmd/flux/manifests"
|
||||
go build -ldflags "-linkmode=external -X main.VERSION=${pkgver}" -o ${_srcname} ./cmd/flux
|
||||
}
|
||||
|
||||
check() {
|
||||
cd "flux2-$pkgver"
|
||||
cd "flux2-${pkgver}"
|
||||
make test
|
||||
}
|
||||
|
||||
package() {
|
||||
cd "flux2-$pkgver"
|
||||
install -Dm755 flux-bin "$pkgdir/usr/bin/flux"
|
||||
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||
cd "flux2-${pkgver}"
|
||||
install -Dm755 ${_srcname} "${pkgdir}/usr/bin/${_srcname}"
|
||||
install -Dm644 LICENSE "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
|
||||
|
||||
"${pkgdir}/usr/bin/${_srcname}" completion bash | install -Dm644 /dev/stdin "${pkgdir}/usr/share/bash-completion/completions/${_srcname}"
|
||||
"${pkgdir}/usr/bin/${_srcname}" completion fish | install -Dm644 /dev/stdin "${pkgdir}/usr/share/fish/vendor_completions.d/${_srcname}.fish"
|
||||
"${pkgdir}/usr/bin/${_srcname}" completion zsh | install -Dm644 /dev/stdin "${pkgdir}/usr/share/zsh/site-functions/_${_srcname}"
|
||||
}
|
||||
|
||||
20
.github/aur/flux-scm/PKGBUILD.template
vendored
20
.github/aur/flux-scm/PKGBUILD.template
vendored
@@ -11,12 +11,15 @@ license=("APACHE")
|
||||
provides=("flux-bin")
|
||||
conflicts=("flux-bin")
|
||||
depends=("glibc")
|
||||
makedepends=("go")
|
||||
optdepends=("kubectl")
|
||||
makedepends=('go>=1.16', 'kustomize>=3.0')
|
||||
optdepends=('kubectl: for apply actions on the Kubernetes cluster',
|
||||
'bash-completion: auto-completion for flux in Bash',
|
||||
'zsh-completions: auto-completion for flux in ZSH')
|
||||
source=(
|
||||
"git+https://github.com/fluxcd/flux2.git"
|
||||
)
|
||||
md5sums=('SKIP')
|
||||
_srcname=flux
|
||||
|
||||
pkgver() {
|
||||
cd "flux2"
|
||||
@@ -29,8 +32,9 @@ build() {
|
||||
export CGO_CFLAGS="$CFLAGS"
|
||||
export CGO_CXXFLAGS="$CXXFLAGS"
|
||||
export CGO_CPPFLAGS="$CPPFLAGS"
|
||||
export GOFLAGS="-buildmode=pie -trimpath -ldflags=-linkmode=external -mod=readonly -modcacherw"
|
||||
go build -ldflags "-X main.VERSION=$pkgver" -o flux-bin ./cmd/flux
|
||||
export GOFLAGS="-buildmode=pie -trimpath -mod=readonly -modcacherw"
|
||||
make cmd/flux/manifests
|
||||
go build -ldflags "-linkmode=external -X main.VERSION=${pkgver}" -o ${_srcname} ./cmd/flux
|
||||
}
|
||||
|
||||
check() {
|
||||
@@ -40,6 +44,10 @@ check() {
|
||||
|
||||
package() {
|
||||
cd "flux2"
|
||||
install -Dm755 flux-bin "$pkgdir/usr/bin/flux"
|
||||
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||
install -Dm755 ${_srcname} "${pkgdir}/usr/bin/${_srcname}"
|
||||
install -Dm644 LICENSE "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
|
||||
|
||||
"${pkgdir}/usr/bin/${_srcname}" completion bash | install -Dm644 /dev/stdin "${pkgdir}/usr/share/bash-completion/completions/${_srcname}"
|
||||
"${pkgdir}/usr/bin/${_srcname}" completion fish | install -Dm644 /dev/stdin "${pkgdir}/usr/share/fish/vendor_completions.d/${_srcname}.fish"
|
||||
"${pkgdir}/usr/bin/${_srcname}" completion zsh | install -Dm644 /dev/stdin "${pkgdir}/usr/share/zsh/site-functions/_${_srcname}"
|
||||
}
|
||||
|
||||
42
.github/runners/README.md
vendored
Normal file
42
.github/runners/README.md
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
# Flux GitHub runners
|
||||
|
||||
How to provision GitHub Actions self-hosted runners for Flux conformance testing.
|
||||
|
||||
## ARM64 Instance specs
|
||||
|
||||
In order to add a new runner to the GitHub Actions pool,
|
||||
first create an instance on Oracle Cloud with the following configuration:
|
||||
- OS: Canonical Ubuntu 20.04
|
||||
- Shape: VM.Standard.A1.Flex
|
||||
- OCPU Count: 2
|
||||
- Memory (GB): 12
|
||||
- Network Bandwidth (Gbps): 2
|
||||
- Local Disk: Block Storage Only
|
||||
|
||||
Note that the instance image source must be **Canonical Ubuntu** instead of the default Oracle Linux.
|
||||
|
||||
## ARM64 Instance setup
|
||||
|
||||
- SSH into a newly created instance
|
||||
```shell
|
||||
ssh ubuntu@<instance-public-IP>
|
||||
```
|
||||
- Create the action runner dir
|
||||
```shell
|
||||
mkdir -p actions-runner && cd actions-runner
|
||||
```
|
||||
- Download the provisioning script
|
||||
```shell
|
||||
curl -sL https://raw.githubusercontent.com/fluxcd/flux2/main/.github/runners/arm64.sh > arm64.sh \
|
||||
&& chmod +x ./arm64.sh
|
||||
```
|
||||
- Retrieve the GitHub runner token from the repository [settings page](https://github.com/fluxcd/flux2/settings/actions/runners/new?arch=arm64&os=linux)
|
||||
- Run the provisioning script passing the token as the first argument
|
||||
```shell
|
||||
sudo ./arm64.sh <TOKEN>
|
||||
```
|
||||
- Reboot the instance
|
||||
```shell
|
||||
sudo reboot
|
||||
```
|
||||
- Navigate to the GitHub repository [runners page](https://github.com/fluxcd/flux2/settings/actions/runners) and check the runner status
|
||||
73
.github/runners/arm64.sh
vendored
Executable file
73
.github/runners/arm64.sh
vendored
Executable file
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Copyright 2021 The Flux authors. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# This script is meant to be run locally and in CI to validate the Kubernetes
|
||||
# manifests (including Flux custom resources) before changes are merged into
|
||||
# the branch synced by Flux in-cluster.
|
||||
|
||||
set -eu
|
||||
|
||||
REPOSITORY_TOKEN=$1
|
||||
REPOSITORY_URL=${2:-https://github.com/fluxcd/flux2}
|
||||
|
||||
KIND_VERSION=0.11.1
|
||||
KUBECTL_VERSION=1.21.2
|
||||
KUSTOMIZE_VERSION=4.1.3
|
||||
GITHUB_RUNNER_VERSION=2.278.0
|
||||
PACKAGES="apt-transport-https ca-certificates software-properties-common build-essential libssl-dev gnupg lsb-release jq"
|
||||
|
||||
# install prerequisites
|
||||
apt-get update \
|
||||
&& apt-get install -y -q ${PACKAGES} \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# install docker
|
||||
curl -fsSL https://get.docker.com -o get-docker.sh \
|
||||
&& chmod +x get-docker.sh
|
||||
./get-docker.sh
|
||||
systemctl enable docker.service
|
||||
systemctl enable containerd.service
|
||||
usermod -aG docker ubuntu
|
||||
|
||||
# install kind
|
||||
curl -Lo ./kind https://kind.sigs.k8s.io/dl/v${KIND_VERSION}/kind-linux-arm64
|
||||
install -o root -g root -m 0755 kind /usr/local/bin/kind
|
||||
|
||||
# install kubectl
|
||||
curl -LO "https://dl.k8s.io/release/v${KUBECTL_VERSION}/bin/linux/arm64/kubectl"
|
||||
install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
|
||||
|
||||
# install kustomize
|
||||
curl -Lo ./kustomize.tar.gz https://github.com/kubernetes-sigs/kustomize/releases/download/kustomize%2Fv${KUSTOMIZE_VERSION}/kustomize_v${KUSTOMIZE_VERSION}_linux_arm64.tar.gz \
|
||||
&& tar -zxvf kustomize.tar.gz \
|
||||
&& rm kustomize.tar.gz
|
||||
install -o root -g root -m 0755 kustomize /usr/local/bin/kustomize
|
||||
|
||||
# download runner
|
||||
curl -o actions-runner-linux-arm64.tar.gz -L https://github.com/actions/runner/releases/download/v${GITHUB_RUNNER_VERSION}/actions-runner-linux-arm64-${GITHUB_RUNNER_VERSION}.tar.gz \
|
||||
&& tar xzf actions-runner-linux-arm64.tar.gz \
|
||||
&& rm actions-runner-linux-arm64.tar.gz
|
||||
|
||||
# install runner dependencies
|
||||
./bin/installdependencies.sh
|
||||
|
||||
# register runner with GitHub
|
||||
sudo -u ubuntu ./config.sh --unattended --url ${REPOSITORY_URL} --token ${REPOSITORY_TOKEN}
|
||||
|
||||
# start runner
|
||||
./svc.sh install
|
||||
./svc.sh start
|
||||
74
.github/workflows/bootstrap.yaml
vendored
74
.github/workflows/bootstrap.yaml
vendored
@@ -2,12 +2,14 @@ name: bootstrap
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- '*'
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
|
||||
jobs:
|
||||
github:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
@@ -15,58 +17,82 @@ jobs:
|
||||
uses: actions/cache@v1
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
key: ${{ runner.os }}-go1.16-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-go-
|
||||
${{ runner.os }}-go1.16-
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.15.x
|
||||
go-version: 1.16.x
|
||||
- name: Setup Kubernetes
|
||||
uses: engineerd/setup-kind@v0.5.0
|
||||
with:
|
||||
version: v0.11.1
|
||||
image: kindest/node:v1.21.1@sha256:69860bda5563ac81e3c0057d654b5253219618a22ec3a346306239bba8cfa1a6
|
||||
- name: Setup Kustomize
|
||||
uses: fluxcd/pkg//actions/kustomize@main
|
||||
- name: Build
|
||||
run: |
|
||||
make cmd/flux/manifests
|
||||
go build -o /tmp/flux ./cmd/flux
|
||||
- name: Set outputs
|
||||
id: vars
|
||||
run: echo "::set-output name=sha_short::$(git rev-parse --short HEAD)"
|
||||
- name: Build
|
||||
run: sudo go build -o ./bin/flux ./cmd/flux
|
||||
run: |
|
||||
REPOSITORY_NAME=${{ github.event.repository.name }}
|
||||
BRANCH_NAME=${GITHUB_REF##*/}
|
||||
COMMIT_SHA=$(git rev-parse HEAD)
|
||||
PSEUDO_RAND_SUFFIX=$(echo "${BRANCH_NAME}-${COMMIT_SHA}" | shasum | awk '{print $1}')
|
||||
TEST_REPO_NAME="${REPOSITORY_NAME}-${PSEUDO_RAND_SUFFIX}"
|
||||
echo "::set-output name=test_repo_name::$TEST_REPO_NAME"
|
||||
- name: bootstrap init
|
||||
run: |
|
||||
./bin/flux bootstrap github --manifests ./manifests/install/ \
|
||||
/tmp/flux bootstrap github --manifests ./manifests/install/ \
|
||||
--owner=fluxcd-testing \
|
||||
--repository=flux-test-${{ steps.vars.outputs.sha_short }} \
|
||||
--repository=${{ steps.vars.outputs.test_repo_name }} \
|
||||
--branch=main \
|
||||
--path=test-cluster
|
||||
--path=test-cluster \
|
||||
--team=team-z
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITPROVIDER_BOT_TOKEN }}
|
||||
- name: bootstrap no-op
|
||||
run: |
|
||||
./bin/flux bootstrap github --manifests ./manifests/install/ \
|
||||
/tmp/flux bootstrap github --manifests ./manifests/install/ \
|
||||
--owner=fluxcd-testing \
|
||||
--repository=flux-test-${{ steps.vars.outputs.sha_short }} \
|
||||
--repository=${{ steps.vars.outputs.test_repo_name }} \
|
||||
--branch=main \
|
||||
--path=test-cluster
|
||||
--path=test-cluster \
|
||||
--team=team-z
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITPROVIDER_BOT_TOKEN }}
|
||||
- name: libgit2
|
||||
run: |
|
||||
/tmp/flux create source git test-libgit2 \
|
||||
--url=ssh://git@github.com/fluxcd-testing/${{ steps.vars.outputs.test_repo_name }} \
|
||||
--git-implementation=libgit2 \
|
||||
--secret-ref=flux-system \
|
||||
--branch=main
|
||||
- name: uninstall
|
||||
run: |
|
||||
./bin/flux uninstall --resources --crds -s --timeout=10m
|
||||
/tmp/flux uninstall -s --keep-namespace
|
||||
kubectl delete ns flux-system --timeout=10m --wait=true
|
||||
- name: bootstrap reinstall
|
||||
run: |
|
||||
./bin/flux bootstrap github --manifests ./manifests/install/ \
|
||||
/tmp/flux bootstrap github --manifests ./manifests/install/ \
|
||||
--owner=fluxcd-testing \
|
||||
--repository=flux-test-${{ steps.vars.outputs.sha_short }} \
|
||||
--repository=${{ steps.vars.outputs.test_repo_name }} \
|
||||
--branch=main \
|
||||
--path=test-cluster
|
||||
--path=test-cluster \
|
||||
--team=team-z
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITPROVIDER_BOT_TOKEN }}
|
||||
- name: delete repository
|
||||
run: |
|
||||
./bin/flux bootstrap github --manifests ./manifests/install/ \
|
||||
--owner=fluxcd-testing \
|
||||
--repository=flux-test-${{ steps.vars.outputs.sha_short }} \
|
||||
--branch=main \
|
||||
--path=test-cluster \
|
||||
--delete
|
||||
curl \
|
||||
-X DELETE \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
-H "Authorization: token ${GITHUB_TOKEN}" \
|
||||
--fail --silent \
|
||||
https://api.github.com/repos/fluxcd-testing/${{ steps.vars.outputs.test_repo_name }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITPROVIDER_BOT_TOKEN }}
|
||||
- name: Debug failure
|
||||
|
||||
77
.github/workflows/docs.yaml
vendored
77
.github/workflows/docs.yaml
vendored
@@ -1,77 +0,0 @@
|
||||
name: Publish docs via GitHub Pages
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- docs*
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Deploy docs
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout master
|
||||
uses: actions/checkout@v1
|
||||
- name: Copy assets
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
controller_version() {
|
||||
sed -n "s/.*$1\/archive\/\(.*\).zip.*/\1/p;n" manifests/bases/$1/kustomization.yaml
|
||||
}
|
||||
|
||||
{
|
||||
# source-controller CRDs
|
||||
SOURCE_VER=$(controller_version source-controller)
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/source-controller/$SOURCE_VER/docs/api/source.md" > docs/components/source/api.md
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/source-controller/$SOURCE_VER/docs/spec/v1beta1/gitrepositories.md" > docs/components/source/gitrepositories.md
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/source-controller/$SOURCE_VER/docs/spec/v1beta1/helmrepositories.md" > docs/components/source/helmrepositories.md
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/source-controller/$SOURCE_VER/docs/spec/v1beta1/helmcharts.md" > docs/components/source/helmcharts.md
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/source-controller/$SOURCE_VER/docs/spec/v1beta1/buckets.md" > docs/components/source/buckets.md
|
||||
}
|
||||
|
||||
{
|
||||
# kustomize-controller CRDs
|
||||
KUSTOMIZE_VER=$(controller_version kustomize-controller)
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/kustomize-controller/$KUSTOMIZE_VER/docs/api/kustomize.md" > docs/components/kustomize/api.md
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/kustomize-controller/$KUSTOMIZE_VER/docs/spec/v1beta1/kustomization.md" > docs/components/kustomize/kustomization.md
|
||||
}
|
||||
|
||||
{
|
||||
# helm-controller CRDs
|
||||
HELM_VER=$(controller_version helm-controller)
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/helm-controller/$HELM_VER/docs/api/helmrelease.md" > docs/components/helm/api.md
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/helm-controller/$HELM_VER/docs/spec/v2beta1/helmreleases.md" > docs/components/helm/helmreleases.md
|
||||
}
|
||||
|
||||
{
|
||||
# notification-controller CRDs
|
||||
NOTIFICATION_VER=$(controller_version notification-controller)
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/notification-controller/$NOTIFICATION_VER/docs/api/notification.md" > docs/components/notification/api.md
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/notification-controller/$NOTIFICATION_VER/docs/spec/v1beta1/event.md" > docs/components/notification/event.md
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/notification-controller/$NOTIFICATION_VER/docs/spec/v1beta1/alert.md" > docs/components/notification/alert.md
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/notification-controller/$NOTIFICATION_VER/docs/spec/v1beta1/provider.md" > docs/components/notification/provider.md
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/notification-controller/$NOTIFICATION_VER/docs/spec/v1beta1/receiver.md" > docs/components/notification/receiver.md
|
||||
}
|
||||
|
||||
{
|
||||
# image-*-controller CRDs; these use the same API group
|
||||
IMG_REFL_VER=$(controller_version image-reflector-controller)
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/image-reflector-controller/$IMG_REFL_VER/docs/api/image-reflector.md" > docs/components/image/reflector-api.md
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/image-reflector-controller/$IMG_REFL_VER/docs/spec/v1alpha1/imagerepositories.md" > docs/components/image/imagerepositories.md
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/image-reflector-controller/$IMG_REFL_VER/docs/spec/v1alpha1/imagepolicies.md" > docs/components/image/imagepolicies.md
|
||||
|
||||
IMG_AUTO_VER=$(controller_version image-automation-controller)
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/image-automation-controller/$IMG_AUTO_VER/docs/api/image-automation.md" > docs/components/image/automation-api.md
|
||||
curl -# -Lf "https://raw.githubusercontent.com/fluxcd/image-automation-controller/$IMG_AUTO_VER/docs/spec/v1alpha1/imageupdateautomations.md" > docs/components/image/imageupdateautomations.md
|
||||
}
|
||||
|
||||
{
|
||||
# install script
|
||||
cp install/flux.sh docs/install.sh
|
||||
}
|
||||
- name: Deploy docs
|
||||
uses: mhausenblas/mkdocs-deploy-gh-pages@master
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
CUSTOM_DOMAIN: toolkit.fluxcd.io
|
||||
38
.github/workflows/e2e-arm64.yaml
vendored
Normal file
38
.github/workflows/e2e-arm64.yaml
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
name: e2e-arm64
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [ main, update-components, arm64-e2e ]
|
||||
|
||||
jobs:
|
||||
ampere:
|
||||
# Runner info
|
||||
# Owner: Stefan Prodan
|
||||
# Docs: https://github.com/fluxcd/flux2/tree/main/.github/runners
|
||||
runs-on: [self-hosted, Linux, ARM64]
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.16.x
|
||||
- name: Prepare
|
||||
id: prep
|
||||
run: |
|
||||
echo ::set-output name=CLUSTER::arm64-${GITHUB_SHA:0:7}-$(date +%s)
|
||||
echo ::set-output name=CONTEXT::kind-arm64-${GITHUB_SHA:0:7}-$(date +%s)
|
||||
- name: Build
|
||||
run: |
|
||||
make build
|
||||
- name: Setup Kubernetes Kind
|
||||
run: |
|
||||
kind create cluster --name ${{ steps.prep.outputs.CLUSTER }} --kubeconfig=/tmp/${{ steps.prep.outputs.CLUSTER }}
|
||||
- name: Run e2e tests
|
||||
run: TEST_KUBECONFIG=/tmp/${{ steps.prep.outputs.CLUSTER }} make e2e
|
||||
- name: Cleanup
|
||||
if: always()
|
||||
run: |
|
||||
kind delete cluster --name ${{ steps.prep.outputs.CLUSTER }}
|
||||
rm /tmp/${{ steps.prep.outputs.CLUSTER }}
|
||||
131
.github/workflows/e2e.yaml
vendored
131
.github/workflows/e2e.yaml
vendored
@@ -1,10 +1,10 @@
|
||||
name: e2e
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
|
||||
jobs:
|
||||
kind:
|
||||
@@ -16,25 +16,33 @@ jobs:
|
||||
uses: actions/cache@v1
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
key: ${{ runner.os }}-go1.16-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-go-
|
||||
${{ runner.os }}-go1.16-
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.15.x
|
||||
go-version: 1.16.x
|
||||
- name: Setup Kubernetes
|
||||
uses: engineerd/setup-kind@v0.5.0
|
||||
with:
|
||||
version: "v0.10.0"
|
||||
image: kindest/node:v1.20.2@sha256:8f7ea6e7642c0da54f04a7ee10431549c0257315b3a634f6ef2fecaaedb19bab
|
||||
version: v0.11.1
|
||||
image: kindest/node:v1.21.1@sha256:69860bda5563ac81e3c0057d654b5253219618a22ec3a346306239bba8cfa1a6
|
||||
config: .github/kind/config.yaml # disable KIND-net
|
||||
- name: Setup envtest
|
||||
uses: fluxcd/pkg/actions/envtest@main
|
||||
with:
|
||||
version: "1.21.x"
|
||||
- name: Setup Calico for network policy
|
||||
run: |
|
||||
kubectl apply -f https://docs.projectcalico.org/v3.16/manifests/calico.yaml
|
||||
kubectl -n kube-system set env daemonset/calico-node FELIX_IGNORELOOSERPF=true
|
||||
- name: Run test
|
||||
- name: Setup Kustomize
|
||||
uses: fluxcd/pkg//actions/kustomize@main
|
||||
- name: Run tests
|
||||
run: make test
|
||||
- name: Run e2e tests
|
||||
run: TEST_KUBECONFIG=$HOME/.kube/config make e2e
|
||||
- name: Check if working tree is dirty
|
||||
run: |
|
||||
if [[ $(git diff --stat) != '' ]]; then
|
||||
@@ -43,43 +51,44 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
- name: Build
|
||||
run: sudo go build -o ./bin/flux ./cmd/flux
|
||||
run: |
|
||||
go build -o /tmp/flux ./cmd/flux
|
||||
- name: flux check --pre
|
||||
run: |
|
||||
./bin/flux check --pre
|
||||
/tmp/flux check --pre
|
||||
- name: flux install --manifests
|
||||
run: |
|
||||
./bin/flux install --manifests ./manifests/install/
|
||||
/tmp/flux install --manifests ./manifests/install/
|
||||
- name: flux create secret
|
||||
run: |
|
||||
./bin/flux create secret git git-ssh-test \
|
||||
/tmp/flux create secret git git-ssh-test \
|
||||
--url ssh://git@github.com/stefanprodan/podinfo
|
||||
./bin/flux create secret git git-https-test \
|
||||
/tmp/flux create secret git git-https-test \
|
||||
--url https://github.com/stefanprodan/podinfo \
|
||||
--username=test --password=test
|
||||
./bin/flux create secret helm helm-test \
|
||||
/tmp/flux create secret helm helm-test \
|
||||
--username=test --password=test
|
||||
- name: flux create source git
|
||||
run: |
|
||||
./bin/flux create source git podinfo \
|
||||
/tmp/flux create source git podinfo \
|
||||
--url https://github.com/stefanprodan/podinfo \
|
||||
--tag-semver=">=3.2.3"
|
||||
- name: flux create source git export apply
|
||||
run: |
|
||||
./bin/flux create source git podinfo-export \
|
||||
/tmp/flux create source git podinfo-export \
|
||||
--url https://github.com/stefanprodan/podinfo \
|
||||
--tag-semver=">=3.2.3" \
|
||||
--export | kubectl apply -f -
|
||||
./bin/flux delete source git podinfo-export --silent
|
||||
/tmp/flux delete source git podinfo-export --silent
|
||||
- name: flux get sources git
|
||||
run: |
|
||||
./bin/flux get sources git
|
||||
/tmp/flux get sources git
|
||||
- name: flux get sources git --all-namespaces
|
||||
run: |
|
||||
./bin/flux get sources git --all-namespaces
|
||||
/tmp/flux get sources git --all-namespaces
|
||||
- name: flux create kustomization
|
||||
run: |
|
||||
./bin/flux create kustomization podinfo \
|
||||
/tmp/flux create kustomization podinfo \
|
||||
--source=podinfo \
|
||||
--path="./deploy/overlays/dev" \
|
||||
--prune=true \
|
||||
@@ -88,113 +97,107 @@ jobs:
|
||||
--health-check="Deployment/frontend.dev" \
|
||||
--health-check="Deployment/backend.dev" \
|
||||
--health-check-timeout=3m
|
||||
- name: flux trace
|
||||
run: |
|
||||
/tmp/flux trace frontend \
|
||||
--kind=deployment \
|
||||
--api-version=apps/v1 \
|
||||
--namespace=dev
|
||||
- name: flux reconcile kustomization --with-source
|
||||
run: |
|
||||
./bin/flux reconcile kustomization podinfo --with-source
|
||||
/tmp/flux reconcile kustomization podinfo --with-source
|
||||
- name: flux get kustomizations
|
||||
run: |
|
||||
./bin/flux get kustomizations
|
||||
/tmp/flux get kustomizations
|
||||
- name: flux get kustomizations --all-namespaces
|
||||
run: |
|
||||
./bin/flux get kustomizations --all-namespaces
|
||||
/tmp/flux get kustomizations --all-namespaces
|
||||
- name: flux suspend kustomization
|
||||
run: |
|
||||
./bin/flux suspend kustomization podinfo
|
||||
/tmp/flux suspend kustomization podinfo
|
||||
- name: flux resume kustomization
|
||||
run: |
|
||||
./bin/flux resume kustomization podinfo
|
||||
/tmp/flux resume kustomization podinfo
|
||||
- name: flux export
|
||||
run: |
|
||||
./bin/flux export source git --all
|
||||
./bin/flux export kustomization --all
|
||||
/tmp/flux export source git --all
|
||||
/tmp/flux export kustomization --all
|
||||
- name: flux delete kustomization
|
||||
run: |
|
||||
./bin/flux delete kustomization podinfo --silent
|
||||
/tmp/flux delete kustomization podinfo --silent
|
||||
- name: flux create source helm
|
||||
run: |
|
||||
./bin/flux create source helm podinfo \
|
||||
/tmp/flux create source helm podinfo \
|
||||
--url https://stefanprodan.github.io/podinfo
|
||||
- name: flux create helmrelease --source=HelmRepository/podinfo
|
||||
run: |
|
||||
./bin/flux create hr podinfo-helm \
|
||||
/tmp/flux create hr podinfo-helm \
|
||||
--target-namespace=default \
|
||||
--source=HelmRepository/podinfo \
|
||||
--source=HelmRepository/podinfo.flux-system \
|
||||
--chart=podinfo \
|
||||
--chart-version=">4.0.0 <5.0.0"
|
||||
- name: flux create helmrelease --source=GitRepository/podinfo
|
||||
run: |
|
||||
./bin/flux create hr podinfo-git \
|
||||
/tmp/flux create hr podinfo-git \
|
||||
--target-namespace=default \
|
||||
--source=GitRepository/podinfo \
|
||||
--chart=./charts/podinfo
|
||||
- name: flux reconcile helmrelease --with-source
|
||||
run: |
|
||||
./bin/flux reconcile helmrelease podinfo-git --with-source
|
||||
/tmp/flux reconcile helmrelease podinfo-git --with-source
|
||||
- name: flux get helmreleases
|
||||
run: |
|
||||
./bin/flux get helmreleases
|
||||
/tmp/flux get helmreleases
|
||||
- name: flux get helmreleases --all-namespaces
|
||||
run: |
|
||||
./bin/flux get helmreleases --all-namespaces
|
||||
/tmp/flux get helmreleases --all-namespaces
|
||||
- name: flux export helmrelease
|
||||
run: |
|
||||
./bin/flux export hr --all
|
||||
/tmp/flux export hr --all
|
||||
- name: flux delete helmrelease podinfo-helm
|
||||
run: |
|
||||
./bin/flux delete hr podinfo-helm --silent
|
||||
/tmp/flux delete hr podinfo-helm --silent
|
||||
- name: flux delete helmrelease podinfo-git
|
||||
run: |
|
||||
./bin/flux delete hr podinfo-git --silent
|
||||
/tmp/flux delete hr podinfo-git --silent
|
||||
- name: flux delete source helm
|
||||
run: |
|
||||
./bin/flux delete source helm podinfo --silent
|
||||
/tmp/flux delete source helm podinfo --silent
|
||||
- name: flux delete source git
|
||||
run: |
|
||||
./bin/flux delete source git podinfo --silent
|
||||
/tmp/flux delete source git podinfo --silent
|
||||
- name: flux create tenant
|
||||
run: |
|
||||
./bin/flux create tenant dev-team --with-namespace=apps
|
||||
./bin/flux -n apps create source helm podinfo \
|
||||
/tmp/flux create tenant dev-team --with-namespace=apps
|
||||
/tmp/flux -n apps create source helm podinfo \
|
||||
--url https://stefanprodan.github.io/podinfo
|
||||
./bin/flux -n apps create hr podinfo-helm \
|
||||
/tmp/flux -n apps create hr podinfo-helm \
|
||||
--source=HelmRepository/podinfo \
|
||||
--chart=podinfo \
|
||||
--chart-version="5.0.x" \
|
||||
--service-account=dev-team
|
||||
- name: flux create image repository
|
||||
run: |
|
||||
./bin/flux create image repository podinfo \
|
||||
--image=ghcr.io/stefanprodan/podinfo \
|
||||
--interval=1m
|
||||
- name: flux create image policy
|
||||
run: |
|
||||
./bin/flux create image policy podinfo \
|
||||
--image-ref=podinfo \
|
||||
--interval=1m \
|
||||
--semver=5.0.x
|
||||
- name: flux get image policy
|
||||
run: |
|
||||
./bin/flux get image policy podinfo | grep '5.0.3'
|
||||
- name: flux2-kustomize-helm-example
|
||||
run: |
|
||||
./bin/flux create source git flux-system \
|
||||
/tmp/flux create source git flux-system \
|
||||
--url=https://github.com/fluxcd/flux2-kustomize-helm-example \
|
||||
--branch=main
|
||||
./bin/flux create kustomization flux-system \
|
||||
--branch=main \
|
||||
--recurse-submodules
|
||||
/tmp/flux create kustomization flux-system \
|
||||
--source=flux-system \
|
||||
--path=./clusters/staging
|
||||
kubectl -n flux-system wait kustomization/apps --for=condition=ready --timeout=2m
|
||||
kubectl -n flux-system wait kustomization/apps --for=condition=ready --timeout=5m
|
||||
- name: flux check
|
||||
run: |
|
||||
./bin/flux check
|
||||
/tmp/flux check
|
||||
- name: flux uninstall
|
||||
run: |
|
||||
./bin/flux uninstall --crds --silent --timeout=10m
|
||||
/tmp/flux uninstall --silent
|
||||
- name: Debug failure
|
||||
if: failure()
|
||||
run: |
|
||||
kubectl version --client --short
|
||||
kubectl -n flux-system get all
|
||||
kubectl -n flux-system describe pods
|
||||
kubectl -n flux-system get kustomizations -oyaml
|
||||
kubectl -n flux-system logs deploy/source-controller
|
||||
kubectl -n flux-system logs deploy/kustomize-controller
|
||||
|
||||
25
.github/workflows/fossa.yml
vendored
25
.github/workflows/fossa.yml
vendored
@@ -1,25 +0,0 @@
|
||||
name: FOSSA
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: "^1.14.x"
|
||||
- name: Add GOPATH to GITHUB_ENV
|
||||
run: echo "GOPATH=$(go env GOPATH)" >>"$GITHUB_ENV"
|
||||
- name: Add GOPATH to GITHUB_PATH
|
||||
run: echo "$GOPATH/bin" >>"$GITHUB_PATH"
|
||||
- name: Run FOSSA scan and upload build data
|
||||
uses: fossa-contrib/fossa-action@v1
|
||||
with:
|
||||
# FOSSA Push-Only API Token
|
||||
fossa-api-key: 5ee8bf422db1471e0bcf2bcb289185de
|
||||
github-token: ${{ github.token }}
|
||||
@@ -2,9 +2,9 @@ name: rebase
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened]
|
||||
types: [ opened ]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
types: [ created ]
|
||||
|
||||
jobs:
|
||||
rebase:
|
||||
70
.github/workflows/release.yaml
vendored
70
.github/workflows/release.yaml
vendored
@@ -2,8 +2,7 @@ name: release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
tags: [ 'v*' ]
|
||||
|
||||
jobs:
|
||||
goreleaser:
|
||||
@@ -16,7 +15,27 @@ jobs:
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.15.x
|
||||
go-version: 1.16.x
|
||||
- name: Setup QEMU
|
||||
uses: docker/setup-qemu-action@v1
|
||||
with:
|
||||
platforms: all
|
||||
- name: Setup Docker Buildx
|
||||
id: buildx
|
||||
uses: docker/setup-buildx-action@v1
|
||||
with:
|
||||
buildkitd-flags: "--debug"
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: fluxcdbot
|
||||
password: ${{ secrets.GHCR_TOKEN }}
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
username: fluxcdbot
|
||||
password: ${{ secrets.DOCKER_FLUXCD_PASSWORD }}
|
||||
- name: Download release notes utility
|
||||
env:
|
||||
GH_REL_URL: https://github.com/buchanae/github-release-notes/releases/download/0.2.0/github-release-notes-linux-amd64-0.2.0.tar.gz
|
||||
@@ -29,39 +48,22 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Setup Kustomize
|
||||
uses: fluxcd/pkg//actions/kustomize@main
|
||||
- name: Generate manifests tarball
|
||||
run: |
|
||||
mkdir -p ./output
|
||||
files=""
|
||||
|
||||
# build controllers
|
||||
for controller in ./manifests/bases/*/; do
|
||||
output_path="./output/$(basename $controller).yaml"
|
||||
echo "building $controller to $output_path"
|
||||
|
||||
kustomize build $controller > $output_path
|
||||
files+=" $(basename $output_path)"
|
||||
done
|
||||
|
||||
# build rbac
|
||||
rbac_path="./manifests/rbac"
|
||||
rbac_output_path="./output/rbac.yaml"
|
||||
echo "building $rbac_path to $rbac_output_path"
|
||||
kustomize build $rbac_path > $rbac_output_path
|
||||
files+=" $(basename $rbac_output_path)"
|
||||
|
||||
# build policies
|
||||
policies_path="./manifests/policies"
|
||||
policies_output_path="./output/policies.yaml"
|
||||
echo "building $policies_path to $policies_output_path"
|
||||
kustomize build $policies_path > $policies_output_path
|
||||
files+=" $(basename $policies_output_path)"
|
||||
|
||||
# create tarball
|
||||
cd ./output && tar -cvzf manifests.tar.gz $files
|
||||
- name: Generate install manifest
|
||||
- name: Generate manifests
|
||||
run: |
|
||||
make cmd/flux/manifests
|
||||
./manifests/scripts/bundle.sh "" ./output manifests.tar.gz
|
||||
kustomize build ./manifests/install > ./output/install.yaml
|
||||
- name: Build CRDs
|
||||
run: |
|
||||
kustomize build manifests/crds > all-crds.yaml
|
||||
- name: Generate OpenAPI JSON schemas from CRDs
|
||||
uses: fluxcd/pkg//actions/crdjsonschema@main
|
||||
with:
|
||||
crd: all-crds.yaml
|
||||
output: schemas
|
||||
- name: Archive the OpenAPI JSON schemas
|
||||
run: |
|
||||
tar -czvf ./output/crd-schemas.tar.gz -C schemas .
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v1
|
||||
with:
|
||||
|
||||
60
.github/workflows/scan.yaml
vendored
Normal file
60
.github/workflows/scan.yaml
vendored
Normal file
@@ -0,0 +1,60 @@
|
||||
name: Scan
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
schedule:
|
||||
- cron: '18 10 * * 3'
|
||||
|
||||
jobs:
|
||||
fossa:
|
||||
name: FOSSA
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Run FOSSA scan and upload build data
|
||||
uses: fossa-contrib/fossa-action@v1
|
||||
with:
|
||||
# FOSSA Push-Only API Token
|
||||
fossa-api-key: 5ee8bf422db1471e0bcf2bcb289185de
|
||||
github-token: ${{ github.token }}
|
||||
|
||||
snyk:
|
||||
name: Snyk
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Setup Kustomize
|
||||
uses: fluxcd/pkg//actions/kustomize@main
|
||||
- name: Build manifests
|
||||
run: |
|
||||
make cmd/flux/manifests
|
||||
- name: Run Snyk to check for vulnerabilities
|
||||
uses: snyk/actions/golang@master
|
||||
continue-on-error: true
|
||||
env:
|
||||
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
|
||||
with:
|
||||
args: --sarif-file-output=snyk.sarif
|
||||
- name: Upload result to GitHub Code Scanning
|
||||
uses: github/codeql-action/upload-sarif@v1
|
||||
with:
|
||||
sarif_file: snyk.sarif
|
||||
|
||||
codeql:
|
||||
name: CodeQL
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v1
|
||||
with:
|
||||
languages: go
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v1
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v1
|
||||
94
.github/workflows/update.yaml
vendored
Normal file
94
.github/workflows/update.yaml
vendored
Normal file
@@ -0,0 +1,94 @@
|
||||
name: Update Components
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "0 * * * *"
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
update-components:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v2
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.16.x
|
||||
- name: Update component versions
|
||||
id: update
|
||||
run: |
|
||||
PR_BODY=""
|
||||
|
||||
bump_version() {
|
||||
local LATEST_VERSION=$(curl -s https://api.github.com/repos/fluxcd/$1/releases | jq -r 'sort_by(.published_at) | .[-1] | .tag_name')
|
||||
local CTRL_VERSION=$(sed -n "s/.*$1\/releases\/download\/\(.*\)\/.*/\1/p;n" manifests/bases/$1/kustomization.yaml)
|
||||
local CRD_VERSION=$(sed -n "s/.*$1\/releases\/download\/\(.*\)\/.*/\1/p" manifests/crds/kustomization.yaml)
|
||||
local MOD_VERSION=$(go list -m -f '{{ .Version }}' "github.com/fluxcd/$1/api")
|
||||
|
||||
local changed=false
|
||||
|
||||
if [[ "${CTRL_VERSION}" != "${LATEST_VERSION}" ]]; then
|
||||
sed -i "s/\($1\/releases\/download\/\)v.*\(\/.*\)/\1${LATEST_VERSION}\2/g" "manifests/bases/$1/kustomization.yaml"
|
||||
changed=true
|
||||
fi
|
||||
|
||||
if [[ "${CRD_VERSION}" != "${LATEST_VERSION}" ]]; then
|
||||
sed -i "s/\($1\/releases\/download\/\)v.*\(\/.*\)/\1${LATEST_VERSION}\2/g" "manifests/crds/kustomization.yaml"
|
||||
changed=true
|
||||
fi
|
||||
|
||||
if [[ "${MOD_VERSION}" != "${LATEST_VERSION}" ]]; then
|
||||
go mod edit -require="github.com/fluxcd/$1/api@${LATEST_VERSION}"
|
||||
rm go.sum
|
||||
go mod tidy
|
||||
changed=true
|
||||
fi
|
||||
|
||||
if [[ "$changed" == true ]]; then
|
||||
PR_BODY="$PR_BODY- $1 to ${LATEST_VERSION}%0A https://github.com/fluxcd/$1/blob/${LATEST_VERSION}/CHANGELOG.md%0A"
|
||||
fi
|
||||
}
|
||||
|
||||
{
|
||||
# bump controller versions
|
||||
bump_version helm-controller
|
||||
bump_version kustomize-controller
|
||||
bump_version source-controller
|
||||
bump_version notification-controller
|
||||
bump_version image-reflector-controller
|
||||
bump_version image-automation-controller
|
||||
|
||||
# diff change
|
||||
git diff
|
||||
|
||||
# export PR_BODY for PR and commit
|
||||
echo "::set-output name=pr_body::$PR_BODY"
|
||||
}
|
||||
|
||||
- name: Create Pull Request
|
||||
id: cpr
|
||||
uses: peter-evans/create-pull-request@v3
|
||||
with:
|
||||
token: ${{ secrets.BOT_GITHUB_TOKEN }}
|
||||
commit-message: |
|
||||
Update toolkit components
|
||||
|
||||
${{ steps.update.outputs.pr_body }}
|
||||
committer: GitHub <noreply@github.com>
|
||||
author: fluxcdbot <fluxcdbot@users.noreply.github.com>
|
||||
signoff: true
|
||||
branch: update-components
|
||||
title: Update toolkit components
|
||||
body: |
|
||||
${{ steps.update.outputs.pr_body }}
|
||||
labels: |
|
||||
area/build
|
||||
reviewers: ${{ secrets.ASSIGNEES }}
|
||||
|
||||
- name: Check output
|
||||
run: |
|
||||
echo "Pull Request Number - ${{ steps.cpr.outputs.pull-request-number }}"
|
||||
echo "Pull Request URL - ${{ steps.cpr.outputs.pull-request-url }}"
|
||||
78
.github/workflows/update.yml
vendored
78
.github/workflows/update.yml
vendored
@@ -1,78 +0,0 @@
|
||||
name: Update Components
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "0 * * * *"
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
update-components:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Update component versions
|
||||
id: update
|
||||
run: |
|
||||
PR_BODY=""
|
||||
|
||||
bump_version() {
|
||||
local RELEASE_VERSION=$(curl -s https://api.github.com/repos/fluxcd/$1/releases | jq -r 'sort_by(.published_at) | .[-1] | .tag_name')
|
||||
local CURRENT_VERSION=$(sed -n "s/.*$1\/archive\/\(.*\).zip.*/\1/p;n" manifests/bases/$1/kustomization.yaml)
|
||||
|
||||
if [[ "${RELEASE_VERSION}" != "${CURRENT_VERSION}" ]]; then
|
||||
# bump kustomize
|
||||
sed -i "s/\($1\/archive\/\)v.*\(.zip\/\/$1-\).*\(\/config.*\)/\1${RELEASE_VERSION}\2${RELEASE_VERSION/v}\3/g" "manifests/bases/$1/kustomization.yaml"
|
||||
|
||||
if [[ ! -z $(go list -m all | grep "github.com/fluxcd/$1/api" | awk '{print $2}') ]]; then
|
||||
# bump go mod
|
||||
go mod edit -require="github.com/fluxcd/$1/api@${RELEASE_VERSION}"
|
||||
fi
|
||||
|
||||
PR_BODY="$PR_BODY- $1 to ${RELEASE_VERSION}%0A"
|
||||
fi
|
||||
}
|
||||
|
||||
{
|
||||
# bump controller versions
|
||||
bump_version helm-controller
|
||||
bump_version kustomize-controller
|
||||
bump_version source-controller
|
||||
bump_version notification-controller
|
||||
bump_version image-reflector-controller
|
||||
bump_version image-automation-controller
|
||||
|
||||
# add missing and remove unused modules
|
||||
go mod tidy
|
||||
|
||||
# diff change
|
||||
git diff
|
||||
|
||||
# export PR_BODY for PR
|
||||
echo "::set-output name=pr_body::$PR_BODY"
|
||||
}
|
||||
|
||||
- name: Create Pull Request
|
||||
id: cpr
|
||||
uses: peter-evans/create-pull-request@v3
|
||||
with:
|
||||
token: ${{ secrets.BOT_GITHUB_TOKEN }}
|
||||
commit-message: Update toolkit components
|
||||
committer: GitHub <noreply@github.com>
|
||||
author: fluxcdbot <fluxcdbot@users.noreply.github.com>
|
||||
title: Update toolkit components
|
||||
body: |
|
||||
${{ steps.update.outputs.pr_body }}
|
||||
|
||||
Auto-generated by [create-pull-request][1]
|
||||
|
||||
[1]: https://github.com/peter-evans/create-pull-request
|
||||
branch: update-components
|
||||
reviewers: ${{ secrets.ASSIGNEES }}
|
||||
|
||||
- name: Check output
|
||||
run: |
|
||||
echo "Pull Request Number - ${{ steps.cpr.outputs.pull-request-number }}"
|
||||
9
.gitignore
vendored
9
.gitignore
vendored
@@ -11,7 +11,14 @@
|
||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||
*.out
|
||||
|
||||
# Release
|
||||
dist/
|
||||
|
||||
# Dependency directories (remove the comment below to include it)
|
||||
# vendor/
|
||||
bin/
|
||||
output/
|
||||
output/
|
||||
cmd/flux/manifests/
|
||||
|
||||
# Docs
|
||||
site/
|
||||
|
||||
@@ -20,6 +20,9 @@ builds:
|
||||
id: darwin
|
||||
goos:
|
||||
- darwin
|
||||
goarch:
|
||||
- amd64
|
||||
- arm64
|
||||
- <<: *build_defaults
|
||||
id: windows
|
||||
goos:
|
||||
@@ -44,7 +47,7 @@ brews:
|
||||
name: homebrew-tap
|
||||
token: "{{ .Env.HOMEBREW_TAP_GITHUB_TOKEN }}"
|
||||
folder: Formula
|
||||
homepage: "https://toolkit.fluxcd.io/"
|
||||
homepage: "https://fluxcd.io/"
|
||||
description: "Flux CLI"
|
||||
dependencies:
|
||||
- name: kubectl
|
||||
@@ -69,5 +72,67 @@ publishers:
|
||||
.github/aur/flux-go/publish.sh {{ .Version }}
|
||||
release:
|
||||
extra_files:
|
||||
- glob: ./output/crd-schemas.tar.gz
|
||||
- glob: ./output/manifests.tar.gz
|
||||
- glob: ./output/install.yaml
|
||||
dockers:
|
||||
- image_templates:
|
||||
- 'fluxcd/flux-cli:{{ .Tag }}-amd64'
|
||||
- 'ghcr.io/fluxcd/flux-cli:{{ .Tag }}-amd64'
|
||||
dockerfile: Dockerfile
|
||||
use_buildx: true
|
||||
goos: linux
|
||||
goarch: amd64
|
||||
build_flag_templates:
|
||||
- "--pull"
|
||||
- "--build-arg=ARCH=linux/amd64"
|
||||
- "--label=org.opencontainers.image.created={{ .Date }}"
|
||||
- "--label=org.opencontainers.image.name={{ .ProjectName }}"
|
||||
- "--label=org.opencontainers.image.revision={{ .FullCommit }}"
|
||||
- "--label=org.opencontainers.image.version={{ .Version }}"
|
||||
- "--label=org.opencontainers.image.source={{ .GitURL }}"
|
||||
- "--platform=linux/amd64"
|
||||
- image_templates:
|
||||
- 'fluxcd/flux-cli:{{ .Tag }}-arm64'
|
||||
- 'ghcr.io/fluxcd/flux-cli:{{ .Tag }}-arm64'
|
||||
dockerfile: Dockerfile
|
||||
use_buildx: true
|
||||
goos: linux
|
||||
goarch: arm64
|
||||
build_flag_templates:
|
||||
- "--pull"
|
||||
- "--build-arg=ARCH=linux/arm64"
|
||||
- "--label=org.opencontainers.image.created={{ .Date }}"
|
||||
- "--label=org.opencontainers.image.name={{ .ProjectName }}"
|
||||
- "--label=org.opencontainers.image.revision={{ .FullCommit }}"
|
||||
- "--label=org.opencontainers.image.version={{ .Version }}"
|
||||
- "--label=org.opencontainers.image.source={{ .GitURL }}"
|
||||
- "--platform=linux/arm64"
|
||||
- image_templates:
|
||||
- 'fluxcd/flux-cli:{{ .Tag }}-arm'
|
||||
- 'ghcr.io/fluxcd/flux-cli:{{ .Tag }}-arm'
|
||||
dockerfile: Dockerfile
|
||||
use_buildx: true
|
||||
goos: linux
|
||||
goarch: arm
|
||||
goarm: 7
|
||||
build_flag_templates:
|
||||
- "--pull"
|
||||
- "--build-arg=ARCH=linux/arm"
|
||||
- "--label=org.opencontainers.image.created={{ .Date }}"
|
||||
- "--label=org.opencontainers.image.name={{ .ProjectName }}"
|
||||
- "--label=org.opencontainers.image.revision={{ .FullCommit }}"
|
||||
- "--label=org.opencontainers.image.version={{ .Version }}"
|
||||
- "--label=org.opencontainers.image.source={{ .GitURL }}"
|
||||
- "--platform=linux/arm/v7"
|
||||
docker_manifests:
|
||||
- name_template: 'fluxcd/flux-cli:{{ .Tag }}'
|
||||
image_templates:
|
||||
- 'fluxcd/flux-cli:{{ .Tag }}-amd64'
|
||||
- 'fluxcd/flux-cli:{{ .Tag }}-arm64'
|
||||
- 'fluxcd/flux-cli:{{ .Tag }}-arm'
|
||||
- name_template: 'ghcr.io/fluxcd/flux-cli:{{ .Tag }}'
|
||||
image_templates:
|
||||
- 'ghcr.io/fluxcd/flux-cli:{{ .Tag }}-amd64'
|
||||
- 'ghcr.io/fluxcd/flux-cli:{{ .Tag }}-arm64'
|
||||
- 'ghcr.io/fluxcd/flux-cli:{{ .Tag }}-arm'
|
||||
|
||||
@@ -48,27 +48,45 @@ you might want to take a look at the [introductory talk and demo](https://www.yo
|
||||
|
||||
This project is composed of:
|
||||
|
||||
- [/f/flux2](https://github.com/fluxcd/flux2): The Flux CLI
|
||||
- [/f/source-manager](https://github.com/fluxcd/source-controller): Kubernetes operator for managing sources
|
||||
- [/f/kustomize-controller](https://github.com/fluxcd/kustomize-controller): Kubernetes operator for building GitOps pipelines with Kustomize
|
||||
- [/f/helm-controller](https://github.com/fluxcd/helm-controller): Kubernetes operator for building GitOps pipelines with Helm
|
||||
- [/f/notification-controller](https://github.com/fluxcd/notification-controller): Kubernetes operator for handling inbound and outbound events
|
||||
- [flux2](https://github.com/fluxcd/flux2): The Flux CLI
|
||||
- [source-manager](https://github.com/fluxcd/source-controller): Kubernetes operator for managing sources (Git and Helm repositories, S3-compatible Buckets)
|
||||
- [kustomize-controller](https://github.com/fluxcd/kustomize-controller): Kubernetes operator for building GitOps pipelines with Kustomize
|
||||
- [helm-controller](https://github.com/fluxcd/helm-controller): Kubernetes operator for building GitOps pipelines with Helm
|
||||
- [notification-controller](https://github.com/fluxcd/notification-controller): Kubernetes operator for handling inbound and outbound events
|
||||
- [image-reflector-controller](https://github.com/fluxcd/image-reflector-controller): Kubernetes operator for scanning container registries
|
||||
- [image-automation-controller](https://github.com/fluxcd/image-automation-controller): Kubernetes operator for patches container image tags in Git
|
||||
|
||||
### Understanding the code
|
||||
|
||||
To get started with developing controllers, you might want to review
|
||||
[our guide](https://toolkit.fluxcd.io/dev-guides/source-watcher/) which
|
||||
[our guide](https://fluxcd.io/docs/gitops-toolkit/source-watcher/) which
|
||||
walks you through writing a short and concise controller that watches out
|
||||
for source changes.
|
||||
|
||||
### How to run the test suite
|
||||
|
||||
Prerequisites:
|
||||
|
||||
* go >= 1.16
|
||||
* kubectl >= 1.18
|
||||
* kustomize >= 3.1
|
||||
|
||||
You can run the unit tests by simply doing
|
||||
|
||||
```bash
|
||||
make test
|
||||
```
|
||||
|
||||
The e2e test suite uses [kind](https://kind.sigs.k8s.io/) for running kubernetes cluster inside docker containers. You can run the e2e tests by simply doing
|
||||
|
||||
```bash
|
||||
make setup-kind
|
||||
make e2e
|
||||
|
||||
# When done
|
||||
make cleanup-kind
|
||||
```
|
||||
|
||||
## Acceptance policy
|
||||
|
||||
These things will make a PR more likely to be accepted:
|
||||
|
||||
23
Dockerfile
Normal file
23
Dockerfile
Normal file
@@ -0,0 +1,23 @@
|
||||
FROM alpine:3.13 as builder
|
||||
|
||||
RUN apk add --no-cache ca-certificates curl
|
||||
|
||||
ARG ARCH=linux/amd64
|
||||
ARG KUBECTL_VER=1.20.4
|
||||
|
||||
RUN curl -sL https://storage.googleapis.com/kubernetes-release/release/v${KUBECTL_VER}/bin/${ARCH}/kubectl \
|
||||
-o /usr/local/bin/kubectl && chmod +x /usr/local/bin/kubectl && \
|
||||
kubectl version --client=true
|
||||
|
||||
FROM alpine:3.13 as flux-cli
|
||||
|
||||
# Create minimal nsswitch.conf file to prioritize the usage of /etc/hosts over DNS queries.
|
||||
# https://github.com/gliderlabs/docker-alpine/issues/367#issuecomment-354316460
|
||||
RUN [ ! -e /etc/nsswitch.conf ] && echo 'hosts: files dns' > /etc/nsswitch.conf
|
||||
|
||||
RUN apk add --no-cache ca-certificates
|
||||
|
||||
COPY --from=builder /usr/local/bin/kubectl /usr/local/bin/
|
||||
COPY --chmod=755 flux /usr/local/bin/
|
||||
|
||||
ENTRYPOINT [ "flux" ]
|
||||
60
Makefile
60
Makefile
@@ -1,4 +1,17 @@
|
||||
VERSION?=$(shell grep 'VERSION' cmd/flux/main.go | awk '{ print $$4 }' | tr -d '"')
|
||||
EMBEDDED_MANIFESTS_TARGET=cmd/flux/manifests
|
||||
TEST_KUBECONFIG?=/tmp/flux-e2e-test-kubeconfig
|
||||
ENVTEST_BIN_VERSION?=latest
|
||||
KUBEBUILDER_ASSETS?="$(shell $(SETUP_ENVTEST) use -i $(ENVTEST_BIN_VERSION) -p path)"
|
||||
|
||||
# Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set)
|
||||
ifeq (,$(shell go env GOBIN))
|
||||
GOBIN=$(shell go env GOPATH)/bin
|
||||
else
|
||||
GOBIN=$(shell go env GOBIN)
|
||||
endif
|
||||
|
||||
rwildcard=$(foreach d,$(wildcard $(addsuffix *,$(1))),$(call rwildcard,$(d)/,$(2)) $(filter $(subst *,%,$(2)),$(d)))
|
||||
|
||||
all: test build
|
||||
|
||||
@@ -11,19 +24,50 @@ fmt:
|
||||
vet:
|
||||
go vet ./...
|
||||
|
||||
test: tidy fmt vet docs
|
||||
go test ./... -coverprofile cover.out
|
||||
setup-kind:
|
||||
kind create cluster --name=flux-e2e-test --kubeconfig=$(TEST_KUBECONFIG) --config=.github/kind/config.yaml
|
||||
kubectl --kubeconfig=$(TEST_KUBECONFIG) apply -f https://docs.projectcalico.org/v3.16/manifests/calico.yaml
|
||||
kubectl --kubeconfig=$(TEST_KUBECONFIG) -n kube-system set env daemonset/calico-node FELIX_IGNORELOOSERPF=true
|
||||
|
||||
build:
|
||||
cleanup-kind:
|
||||
kind delete cluster --name=flux-e2e-test
|
||||
rm $(TEST_KUBECONFIG)
|
||||
|
||||
test: $(EMBEDDED_MANIFESTS_TARGET) tidy fmt vet setup-envtest
|
||||
KUBEBUILDER_ASSETS=$(KUBEBUILDER_ASSETS) go test ./... -coverprofile cover.out --tags=unit
|
||||
|
||||
e2e: $(EMBEDDED_MANIFESTS_TARGET) tidy fmt vet
|
||||
TEST_KUBECONFIG=$(TEST_KUBECONFIG) go test ./cmd/flux/... -coverprofile e2e.cover.out --tags=e2e -v -failfast
|
||||
|
||||
test-with-kind: setup-envtest
|
||||
make setup-kind
|
||||
make e2e
|
||||
make cleanup-kind
|
||||
|
||||
$(EMBEDDED_MANIFESTS_TARGET): $(call rwildcard,manifests/,*.yaml *.json)
|
||||
./manifests/scripts/bundle.sh
|
||||
|
||||
build: $(EMBEDDED_MANIFESTS_TARGET)
|
||||
CGO_ENABLED=0 go build -o ./bin/flux ./cmd/flux
|
||||
|
||||
install:
|
||||
go install cmd/flux
|
||||
|
||||
.PHONY: docs
|
||||
docs:
|
||||
rm docs/cmd/*
|
||||
mkdir -p ./docs/cmd && go run ./cmd/flux/ docgen
|
||||
|
||||
install-dev:
|
||||
CGO_ENABLED=0 go build -o /usr/local/bin ./cmd/flux
|
||||
|
||||
# Find or download setup-envtest
|
||||
setup-envtest:
|
||||
ifeq (, $(shell which setup-envtest))
|
||||
@{ \
|
||||
set -e ;\
|
||||
SETUP_ENVTEST_TMP_DIR=$$(mktemp -d) ;\
|
||||
cd $$SETUP_ENVTEST_TMP_DIR ;\
|
||||
go mod init tmp ;\
|
||||
go get sigs.k8s.io/controller-runtime/tools/setup-envtest@latest ;\
|
||||
rm -rf $$SETUP_ENVTEST_TMP_DIR ;\
|
||||
}
|
||||
SETUP_ENVTEST=$(GOBIN)/setup-envtest
|
||||
else
|
||||
SETUP_ENVTEST=$(shell which setup-envtest)
|
||||
endif
|
||||
|
||||
85
README.md
85
README.md
@@ -1,5 +1,6 @@
|
||||
# Flux version 2
|
||||
|
||||
[](https://bestpractices.coreinfrastructure.org/projects/4782)
|
||||
[](https://github.com/fluxcd/flux2/actions)
|
||||
[](https://goreportcard.com/report/github.com/fluxcd/flux2)
|
||||
[](https://github.com/fluxcd/flux2/blob/main/LICENSE)
|
||||
@@ -21,16 +22,22 @@ Delivery on top of Kubernetes.
|
||||
|
||||
## Flux installation
|
||||
|
||||
With Homebrew:
|
||||
With [Homebrew](https://brew.sh) for macOS and Linux:
|
||||
|
||||
```sh
|
||||
brew install fluxcd/tap/flux
|
||||
```
|
||||
|
||||
With Bash:
|
||||
With [GoFish](https://gofi.sh) for Windows, macOS and Linux:
|
||||
|
||||
```sh
|
||||
curl -s https://toolkit.fluxcd.io/install.sh | sudo bash
|
||||
gofish install flux
|
||||
```
|
||||
|
||||
With Bash for macOS and Linux:
|
||||
|
||||
```sh
|
||||
curl -s https://fluxcd.io/install.sh | sudo bash
|
||||
|
||||
# enable completions in ~/.bash_profile
|
||||
. <(flux completion bash)
|
||||
@@ -45,8 +52,13 @@ Arch Linux (AUR) packages:
|
||||
- [flux-scm](https://aur.archlinux.org/packages/flux-scm): build the latest
|
||||
(unstable) version from source code from our git `main` branch
|
||||
|
||||
Binaries for macOS, Windows and Linux AMD64/ARM are available to download on the
|
||||
[release page](https://github.com/fluxcd/flux2/releases).
|
||||
Binaries for macOS AMD64/ARM64, Linux AMD64/ARM/ARM64 and Windows are available to
|
||||
download on the [release page](https://github.com/fluxcd/flux2/releases).
|
||||
|
||||
A multi-arch container image with `kubectl` and `flux` is available on Docker Hub and GitHub:
|
||||
|
||||
* `docker.io/fluxcd/flux-cli:<version>`
|
||||
* `ghcr.io/fluxcd/flux-cli:<version>`
|
||||
|
||||
Verify that your cluster satisfies the prerequisites with:
|
||||
|
||||
@@ -57,16 +69,15 @@ flux check --pre
|
||||
## Get started
|
||||
|
||||
To get started with Flux, start [browsing the
|
||||
documentation](https://toolkit.fluxcd.io) or get started with one of
|
||||
documentation](https://fluxcd.io/docs/) or get started with one of
|
||||
the following guides:
|
||||
|
||||
- [Get started with Flux (deep dive)](https://toolkit.fluxcd.io/get-started/)
|
||||
- [Installation](https://toolkit.fluxcd.io/guides/installation/)
|
||||
- [Manage Helm Releases](https://toolkit.fluxcd.io/guides/helmreleases/)
|
||||
- [Setup Notifications](https://toolkit.fluxcd.io/guides/notifications/)
|
||||
- [Setup Webhook Receivers](https://toolkit.fluxcd.io/guides/webhook-receivers/)
|
||||
- [Get started with Flux](https://fluxcd.io/docs/get-started/)
|
||||
- [Manage Helm Releases](https://fluxcd.io/docs/guides/helmreleases/)
|
||||
- [Automate image updates to Git](https://fluxcd.io/docs/guides/image-update/)
|
||||
- [Manage Kubernetes secrets with Mozilla SOPS](https://fluxcd.io/docs/guides/mozilla-sops/)
|
||||
|
||||
If you should need help, please refer to our **[Support page](https://fluxcd.io/support/)**.
|
||||
If you need help, please refer to our **[Support page](https://fluxcd.io/support/)**.
|
||||
|
||||
## GitOps Toolkit
|
||||
|
||||
@@ -75,38 +86,45 @@ runtime for Flux v2. The APIs comprise Kubernetes custom resources,
|
||||
which can be created and updated by a cluster user, or by other
|
||||
automation tooling.
|
||||
|
||||

|
||||

|
||||
|
||||
You can use the toolkit to extend Flux, or to build your own systems
|
||||
for continuous delivery -- see [the developer
|
||||
guides](https://toolkit.fluxcd.io/dev-guides/source-watcher/).
|
||||
guides](https://fluxcd.io/docs/gitops-toolkit/source-watcher/).
|
||||
|
||||
### Components
|
||||
|
||||
- [Source Controller](https://toolkit.fluxcd.io/components/source/controller/)
|
||||
- [GitRepository CRD](https://toolkit.fluxcd.io/components/source/gitrepositories/)
|
||||
- [HelmRepository CRD](https://toolkit.fluxcd.io/components/source/helmrepositories/)
|
||||
- [HelmChart CRD](https://toolkit.fluxcd.io/components/source/helmcharts/)
|
||||
- [Bucket CRD](https://toolkit.fluxcd.io/components/source/buckets/)
|
||||
- [Kustomize Controller](https://toolkit.fluxcd.io/components/kustomize/controller/)
|
||||
- [Kustomization CRD](https://toolkit.fluxcd.io/components/kustomize/kustomization/)
|
||||
- [Helm Controller](https://toolkit.fluxcd.io/components/helm/controller/)
|
||||
- [HelmRelease CRD](https://toolkit.fluxcd.io/components/helm/helmreleases/)
|
||||
- [Notification Controller](https://toolkit.fluxcd.io/components/notification/controller/)
|
||||
- [Provider CRD](https://toolkit.fluxcd.io/components/notification/provider/)
|
||||
- [Alert CRD](https://toolkit.fluxcd.io/components/notification/alert/)
|
||||
- [Receiver CRD](https://toolkit.fluxcd.io/components/notification/receiver/)
|
||||
|
||||
- [Source Controller](https://fluxcd.io/docs/components/source/)
|
||||
- [GitRepository CRD](https://fluxcd.io/docs/components/source/gitrepositories/)
|
||||
- [HelmRepository CRD](https://fluxcd.io/docs/components/source/helmrepositories/)
|
||||
- [HelmChart CRD](https://fluxcd.io/docs/components/source/helmcharts/)
|
||||
- [Bucket CRD](https://fluxcd.io/docs/components/source/buckets/)
|
||||
- [Kustomize Controller](https://fluxcd.io/docs/components/kustomize/)
|
||||
- [Kustomization CRD](https://fluxcd.io/docs/components/kustomize/kustomization/)
|
||||
- [Helm Controller](https://fluxcd.io/docs/components/helm/)
|
||||
- [HelmRelease CRD](https://fluxcd.io/docs/components/helm/helmreleases/)
|
||||
- [Notification Controller](https://fluxcd.io/docs/components/notification/)
|
||||
- [Provider CRD](https://fluxcd.io/docs/components/notification/provider/)
|
||||
- [Alert CRD](https://fluxcd.io/docs/components/notification/alert/)
|
||||
- [Receiver CRD](https://fluxcd.io/docs/components/notification/receiver/)
|
||||
- [Image Automation Controllers](https://fluxcd.io/docs/components/image/)
|
||||
- [ImageRepository CRD](https://fluxcd.io/docs/components/image/imagerepositories/)
|
||||
- [ImagePolicy CRD](https://fluxcd.io/docs/components/image/imagepolicies/)
|
||||
- [ImageUpdateAutomation CRD](https://fluxcd.io/docs/components/image/imageupdateautomations/)
|
||||
|
||||
## Community
|
||||
|
||||
Need help or want to contribute? Please see the links below. The Flux project is always looking for new contributors and there are a multitude of ways to get involved.
|
||||
Need help or want to contribute? Please see the links below. The Flux project is always looking for
|
||||
new contributors and there are a multitude of ways to get involved.
|
||||
|
||||
- Getting Started?
|
||||
- Look at our [Get Started guide](https://toolkit.fluxcd.io/get-started/) and give us feedback
|
||||
- Look at our [Get Started guide](https://fluxcd.io/docs/get-started/) and give us feedback
|
||||
- Need help?
|
||||
- First: Ask questions on our [GH Discussions page](https://github.com/fluxcd/flux2/discussions)
|
||||
- Second: Talk to us in the #flux channel on [CNCF Slack](https://slack.cncf.io/)
|
||||
- Please follow our [Support Guidelines](https://fluxcd.io/support/) (in short: be nice, be respectful of volunteers' time, understand that maintainers and contributors cannot respond to all DMs, and keep discussions in the public #flux channel as much as possible).
|
||||
- Please follow our [Support Guidelines](https://fluxcd.io/support/)
|
||||
(in short: be nice, be respectful of volunteers' time, understand that maintainers and
|
||||
contributors cannot respond to all DMs, and keep discussions in the public #flux channel as much as possible).
|
||||
- Have feature proposals or want to contribute?
|
||||
- Propose features on our [GH Discussions page](https://github.com/fluxcd/flux2/discussions)
|
||||
- Join our upcoming dev meetings ([meeting access and agenda](https://docs.google.com/document/d/1l_M0om0qUEN_NNiGgpqJ2tvsF2iioHkaARDeh6b70B0/view))
|
||||
@@ -115,6 +133,9 @@ Need help or want to contribute? Please see the links below. The Flux project is
|
||||
|
||||
### Events
|
||||
|
||||
Check out our **[events calendar](https://fluxcd.io/community/#talks)**, both with upcoming talks you can attend or past events videos you can watch.
|
||||
Check out our **[events calendar](https://fluxcd.io/#calendar)**,
|
||||
both with upcoming talks, events and meetings you can attend.
|
||||
Or view the **[resources section](https://fluxcd.io/resources)**
|
||||
with past events videos you can watch.
|
||||
|
||||
We look forward to seeing you with us!
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
FROM stefanprodan/alpine-base:latest
|
||||
|
||||
COPY entrypoint.sh /entrypoint.sh
|
||||
RUN chmod +x /entrypoint.sh
|
||||
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
@@ -10,15 +10,30 @@ Usage:
|
||||
run: flux -v
|
||||
```
|
||||
|
||||
This action places the `flux` binary inside your repository root under `bin/flux`.
|
||||
You should add `bin/flux` to your `.gitignore` file, as in the following example:
|
||||
The latest stable version of the `flux` binary is downloaded from
|
||||
GitHub [releases](https://github.com/fluxcd/flux2/releases)
|
||||
and placed at `/usr/local/bin/flux`.
|
||||
|
||||
```gitignore
|
||||
# ignore flux binary
|
||||
bin/flux
|
||||
Note that this action can only be used on GitHub **Linux** runners.
|
||||
You can change the arch (defaults to `amd64`) with:
|
||||
|
||||
```yaml
|
||||
steps:
|
||||
- name: Setup Flux CLI
|
||||
uses: fluxcd/flux2/action@main
|
||||
with:
|
||||
arch: arm64 # can be amd64, arm64 or arm
|
||||
```
|
||||
|
||||
Note that this action can only be used on GitHub **Linux AMD64** runners.
|
||||
You can download a specific version with:
|
||||
|
||||
```yaml
|
||||
steps:
|
||||
- name: Setup Flux CLI
|
||||
uses: fluxcd/flux2/action@main
|
||||
with:
|
||||
version: 0.8.0
|
||||
```
|
||||
|
||||
### Automate Flux updates
|
||||
|
||||
|
||||
@@ -1,15 +1,43 @@
|
||||
name: 'kustomize'
|
||||
description: 'A GitHub Action for running Flux commands'
|
||||
author: 'Flux project'
|
||||
name: Setup Flux CLI
|
||||
description: A GitHub Action for running Flux commands
|
||||
author: Stefan Prodan
|
||||
branding:
|
||||
icon: 'command'
|
||||
color: 'blue'
|
||||
color: blue
|
||||
icon: command
|
||||
inputs:
|
||||
version:
|
||||
description: 'strict semver'
|
||||
description: "Flux version e.g. 0.8.0 (defaults to latest stable release)"
|
||||
required: false
|
||||
arch:
|
||||
description: "arch can be amd64, arm64 or arm"
|
||||
required: true
|
||||
default: "amd64"
|
||||
runs:
|
||||
using: 'docker'
|
||||
image: 'Dockerfile'
|
||||
args:
|
||||
- ${{ inputs.version }}
|
||||
using: composite
|
||||
steps:
|
||||
- name: "Download flux binary to tmp"
|
||||
shell: bash
|
||||
run: |
|
||||
ARCH=${{ inputs.arch }}
|
||||
VERSION=${{ inputs.version }}
|
||||
|
||||
if [ -z $VERSION ]; then
|
||||
VERSION=$(curl https://api.github.com/repos/fluxcd/flux2/releases/latest -sL | grep tag_name | sed -E 's/.*"([^"]+)".*/\1/' | cut -c 2-)
|
||||
fi
|
||||
|
||||
BIN_URL="https://github.com/fluxcd/flux2/releases/download/v${VERSION}/flux_${VERSION}_linux_${ARCH}.tar.gz"
|
||||
curl -sL ${BIN_URL} -o /tmp/flux.tar.gz
|
||||
mkdir -p /tmp/flux
|
||||
tar -C /tmp/flux/ -zxvf /tmp/flux.tar.gz
|
||||
- name: "Add flux binary to /usr/local/bin"
|
||||
shell: bash
|
||||
run: |
|
||||
sudo cp /tmp/flux/flux /usr/local/bin
|
||||
- name: "Cleanup tmp"
|
||||
shell: bash
|
||||
run: |
|
||||
rm -rf /tmp/flux/ /tmp/flux.tar.gz
|
||||
- name: "Verify correct installation of binary"
|
||||
shell: bash
|
||||
run: |
|
||||
flux -v
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Copyright 2020 The Flux authors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
set -e
|
||||
|
||||
VERSION=$1
|
||||
|
||||
if [ -z $VERSION ]; then
|
||||
# Find latest release if no version is specified
|
||||
VERSION=$(curl https://api.github.com/repos/fluxcd/flux2/releases/latest -sL | grep tag_name | sed -E 's/.*"([^"]+)".*/\1/' | cut -c 2-)
|
||||
fi
|
||||
|
||||
# Download linux binary
|
||||
BIN_URL="https://github.com/fluxcd/flux2/releases/download/v${VERSION}/flux_${VERSION}_linux_amd64.tar.gz"
|
||||
curl -sL $BIN_URL | tar xz
|
||||
|
||||
# Copy binary to GitHub runner
|
||||
mkdir -p $GITHUB_WORKSPACE/bin
|
||||
mv ./flux $GITHUB_WORKSPACE/bin
|
||||
chmod +x $GITHUB_WORKSPACE/bin/flux
|
||||
|
||||
# Print version
|
||||
$GITHUB_WORKSPACE/bin/flux -v
|
||||
|
||||
# Add binary to GitHub runner path
|
||||
echo "$GITHUB_WORKSPACE/bin" >> $GITHUB_PATH
|
||||
echo "$RUNNER_WORKSPACE/$(basename $GITHUB_REPOSITORY)/bin" >> $GITHUB_PATH
|
||||
56
cmd/flux/alert.go
Normal file
56
cmd/flux/alert.go
Normal file
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
Copyright 2021 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
// notificationv1.Alert
|
||||
|
||||
var alertType = apiType{
|
||||
kind: notificationv1.AlertKind,
|
||||
humanKind: "alert",
|
||||
}
|
||||
|
||||
type alertAdapter struct {
|
||||
*notificationv1.Alert
|
||||
}
|
||||
|
||||
func (a alertAdapter) asClientObject() client.Object {
|
||||
return a.Alert
|
||||
}
|
||||
|
||||
func (a alertAdapter) deepCopyClientObject() client.Object {
|
||||
return a.Alert.DeepCopy()
|
||||
}
|
||||
|
||||
// notificationv1.Alert
|
||||
|
||||
type alertListAdapter struct {
|
||||
*notificationv1.AlertList
|
||||
}
|
||||
|
||||
func (a alertListAdapter) asClientList() client.ObjectList {
|
||||
return a.AlertList
|
||||
}
|
||||
|
||||
func (a alertListAdapter) len() int {
|
||||
return len(a.AlertList.Items)
|
||||
}
|
||||
56
cmd/flux/alert_provider.go
Normal file
56
cmd/flux/alert_provider.go
Normal file
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
Copyright 2021 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
// notificationv1.Provider
|
||||
|
||||
var alertProviderType = apiType{
|
||||
kind: notificationv1.ProviderKind,
|
||||
humanKind: "alert provider",
|
||||
}
|
||||
|
||||
type alertProviderAdapter struct {
|
||||
*notificationv1.Provider
|
||||
}
|
||||
|
||||
func (a alertProviderAdapter) asClientObject() client.Object {
|
||||
return a.Provider
|
||||
}
|
||||
|
||||
func (a alertProviderAdapter) deepCopyClientObject() client.Object {
|
||||
return a.Provider.DeepCopy()
|
||||
}
|
||||
|
||||
// notificationv1.Provider
|
||||
|
||||
type alertProviderListAdapter struct {
|
||||
*notificationv1.ProviderList
|
||||
}
|
||||
|
||||
func (a alertProviderListAdapter) asClientList() client.ObjectList {
|
||||
return a.ProviderList
|
||||
}
|
||||
|
||||
func (a alertProviderListAdapter) len() int {
|
||||
return len(a.ProviderList.Items)
|
||||
}
|
||||
@@ -17,26 +17,15 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/elliptic"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"time"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/install"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/sync"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/sourcesecret"
|
||||
)
|
||||
|
||||
var bootstrapCmd = &cobra.Command{
|
||||
@@ -46,20 +35,39 @@ var bootstrapCmd = &cobra.Command{
|
||||
}
|
||||
|
||||
type bootstrapFlags struct {
|
||||
version string
|
||||
version string
|
||||
arch flags.Arch
|
||||
logLevel flags.LogLevel
|
||||
|
||||
branch string
|
||||
recurseSubmodules bool
|
||||
manifestsPath string
|
||||
|
||||
defaultComponents []string
|
||||
extraComponents []string
|
||||
registry string
|
||||
imagePullSecret string
|
||||
branch string
|
||||
requiredComponents []string
|
||||
|
||||
registry string
|
||||
imagePullSecret string
|
||||
|
||||
secretName string
|
||||
tokenAuth bool
|
||||
keyAlgorithm flags.PublicKeyAlgorithm
|
||||
keyRSABits flags.RSAKeyBits
|
||||
keyECDSACurve flags.ECDSACurve
|
||||
sshHostname string
|
||||
caFile string
|
||||
privateKeyFile string
|
||||
|
||||
watchAllNamespaces bool
|
||||
networkPolicy bool
|
||||
manifestsPath string
|
||||
arch flags.Arch
|
||||
logLevel flags.LogLevel
|
||||
requiredComponents []string
|
||||
tokenAuth bool
|
||||
clusterDomain string
|
||||
tolerationKeys []string
|
||||
|
||||
authorName string
|
||||
authorEmail string
|
||||
|
||||
commitMessageAppendix string
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -69,19 +77,25 @@ const (
|
||||
var bootstrapArgs = NewBootstrapFlags()
|
||||
|
||||
func init() {
|
||||
bootstrapCmd.PersistentFlags().StringVarP(&bootstrapArgs.version, "version", "v", rootArgs.defaults.Version,
|
||||
"toolkit version")
|
||||
bootstrapCmd.PersistentFlags().StringVarP(&bootstrapArgs.version, "version", "v", "",
|
||||
"toolkit version, when specified the manifests are downloaded from https://github.com/fluxcd/flux2/releases")
|
||||
|
||||
bootstrapCmd.PersistentFlags().StringSliceVar(&bootstrapArgs.defaultComponents, "components", rootArgs.defaults.Components,
|
||||
"list of components, accepts comma-separated values")
|
||||
bootstrapCmd.PersistentFlags().StringSliceVar(&bootstrapArgs.extraComponents, "components-extra", nil,
|
||||
"list of components in addition to those supplied or defaulted, accepts comma-separated values")
|
||||
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapArgs.registry, "registry", "ghcr.io/fluxcd",
|
||||
"container registry where the toolkit images are published")
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapArgs.imagePullSecret, "image-pull-secret", "",
|
||||
"Kubernetes secret name used for pulling the toolkit images from a private registry")
|
||||
bootstrapCmd.PersistentFlags().Var(&bootstrapArgs.arch, "arch", bootstrapArgs.arch.Description())
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapArgs.branch, "branch", bootstrapDefaultBranch,
|
||||
"default branch (for GitHub this must match the default branch setting for the organization)")
|
||||
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapArgs.branch, "branch", bootstrapDefaultBranch, "Git branch")
|
||||
bootstrapCmd.PersistentFlags().BoolVar(&bootstrapArgs.recurseSubmodules, "recurse-submodules", false,
|
||||
"when enabled, configures the GitRepository source to initialize and include Git submodules in the artifact it produces")
|
||||
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapArgs.manifestsPath, "manifests", "", "path to the manifest directory")
|
||||
|
||||
bootstrapCmd.PersistentFlags().BoolVar(&bootstrapArgs.watchAllNamespaces, "watch-all-namespaces", true,
|
||||
"watch for custom resources in all namespaces, if set to false it will only watch the namespace where the toolkit is installed")
|
||||
bootstrapCmd.PersistentFlags().BoolVar(&bootstrapArgs.networkPolicy, "network-policy", true,
|
||||
@@ -89,10 +103,27 @@ func init() {
|
||||
bootstrapCmd.PersistentFlags().BoolVar(&bootstrapArgs.tokenAuth, "token-auth", false,
|
||||
"when enabled, the personal access token will be used instead of SSH deploy key")
|
||||
bootstrapCmd.PersistentFlags().Var(&bootstrapArgs.logLevel, "log-level", bootstrapArgs.logLevel.Description())
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapArgs.manifestsPath, "manifests", "", "path to the manifest directory")
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapArgs.clusterDomain, "cluster-domain", rootArgs.defaults.ClusterDomain, "internal cluster domain")
|
||||
bootstrapCmd.PersistentFlags().MarkHidden("manifests")
|
||||
bootstrapCmd.PersistentFlags().StringSliceVar(&bootstrapArgs.tolerationKeys, "toleration-keys", nil,
|
||||
"list of toleration keys used to schedule the components pods onto nodes with matching taints")
|
||||
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapArgs.secretName, "secret-name", rootArgs.defaults.Namespace, "name of the secret the sync credentials can be found in or stored to")
|
||||
bootstrapCmd.PersistentFlags().Var(&bootstrapArgs.keyAlgorithm, "ssh-key-algorithm", bootstrapArgs.keyAlgorithm.Description())
|
||||
bootstrapCmd.PersistentFlags().Var(&bootstrapArgs.keyRSABits, "ssh-rsa-bits", bootstrapArgs.keyRSABits.Description())
|
||||
bootstrapCmd.PersistentFlags().Var(&bootstrapArgs.keyECDSACurve, "ssh-ecdsa-curve", bootstrapArgs.keyECDSACurve.Description())
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapArgs.sshHostname, "ssh-hostname", "", "SSH hostname, to be used when the SSH host differs from the HTTPS one")
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapArgs.caFile, "ca-file", "", "path to TLS CA file used for validating self-signed certificates")
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapArgs.privateKeyFile, "private-key-file", "", "path to a private key file used for authenticating to the Git SSH server")
|
||||
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapArgs.authorName, "author-name", "Flux", "author name for Git commits")
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapArgs.authorEmail, "author-email", "", "author email for Git commits")
|
||||
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapArgs.commitMessageAppendix, "commit-message-appendix", "", "string to add to the commit messages, e.g. '[ci skip]'")
|
||||
|
||||
bootstrapCmd.PersistentFlags().Var(&bootstrapArgs.arch, "arch", bootstrapArgs.arch.Description())
|
||||
bootstrapCmd.PersistentFlags().MarkDeprecated("arch", "multi-arch container image is now available for AMD64, ARMv7 and ARM64")
|
||||
bootstrapCmd.PersistentFlags().MarkHidden("manifests")
|
||||
|
||||
rootCmd.AddCommand(bootstrapCmd)
|
||||
}
|
||||
|
||||
@@ -100,6 +131,9 @@ func NewBootstrapFlags() bootstrapFlags {
|
||||
return bootstrapFlags{
|
||||
logLevel: flags.LogLevel(rootArgs.defaults.LogLevel),
|
||||
requiredComponents: []string{"source-controller", "kustomize-controller"},
|
||||
keyAlgorithm: flags.PublicKeyAlgorithm(sourcesecret.RSAPrivateKeyAlgorithm),
|
||||
keyRSABits: 2048,
|
||||
keyECDSACurve: flags.ECDSACurve{Curve: elliptic.P384()},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,6 +141,20 @@ func bootstrapComponents() []string {
|
||||
return append(bootstrapArgs.defaultComponents, bootstrapArgs.extraComponents...)
|
||||
}
|
||||
|
||||
func buildEmbeddedManifestBase() (string, error) {
|
||||
if !isEmbeddedVersion(bootstrapArgs.version) {
|
||||
return "", nil
|
||||
}
|
||||
tmpBaseDir, err := os.MkdirTemp("", "flux-manifests-")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := writeEmbeddedManifests(tmpBaseDir); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return tmpBaseDir, nil
|
||||
}
|
||||
|
||||
func bootstrapValidate() error {
|
||||
components := bootstrapComponents()
|
||||
for _, component := range bootstrapArgs.requiredComponents {
|
||||
@@ -122,173 +170,10 @@ func bootstrapValidate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateInstallManifests(targetPath, namespace, tmpDir string, localManifests string) (string, error) {
|
||||
opts := install.Options{
|
||||
BaseURL: localManifests,
|
||||
Version: bootstrapArgs.version,
|
||||
Namespace: rootArgs.namespace,
|
||||
Components: bootstrapComponents(),
|
||||
Registry: bootstrapArgs.registry,
|
||||
ImagePullSecret: bootstrapArgs.imagePullSecret,
|
||||
WatchAllNamespaces: bootstrapArgs.watchAllNamespaces,
|
||||
NetworkPolicy: bootstrapArgs.networkPolicy,
|
||||
LogLevel: bootstrapArgs.logLevel.String(),
|
||||
NotificationController: rootArgs.defaults.NotificationController,
|
||||
ManifestFile: rootArgs.defaults.ManifestFile,
|
||||
Timeout: rootArgs.timeout,
|
||||
TargetPath: targetPath,
|
||||
ClusterDomain: bootstrapArgs.clusterDomain,
|
||||
func mapTeamSlice(s []string, defaultPermission string) map[string]string {
|
||||
m := make(map[string]string, len(s))
|
||||
for _, v := range s {
|
||||
m[v] = defaultPermission
|
||||
}
|
||||
|
||||
if localManifests == "" {
|
||||
opts.BaseURL = rootArgs.defaults.BaseURL
|
||||
}
|
||||
|
||||
output, err := install.Generate(opts)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("generating install manifests failed: %w", err)
|
||||
}
|
||||
|
||||
filePath, err := output.WriteFile(tmpDir)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("generating install manifests failed: %w", err)
|
||||
}
|
||||
return filePath, nil
|
||||
}
|
||||
|
||||
func applyInstallManifests(ctx context.Context, manifestPath string, components []string) error {
|
||||
kubectlArgs := []string{"apply", "-f", manifestPath}
|
||||
if _, err := utils.ExecKubectlCommand(ctx, utils.ModeOS, rootArgs.kubeconfig, rootArgs.kubecontext, kubectlArgs...); err != nil {
|
||||
return fmt.Errorf("install failed")
|
||||
}
|
||||
|
||||
for _, deployment := range components {
|
||||
kubectlArgs = []string{"-n", rootArgs.namespace, "rollout", "status", "deployment", deployment, "--timeout", rootArgs.timeout.String()}
|
||||
if _, err := utils.ExecKubectlCommand(ctx, utils.ModeOS, rootArgs.kubeconfig, rootArgs.kubecontext, kubectlArgs...); err != nil {
|
||||
return fmt.Errorf("install failed")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateSyncManifests(url, branch, name, namespace, targetPath, tmpDir string, interval time.Duration) (string, error) {
|
||||
opts := sync.Options{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
URL: url,
|
||||
Branch: branch,
|
||||
Interval: interval,
|
||||
TargetPath: targetPath,
|
||||
ManifestFile: sync.MakeDefaultOptions().ManifestFile,
|
||||
}
|
||||
|
||||
manifest, err := sync.Generate(opts)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("generating install manifests failed: %w", err)
|
||||
}
|
||||
|
||||
output, err := manifest.WriteFile(tmpDir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
outputDir := filepath.Dir(output)
|
||||
if err := utils.GenerateKustomizationYaml(outputDir); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return outputDir, nil
|
||||
}
|
||||
|
||||
func applySyncManifests(ctx context.Context, kubeClient client.Client, name, namespace, manifestsPath string) error {
|
||||
kubectlArgs := []string{"apply", "-k", manifestsPath}
|
||||
if _, err := utils.ExecKubectlCommand(ctx, utils.ModeStderrOS, rootArgs.kubeconfig, rootArgs.kubecontext, kubectlArgs...); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Waitingf("waiting for cluster sync")
|
||||
|
||||
var gitRepository sourcev1.GitRepository
|
||||
if err := wait.PollImmediate(rootArgs.pollInterval, rootArgs.timeout,
|
||||
isGitRepositoryReady(ctx, kubeClient, types.NamespacedName{Name: name, Namespace: namespace}, &gitRepository)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var kustomization kustomizev1.Kustomization
|
||||
if err := wait.PollImmediate(rootArgs.pollInterval, rootArgs.timeout,
|
||||
isKustomizationReady(ctx, kubeClient, types.NamespacedName{Name: name, Namespace: namespace}, &kustomization)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func shouldInstallManifests(ctx context.Context, kubeClient client.Client, namespace string) bool {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: namespace,
|
||||
}
|
||||
var kustomization kustomizev1.Kustomization
|
||||
if err := kubeClient.Get(ctx, namespacedName, &kustomization); err != nil {
|
||||
return true
|
||||
}
|
||||
|
||||
return kustomization.Status.LastAppliedRevision == ""
|
||||
}
|
||||
|
||||
func shouldCreateDeployKey(ctx context.Context, kubeClient client.Client, namespace string) bool {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: namespace,
|
||||
}
|
||||
|
||||
var existing corev1.Secret
|
||||
if err := kubeClient.Get(ctx, namespacedName, &existing); err != nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func generateDeployKey(ctx context.Context, kubeClient client.Client, url *url.URL, namespace string) (string, error) {
|
||||
pair, err := generateKeyPair(ctx, sourceArgs.GitKeyAlgorithm, sourceArgs.GitRSABits, sourceArgs.GitECDSACurve)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
hostKey, err := scanHostKey(ctx, url)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
secret := corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: namespace,
|
||||
Namespace: namespace,
|
||||
},
|
||||
StringData: map[string]string{
|
||||
"identity": string(pair.PrivateKey),
|
||||
"identity.pub": string(pair.PublicKey),
|
||||
"known_hosts": string(hostKey),
|
||||
},
|
||||
}
|
||||
if err := upsertSecret(ctx, kubeClient, secret); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(pair.PublicKey), nil
|
||||
}
|
||||
|
||||
func checkIfBootstrapPathDiffers(ctx context.Context, kubeClient client.Client, namespace string, path string) (string, bool) {
|
||||
namespacedName := types.NamespacedName{
|
||||
Name: namespace,
|
||||
Namespace: namespace,
|
||||
}
|
||||
var fluxSystemKustomization kustomizev1.Kustomization
|
||||
err := kubeClient.Get(ctx, namespacedName, &fluxSystemKustomization)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
if fluxSystemKustomization.Spec.Path == path {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return fluxSystemKustomization.Spec.Path, true
|
||||
return m
|
||||
}
|
||||
|
||||
263
cmd/flux/bootstrap_git.go
Normal file
263
cmd/flux/bootstrap_git.go
Normal file
@@ -0,0 +1,263 @@
|
||||
/*
|
||||
Copyright 2021 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-git/go-git/v5/plumbing/transport"
|
||||
"github.com/go-git/go-git/v5/plumbing/transport/http"
|
||||
"github.com/go-git/go-git/v5/plumbing/transport/ssh"
|
||||
"github.com/manifoldco/promptui"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/bootstrap"
|
||||
"github.com/fluxcd/flux2/internal/bootstrap/git/gogit"
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/install"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/sourcesecret"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/sync"
|
||||
)
|
||||
|
||||
var bootstrapGitCmd = &cobra.Command{
|
||||
Use: "git",
|
||||
Short: "Bootstrap toolkit components in a Git repository",
|
||||
Long: `The bootstrap git command commits the toolkit components manifests to the
|
||||
branch of a Git repository. It then configures the target cluster to synchronize with
|
||||
the repository. If the toolkit components are present on the cluster, the bootstrap
|
||||
command will perform an upgrade if needed.`,
|
||||
Example: ` # Run bootstrap for a Git repository and authenticate with your SSH agent
|
||||
flux bootstrap git --url=ssh://git@example.com/repository.git
|
||||
|
||||
# Run bootstrap for a Git repository and authenticate using a password
|
||||
flux bootstrap git --url=https://example.com/repository.git --password=<password>
|
||||
|
||||
# Run bootstrap for a Git repository with a passwordless private key
|
||||
flux bootstrap git --url=ssh://git@example.com/repository.git --private-key-file=<path/to/private.key>
|
||||
|
||||
# Run bootstrap for a Git repository with a private key and password
|
||||
flux bootstrap git --url=ssh://git@example.com/repository.git --private-key-file=<path/to/private.key> --password=<password>
|
||||
`,
|
||||
RunE: bootstrapGitCmdRun,
|
||||
}
|
||||
|
||||
type gitFlags struct {
|
||||
url string
|
||||
interval time.Duration
|
||||
path flags.SafeRelativePath
|
||||
username string
|
||||
password string
|
||||
silent bool
|
||||
}
|
||||
|
||||
var gitArgs gitFlags
|
||||
|
||||
func init() {
|
||||
bootstrapGitCmd.Flags().StringVar(&gitArgs.url, "url", "", "Git repository URL")
|
||||
bootstrapGitCmd.Flags().DurationVar(&gitArgs.interval, "interval", time.Minute, "sync interval")
|
||||
bootstrapGitCmd.Flags().Var(&gitArgs.path, "path", "path relative to the repository root, when specified the cluster sync will be scoped to this path")
|
||||
bootstrapGitCmd.Flags().StringVarP(&gitArgs.username, "username", "u", "git", "basic authentication username")
|
||||
bootstrapGitCmd.Flags().StringVarP(&gitArgs.password, "password", "p", "", "basic authentication password")
|
||||
bootstrapGitCmd.Flags().BoolVarP(&gitArgs.silent, "silent", "s", false, "assumes the deploy key is already setup, skips confirmation")
|
||||
|
||||
bootstrapCmd.AddCommand(bootstrapGitCmd)
|
||||
}
|
||||
|
||||
func bootstrapGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if err := bootstrapValidate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
repositoryURL, err := url.Parse(gitArgs.url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gitAuth, err := transportForURL(repositoryURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Manifest base
|
||||
if ver, err := getVersion(bootstrapArgs.version); err == nil {
|
||||
bootstrapArgs.version = ver
|
||||
}
|
||||
manifestsBase, err := buildEmbeddedManifestBase()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(manifestsBase)
|
||||
|
||||
// Lazy go-git repository
|
||||
tmpDir, err := os.MkdirTemp("", "flux-bootstrap-")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create temporary working dir: %w", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
gitClient := gogit.New(tmpDir, gitAuth)
|
||||
|
||||
// Install manifest config
|
||||
installOptions := install.Options{
|
||||
BaseURL: rootArgs.defaults.BaseURL,
|
||||
Version: bootstrapArgs.version,
|
||||
Namespace: rootArgs.namespace,
|
||||
Components: bootstrapComponents(),
|
||||
Registry: bootstrapArgs.registry,
|
||||
ImagePullSecret: bootstrapArgs.imagePullSecret,
|
||||
WatchAllNamespaces: bootstrapArgs.watchAllNamespaces,
|
||||
NetworkPolicy: bootstrapArgs.networkPolicy,
|
||||
LogLevel: bootstrapArgs.logLevel.String(),
|
||||
NotificationController: rootArgs.defaults.NotificationController,
|
||||
ManifestFile: rootArgs.defaults.ManifestFile,
|
||||
Timeout: rootArgs.timeout,
|
||||
TargetPath: gitArgs.path.ToSlash(),
|
||||
ClusterDomain: bootstrapArgs.clusterDomain,
|
||||
TolerationKeys: bootstrapArgs.tolerationKeys,
|
||||
}
|
||||
if customBaseURL := bootstrapArgs.manifestsPath; customBaseURL != "" {
|
||||
installOptions.BaseURL = customBaseURL
|
||||
}
|
||||
|
||||
// Source generation and secret config
|
||||
secretOpts := sourcesecret.Options{
|
||||
Name: bootstrapArgs.secretName,
|
||||
Namespace: rootArgs.namespace,
|
||||
TargetPath: gitArgs.path.String(),
|
||||
ManifestFile: sourcesecret.MakeDefaultOptions().ManifestFile,
|
||||
}
|
||||
if bootstrapArgs.tokenAuth {
|
||||
secretOpts.Username = gitArgs.username
|
||||
secretOpts.Password = gitArgs.password
|
||||
|
||||
if bootstrapArgs.caFile != "" {
|
||||
secretOpts.CAFilePath = bootstrapArgs.caFile
|
||||
}
|
||||
|
||||
// Configure repository URL to match auth config for sync.
|
||||
repositoryURL.User = nil
|
||||
repositoryURL.Scheme = "https"
|
||||
repositoryURL.Host = repositoryURL.Hostname()
|
||||
} else {
|
||||
secretOpts.PrivateKeyAlgorithm = sourcesecret.PrivateKeyAlgorithm(bootstrapArgs.keyAlgorithm)
|
||||
secretOpts.Password = gitArgs.password
|
||||
secretOpts.RSAKeyBits = int(bootstrapArgs.keyRSABits)
|
||||
secretOpts.ECDSACurve = bootstrapArgs.keyECDSACurve.Curve
|
||||
|
||||
// Configure repository URL to match auth config for sync.
|
||||
repositoryURL.User = url.User(gitArgs.username)
|
||||
repositoryURL.Scheme = "ssh"
|
||||
if bootstrapArgs.sshHostname != "" {
|
||||
repositoryURL.Host = bootstrapArgs.sshHostname
|
||||
}
|
||||
if bootstrapArgs.privateKeyFile != "" {
|
||||
secretOpts.PrivateKeyPath = bootstrapArgs.privateKeyFile
|
||||
}
|
||||
|
||||
// Configure last as it depends on the config above.
|
||||
secretOpts.SSHHostname = repositoryURL.Host
|
||||
}
|
||||
|
||||
// Sync manifest config
|
||||
syncOpts := sync.Options{
|
||||
Interval: gitArgs.interval,
|
||||
Name: rootArgs.namespace,
|
||||
Namespace: rootArgs.namespace,
|
||||
URL: repositoryURL.String(),
|
||||
Branch: bootstrapArgs.branch,
|
||||
Secret: bootstrapArgs.secretName,
|
||||
TargetPath: gitArgs.path.ToSlash(),
|
||||
ManifestFile: sync.MakeDefaultOptions().ManifestFile,
|
||||
GitImplementation: sourceGitArgs.gitImplementation.String(),
|
||||
RecurseSubmodules: bootstrapArgs.recurseSubmodules,
|
||||
}
|
||||
|
||||
// Bootstrap config
|
||||
bootstrapOpts := []bootstrap.GitOption{
|
||||
bootstrap.WithRepositoryURL(gitArgs.url),
|
||||
bootstrap.WithBranch(bootstrapArgs.branch),
|
||||
bootstrap.WithAuthor(bootstrapArgs.authorName, bootstrapArgs.authorEmail),
|
||||
bootstrap.WithCommitMessageAppendix(bootstrapArgs.commitMessageAppendix),
|
||||
bootstrap.WithKubeconfig(rootArgs.kubeconfig, rootArgs.kubecontext),
|
||||
bootstrap.WithPostGenerateSecretFunc(promptPublicKey),
|
||||
bootstrap.WithLogger(logger),
|
||||
}
|
||||
|
||||
// Setup bootstrapper with constructed configs
|
||||
b, err := bootstrap.NewPlainGitProvider(gitClient, kubeClient, bootstrapOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Run
|
||||
return bootstrap.Run(ctx, b, manifestsBase, installOptions, secretOpts, syncOpts, rootArgs.pollInterval, rootArgs.timeout)
|
||||
}
|
||||
|
||||
// transportForURL constructs a transport.AuthMethod based on the scheme
|
||||
// of the given URL and the configured flags. If the protocol equals
|
||||
// "ssh" but no private key is configured, authentication using the local
|
||||
// SSH-agent is attempted.
|
||||
func transportForURL(u *url.URL) (transport.AuthMethod, error) {
|
||||
switch u.Scheme {
|
||||
case "https":
|
||||
return &http.BasicAuth{
|
||||
Username: gitArgs.username,
|
||||
Password: gitArgs.password,
|
||||
}, nil
|
||||
case "ssh":
|
||||
if bootstrapArgs.privateKeyFile != "" {
|
||||
return ssh.NewPublicKeysFromFile(u.User.Username(), bootstrapArgs.privateKeyFile, gitArgs.password)
|
||||
}
|
||||
return nil, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("scheme %q is not supported", u.Scheme)
|
||||
}
|
||||
}
|
||||
|
||||
func promptPublicKey(ctx context.Context, secret corev1.Secret, _ sourcesecret.Options) error {
|
||||
ppk, ok := secret.StringData[sourcesecret.PublicKeySecretKey]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.Successf("public key: %s", strings.TrimSpace(ppk))
|
||||
|
||||
if !gitArgs.silent {
|
||||
prompt := promptui.Prompt{
|
||||
Label: "Please give the key access to your repository",
|
||||
IsConfirm: true,
|
||||
}
|
||||
_, err := prompt.Run()
|
||||
if err != nil {
|
||||
return fmt.Errorf("aborting")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -19,21 +19,20 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/go-git/go-git/v5/plumbing/transport/http"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
"github.com/fluxcd/pkg/git"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/bootstrap"
|
||||
"github.com/fluxcd/flux2/internal/bootstrap/git/gogit"
|
||||
"github.com/fluxcd/flux2/internal/bootstrap/provider"
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/install"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/sourcesecret"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/sync"
|
||||
)
|
||||
|
||||
var bootstrapGitHubCmd = &cobra.Command{
|
||||
@@ -47,45 +46,46 @@ the bootstrap command will perform an upgrade if needed.`,
|
||||
Example: ` # Create a GitHub personal access token and export it as an env var
|
||||
export GITHUB_TOKEN=<my-token>
|
||||
|
||||
# Run bootstrap for a private repo owned by a GitHub organization
|
||||
flux bootstrap github --owner=<organization> --repository=<repo name>
|
||||
# Run bootstrap for a private repository owned by a GitHub organization
|
||||
flux bootstrap github --owner=<organization> --repository=<repository name>
|
||||
|
||||
# Run bootstrap for a private repo and assign organization teams to it
|
||||
flux bootstrap github --owner=<organization> --repository=<repo name> --team=<team1 slug> --team=<team2 slug>
|
||||
# Run bootstrap for a private repository and assign organization teams to it
|
||||
flux bootstrap github --owner=<organization> --repository=<repository name> --team=<team1 slug> --team=<team2 slug>
|
||||
|
||||
# Run bootstrap for a repository path
|
||||
flux bootstrap github --owner=<organization> --repository=<repo name> --path=dev-cluster
|
||||
flux bootstrap github --owner=<organization> --repository=<repository name> --path=dev-cluster
|
||||
|
||||
# Run bootstrap for a public repository on a personal account
|
||||
flux bootstrap github --owner=<user> --repository=<repo name> --private=false --personal=true
|
||||
flux bootstrap github --owner=<user> --repository=<repository name> --private=false --personal=true
|
||||
|
||||
# Run bootstrap for a private repo hosted on GitHub Enterprise using SSH auth
|
||||
flux bootstrap github --owner=<organization> --repository=<repo name> --hostname=<domain> --ssh-hostname=<domain>
|
||||
# Run bootstrap for a private repository hosted on GitHub Enterprise using SSH auth
|
||||
flux bootstrap github --owner=<organization> --repository=<repository name> --hostname=<domain> --ssh-hostname=<domain>
|
||||
|
||||
# Run bootstrap for a private repo hosted on GitHub Enterprise using HTTPS auth
|
||||
flux bootstrap github --owner=<organization> --repository=<repo name> --hostname=<domain> --token-auth
|
||||
# Run bootstrap for a private repository hosted on GitHub Enterprise using HTTPS auth
|
||||
flux bootstrap github --owner=<organization> --repository=<repository name> --hostname=<domain> --token-auth
|
||||
|
||||
# Run bootstrap for a an existing repository with a branch named main
|
||||
flux bootstrap github --owner=<organization> --repository=<repo name> --branch=main
|
||||
`,
|
||||
# Run bootstrap for an existing repository with a branch named main
|
||||
flux bootstrap github --owner=<organization> --repository=<repository name> --branch=main`,
|
||||
RunE: bootstrapGitHubCmdRun,
|
||||
}
|
||||
|
||||
type githubFlags struct {
|
||||
owner string
|
||||
repository string
|
||||
interval time.Duration
|
||||
personal bool
|
||||
private bool
|
||||
hostname string
|
||||
path flags.SafeRelativePath
|
||||
teams []string
|
||||
delete bool
|
||||
sshHostname string
|
||||
owner string
|
||||
repository string
|
||||
interval time.Duration
|
||||
personal bool
|
||||
private bool
|
||||
hostname string
|
||||
path flags.SafeRelativePath
|
||||
teams []string
|
||||
readWriteKey bool
|
||||
reconcile bool
|
||||
}
|
||||
|
||||
const (
|
||||
ghDefaultPermission = "maintain"
|
||||
ghDefaultDomain = "github.com"
|
||||
ghTokenEnvVar = "GITHUB_TOKEN"
|
||||
)
|
||||
|
||||
var githubArgs githubFlags
|
||||
@@ -93,24 +93,22 @@ var githubArgs githubFlags
|
||||
func init() {
|
||||
bootstrapGitHubCmd.Flags().StringVar(&githubArgs.owner, "owner", "", "GitHub user or organization name")
|
||||
bootstrapGitHubCmd.Flags().StringVar(&githubArgs.repository, "repository", "", "GitHub repository name")
|
||||
bootstrapGitHubCmd.Flags().StringArrayVar(&githubArgs.teams, "team", []string{}, "GitHub team to be given maintainer access")
|
||||
bootstrapGitHubCmd.Flags().BoolVar(&githubArgs.personal, "personal", false, "is personal repository")
|
||||
bootstrapGitHubCmd.Flags().BoolVar(&githubArgs.private, "private", true, "is private repository")
|
||||
bootstrapGitHubCmd.Flags().StringSliceVar(&githubArgs.teams, "team", []string{}, "GitHub team to be given maintainer access (also accepts comma-separated values)")
|
||||
bootstrapGitHubCmd.Flags().BoolVar(&githubArgs.personal, "personal", false, "if true, the owner is assumed to be a GitHub user; otherwise an org")
|
||||
bootstrapGitHubCmd.Flags().BoolVar(&githubArgs.private, "private", true, "if true, the repository is setup or configured as private")
|
||||
bootstrapGitHubCmd.Flags().DurationVar(&githubArgs.interval, "interval", time.Minute, "sync interval")
|
||||
bootstrapGitHubCmd.Flags().StringVar(&githubArgs.hostname, "hostname", git.GitHubDefaultHostname, "GitHub hostname")
|
||||
bootstrapGitHubCmd.Flags().StringVar(&githubArgs.sshHostname, "ssh-hostname", "", "GitHub SSH hostname, to be used when the SSH host differs from the HTTPS one")
|
||||
bootstrapGitHubCmd.Flags().StringVar(&githubArgs.hostname, "hostname", ghDefaultDomain, "GitHub hostname")
|
||||
bootstrapGitHubCmd.Flags().Var(&githubArgs.path, "path", "path relative to the repository root, when specified the cluster sync will be scoped to this path")
|
||||
|
||||
bootstrapGitHubCmd.Flags().BoolVar(&githubArgs.delete, "delete", false, "delete repository (used for testing only)")
|
||||
bootstrapGitHubCmd.Flags().MarkHidden("delete")
|
||||
bootstrapGitHubCmd.Flags().BoolVar(&githubArgs.readWriteKey, "read-write-key", false, "if true, the deploy key is configured with read/write permissions")
|
||||
bootstrapGitHubCmd.Flags().BoolVar(&githubArgs.reconcile, "reconcile", false, "if true, the configured options are also reconciled if the repository already exists")
|
||||
|
||||
bootstrapCmd.AddCommand(bootstrapGitHubCmd)
|
||||
}
|
||||
|
||||
func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ghToken := os.Getenv(git.GitHubTokenName)
|
||||
ghToken := os.Getenv(ghTokenEnvVar)
|
||||
if ghToken == "" {
|
||||
return fmt.Errorf("%s environment variable not found", git.GitHubTokenName)
|
||||
return fmt.Errorf("%s environment variable not found", ghTokenEnvVar)
|
||||
}
|
||||
|
||||
if err := bootstrapValidate(); err != nil {
|
||||
@@ -125,176 +123,129 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
usedPath, bootstrapPathDiffers := checkIfBootstrapPathDiffers(ctx, kubeClient, rootArgs.namespace, filepath.ToSlash(githubArgs.path.String()))
|
||||
|
||||
if bootstrapPathDiffers {
|
||||
return fmt.Errorf("cluster already bootstrapped to %v path", usedPath)
|
||||
// Manifest base
|
||||
if ver, err := getVersion(bootstrapArgs.version); err == nil {
|
||||
bootstrapArgs.version = ver
|
||||
}
|
||||
manifestsBase, err := buildEmbeddedManifestBase()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(manifestsBase)
|
||||
|
||||
repository, err := git.NewRepository(githubArgs.repository, githubArgs.owner, githubArgs.hostname, ghToken, "flux", githubArgs.owner+"@users.noreply.github.com")
|
||||
// Build GitHub provider
|
||||
providerCfg := provider.Config{
|
||||
Provider: provider.GitProviderGitHub,
|
||||
Hostname: githubArgs.hostname,
|
||||
Token: ghToken,
|
||||
}
|
||||
providerClient, err := provider.BuildGitProvider(providerCfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if githubArgs.sshHostname != "" {
|
||||
repository.SSHHost = githubArgs.sshHostname
|
||||
}
|
||||
|
||||
provider := &git.GithubProvider{
|
||||
IsPrivate: githubArgs.private,
|
||||
IsPersonal: githubArgs.personal,
|
||||
}
|
||||
|
||||
tmpDir, err := ioutil.TempDir("", rootArgs.namespace)
|
||||
// Lazy go-git repository
|
||||
tmpDir, err := os.MkdirTemp("", "flux-bootstrap-")
|
||||
if err != nil {
|
||||
return err
|
||||
return fmt.Errorf("failed to create temporary working dir: %w", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
gitClient := gogit.New(tmpDir, &http.BasicAuth{
|
||||
Username: githubArgs.owner,
|
||||
Password: ghToken,
|
||||
})
|
||||
|
||||
if githubArgs.delete {
|
||||
if err := provider.DeleteRepository(ctx, repository); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("repository deleted")
|
||||
return nil
|
||||
// Install manifest config
|
||||
installOptions := install.Options{
|
||||
BaseURL: rootArgs.defaults.BaseURL,
|
||||
Version: bootstrapArgs.version,
|
||||
Namespace: rootArgs.namespace,
|
||||
Components: bootstrapComponents(),
|
||||
Registry: bootstrapArgs.registry,
|
||||
ImagePullSecret: bootstrapArgs.imagePullSecret,
|
||||
WatchAllNamespaces: bootstrapArgs.watchAllNamespaces,
|
||||
NetworkPolicy: bootstrapArgs.networkPolicy,
|
||||
LogLevel: bootstrapArgs.logLevel.String(),
|
||||
NotificationController: rootArgs.defaults.NotificationController,
|
||||
ManifestFile: rootArgs.defaults.ManifestFile,
|
||||
Timeout: rootArgs.timeout,
|
||||
TargetPath: githubArgs.path.ToSlash(),
|
||||
ClusterDomain: bootstrapArgs.clusterDomain,
|
||||
TolerationKeys: bootstrapArgs.tolerationKeys,
|
||||
}
|
||||
if customBaseURL := bootstrapArgs.manifestsPath; customBaseURL != "" {
|
||||
installOptions.BaseURL = customBaseURL
|
||||
}
|
||||
|
||||
// create GitHub repository if doesn't exists
|
||||
logger.Actionf("connecting to %s", githubArgs.hostname)
|
||||
changed, err := provider.CreateRepository(ctx, repository)
|
||||
if err != nil {
|
||||
return err
|
||||
// Source generation and secret config
|
||||
secretOpts := sourcesecret.Options{
|
||||
Name: bootstrapArgs.secretName,
|
||||
Namespace: rootArgs.namespace,
|
||||
TargetPath: githubArgs.path.ToSlash(),
|
||||
ManifestFile: sourcesecret.MakeDefaultOptions().ManifestFile,
|
||||
}
|
||||
if changed {
|
||||
logger.Successf("repository created")
|
||||
}
|
||||
|
||||
withErrors := false
|
||||
// add teams to org repository
|
||||
if !githubArgs.personal {
|
||||
for _, team := range githubArgs.teams {
|
||||
if changed, err := provider.AddTeam(ctx, repository, team, ghDefaultPermission); err != nil {
|
||||
logger.Failuref(err.Error())
|
||||
withErrors = true
|
||||
} else if changed {
|
||||
logger.Successf("%s team access granted", team)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// clone repository and checkout the main branch
|
||||
if err := repository.Checkout(ctx, bootstrapArgs.branch, tmpDir); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("repository cloned")
|
||||
|
||||
// generate install manifests
|
||||
logger.Generatef("generating manifests")
|
||||
installManifest, err := generateInstallManifests(githubArgs.path.String(), rootArgs.namespace, tmpDir, bootstrapArgs.manifestsPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// stage install manifests
|
||||
changed, err = repository.Commit(ctx, path.Join(githubArgs.path.String(), rootArgs.namespace), "Add manifests")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// push install manifests
|
||||
if changed {
|
||||
if err := repository.Push(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("components manifests pushed")
|
||||
} else {
|
||||
logger.Successf("components are up to date")
|
||||
}
|
||||
|
||||
// determine if repo synchronization is working
|
||||
isInstall := shouldInstallManifests(ctx, kubeClient, rootArgs.namespace)
|
||||
|
||||
if isInstall {
|
||||
// apply install manifests
|
||||
logger.Actionf("installing components in %s namespace", rootArgs.namespace)
|
||||
if err := applyInstallManifests(ctx, installManifest, bootstrapComponents()); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("install completed")
|
||||
}
|
||||
|
||||
repoURL := repository.GetURL()
|
||||
|
||||
if bootstrapArgs.tokenAuth {
|
||||
// setup HTTPS token auth
|
||||
secret := corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: rootArgs.namespace,
|
||||
Namespace: rootArgs.namespace,
|
||||
},
|
||||
StringData: map[string]string{
|
||||
"username": "git",
|
||||
"password": ghToken,
|
||||
},
|
||||
}
|
||||
if err := upsertSecret(ctx, kubeClient, secret); err != nil {
|
||||
return err
|
||||
secretOpts.Username = "git"
|
||||
secretOpts.Password = ghToken
|
||||
|
||||
if bootstrapArgs.caFile != "" {
|
||||
secretOpts.CAFilePath = bootstrapArgs.caFile
|
||||
}
|
||||
} else {
|
||||
// setup SSH deploy key
|
||||
repoURL = repository.GetSSH()
|
||||
if shouldCreateDeployKey(ctx, kubeClient, rootArgs.namespace) {
|
||||
logger.Actionf("configuring deploy key")
|
||||
u, err := url.Parse(repository.GetSSH())
|
||||
if err != nil {
|
||||
return fmt.Errorf("git URL parse failed: %w", err)
|
||||
}
|
||||
secretOpts.PrivateKeyAlgorithm = sourcesecret.PrivateKeyAlgorithm(bootstrapArgs.keyAlgorithm)
|
||||
secretOpts.RSAKeyBits = int(bootstrapArgs.keyRSABits)
|
||||
secretOpts.ECDSACurve = bootstrapArgs.keyECDSACurve.Curve
|
||||
secretOpts.SSHHostname = githubArgs.hostname
|
||||
|
||||
key, err := generateDeployKey(ctx, kubeClient, u, rootArgs.namespace)
|
||||
if err != nil {
|
||||
return fmt.Errorf("generating deploy key failed: %w", err)
|
||||
}
|
||||
|
||||
keyName := "flux"
|
||||
if githubArgs.path != "" {
|
||||
keyName = fmt.Sprintf("flux-%s", githubArgs.path)
|
||||
}
|
||||
|
||||
if changed, err := provider.AddDeployKey(ctx, repository, key, keyName); err != nil {
|
||||
return err
|
||||
} else if changed {
|
||||
logger.Successf("deploy key configured")
|
||||
}
|
||||
if bootstrapArgs.sshHostname != "" {
|
||||
secretOpts.SSHHostname = bootstrapArgs.sshHostname
|
||||
}
|
||||
}
|
||||
|
||||
// configure repo synchronization
|
||||
logger.Actionf("generating sync manifests")
|
||||
syncManifests, err := generateSyncManifests(repoURL, bootstrapArgs.branch, rootArgs.namespace, rootArgs.namespace, filepath.ToSlash(githubArgs.path.String()), tmpDir, githubArgs.interval)
|
||||
// Sync manifest config
|
||||
syncOpts := sync.Options{
|
||||
Interval: githubArgs.interval,
|
||||
Name: rootArgs.namespace,
|
||||
Namespace: rootArgs.namespace,
|
||||
Branch: bootstrapArgs.branch,
|
||||
Secret: bootstrapArgs.secretName,
|
||||
TargetPath: githubArgs.path.ToSlash(),
|
||||
ManifestFile: sync.MakeDefaultOptions().ManifestFile,
|
||||
GitImplementation: sourceGitArgs.gitImplementation.String(),
|
||||
RecurseSubmodules: bootstrapArgs.recurseSubmodules,
|
||||
}
|
||||
|
||||
// Bootstrap config
|
||||
bootstrapOpts := []bootstrap.GitProviderOption{
|
||||
bootstrap.WithProviderRepository(githubArgs.owner, githubArgs.repository, githubArgs.personal),
|
||||
bootstrap.WithBranch(bootstrapArgs.branch),
|
||||
bootstrap.WithBootstrapTransportType("https"),
|
||||
bootstrap.WithAuthor(bootstrapArgs.authorName, bootstrapArgs.authorEmail),
|
||||
bootstrap.WithCommitMessageAppendix(bootstrapArgs.commitMessageAppendix),
|
||||
bootstrap.WithProviderTeamPermissions(mapTeamSlice(githubArgs.teams, ghDefaultPermission)),
|
||||
bootstrap.WithReadWriteKeyPermissions(githubArgs.readWriteKey),
|
||||
bootstrap.WithKubeconfig(rootArgs.kubeconfig, rootArgs.kubecontext),
|
||||
bootstrap.WithLogger(logger),
|
||||
}
|
||||
if bootstrapArgs.sshHostname != "" {
|
||||
bootstrapOpts = append(bootstrapOpts, bootstrap.WithSSHHostname(bootstrapArgs.sshHostname))
|
||||
}
|
||||
if bootstrapArgs.tokenAuth {
|
||||
bootstrapOpts = append(bootstrapOpts, bootstrap.WithSyncTransportType("https"))
|
||||
}
|
||||
if !githubArgs.private {
|
||||
bootstrapOpts = append(bootstrapOpts, bootstrap.WithProviderRepositoryConfig("", "", "public"))
|
||||
}
|
||||
if githubArgs.reconcile {
|
||||
bootstrapOpts = append(bootstrapOpts, bootstrap.WithReconcile())
|
||||
}
|
||||
|
||||
// Setup bootstrapper with constructed configs
|
||||
b, err := bootstrap.NewGitProviderBootstrapper(gitClient, providerClient, kubeClient, bootstrapOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// commit and push manifests
|
||||
if changed, err = repository.Commit(ctx, path.Join(githubArgs.path.String(), rootArgs.namespace), "Add manifests"); err != nil {
|
||||
return err
|
||||
} else if changed {
|
||||
if err := repository.Push(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("sync manifests pushed")
|
||||
}
|
||||
|
||||
// apply manifests and waiting for sync
|
||||
logger.Actionf("applying sync manifests")
|
||||
if err := applySyncManifests(ctx, kubeClient, rootArgs.namespace, rootArgs.namespace, syncManifests); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if withErrors {
|
||||
return fmt.Errorf("bootstrap completed with errors")
|
||||
}
|
||||
|
||||
logger.Successf("bootstrap finished")
|
||||
return nil
|
||||
// Run
|
||||
return bootstrap.Run(ctx, b, manifestsBase, installOptions, secretOpts, syncOpts, rootArgs.pollInterval, rootArgs.timeout)
|
||||
}
|
||||
|
||||
@@ -19,22 +19,22 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-git/go-git/v5/plumbing/transport/http"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
"github.com/fluxcd/pkg/git"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/bootstrap"
|
||||
"github.com/fluxcd/flux2/internal/bootstrap/git/gogit"
|
||||
"github.com/fluxcd/flux2/internal/bootstrap/provider"
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/install"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/sourcesecret"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/sync"
|
||||
)
|
||||
|
||||
var bootstrapGitLabCmd = &cobra.Command{
|
||||
@@ -48,40 +48,44 @@ the bootstrap command will perform an upgrade if needed.`,
|
||||
Example: ` # Create a GitLab API token and export it as an env var
|
||||
export GITLAB_TOKEN=<my-token>
|
||||
|
||||
# Run bootstrap for a private repo using HTTPS token authentication
|
||||
flux bootstrap gitlab --owner=<group> --repository=<repo name> --token-auth
|
||||
# Run bootstrap for a private repository using HTTPS token authentication
|
||||
flux bootstrap gitlab --owner=<group> --repository=<repository name> --token-auth
|
||||
|
||||
# Run bootstrap for a private repo using SSH authentication
|
||||
flux bootstrap gitlab --owner=<group> --repository=<repo name>
|
||||
# Run bootstrap for a private repository using SSH authentication
|
||||
flux bootstrap gitlab --owner=<group> --repository=<repository name>
|
||||
|
||||
# Run bootstrap for a repository path
|
||||
flux bootstrap gitlab --owner=<group> --repository=<repo name> --path=dev-cluster
|
||||
flux bootstrap gitlab --owner=<group> --repository=<repository name> --path=dev-cluster
|
||||
|
||||
# Run bootstrap for a public repository on a personal account
|
||||
flux bootstrap gitlab --owner=<user> --repository=<repo name> --private=false --personal --token-auth
|
||||
flux bootstrap gitlab --owner=<user> --repository=<repository name> --private=false --personal --token-auth
|
||||
|
||||
# Run bootstrap for a private repo hosted on a GitLab server
|
||||
flux bootstrap gitlab --owner=<group> --repository=<repo name> --hostname=<domain> --token-auth
|
||||
# Run bootstrap for a private repository hosted on a GitLab server
|
||||
flux bootstrap gitlab --owner=<group> --repository=<repository name> --hostname=<domain> --token-auth
|
||||
|
||||
# Run bootstrap for a an existing repository with a branch named main
|
||||
flux bootstrap gitlab --owner=<organization> --repository=<repo name> --branch=main --token-auth
|
||||
`,
|
||||
flux bootstrap gitlab --owner=<organization> --repository=<repository name> --branch=main --token-auth`,
|
||||
RunE: bootstrapGitLabCmdRun,
|
||||
}
|
||||
|
||||
const (
|
||||
gitlabProjectRegex = `\A[[:alnum:]\x{00A9}-\x{1f9ff}_][[:alnum:]\p{Pd}\x{00A9}-\x{1f9ff}_\.]*\z`
|
||||
glDefaultPermission = "maintain"
|
||||
glDefaultDomain = "gitlab.com"
|
||||
glTokenEnvVar = "GITLAB_TOKEN"
|
||||
gitlabProjectRegex = `\A[[:alnum:]\x{00A9}-\x{1f9ff}_][[:alnum:]\p{Pd}\x{00A9}-\x{1f9ff}_\.]*\z`
|
||||
)
|
||||
|
||||
type gitlabFlags struct {
|
||||
owner string
|
||||
repository string
|
||||
interval time.Duration
|
||||
personal bool
|
||||
private bool
|
||||
hostname string
|
||||
sshHostname string
|
||||
path flags.SafeRelativePath
|
||||
owner string
|
||||
repository string
|
||||
interval time.Duration
|
||||
personal bool
|
||||
private bool
|
||||
hostname string
|
||||
path flags.SafeRelativePath
|
||||
teams []string
|
||||
readWriteKey bool
|
||||
reconcile bool
|
||||
}
|
||||
|
||||
var gitlabArgs gitlabFlags
|
||||
@@ -89,29 +93,30 @@ var gitlabArgs gitlabFlags
|
||||
func init() {
|
||||
bootstrapGitLabCmd.Flags().StringVar(&gitlabArgs.owner, "owner", "", "GitLab user or group name")
|
||||
bootstrapGitLabCmd.Flags().StringVar(&gitlabArgs.repository, "repository", "", "GitLab repository name")
|
||||
bootstrapGitLabCmd.Flags().BoolVar(&gitlabArgs.personal, "personal", false, "is personal repository")
|
||||
bootstrapGitLabCmd.Flags().BoolVar(&gitlabArgs.private, "private", true, "is private repository")
|
||||
bootstrapGitLabCmd.Flags().StringSliceVar(&gitlabArgs.teams, "team", []string{}, "GitLab teams to be given maintainer access (also accepts comma-separated values)")
|
||||
bootstrapGitLabCmd.Flags().BoolVar(&gitlabArgs.personal, "personal", false, "if true, the owner is assumed to be a GitLab user; otherwise a group")
|
||||
bootstrapGitLabCmd.Flags().BoolVar(&gitlabArgs.private, "private", true, "if true, the repository is setup or configured as private")
|
||||
bootstrapGitLabCmd.Flags().DurationVar(&gitlabArgs.interval, "interval", time.Minute, "sync interval")
|
||||
bootstrapGitLabCmd.Flags().StringVar(&gitlabArgs.hostname, "hostname", git.GitLabDefaultHostname, "GitLab hostname")
|
||||
bootstrapGitLabCmd.Flags().StringVar(&gitlabArgs.sshHostname, "ssh-hostname", "", "GitLab SSH hostname, to be used when the SSH host differs from the HTTPS one")
|
||||
bootstrapGitLabCmd.Flags().StringVar(&gitlabArgs.hostname, "hostname", glDefaultDomain, "GitLab hostname")
|
||||
bootstrapGitLabCmd.Flags().Var(&gitlabArgs.path, "path", "path relative to the repository root, when specified the cluster sync will be scoped to this path")
|
||||
bootstrapGitLabCmd.Flags().BoolVar(&gitlabArgs.readWriteKey, "read-write-key", false, "if true, the deploy key is configured with read/write permissions")
|
||||
bootstrapGitLabCmd.Flags().BoolVar(&gitlabArgs.reconcile, "reconcile", false, "if true, the configured options are also reconciled if the repository already exists")
|
||||
|
||||
bootstrapCmd.AddCommand(bootstrapGitLabCmd)
|
||||
}
|
||||
|
||||
func bootstrapGitLabCmdRun(cmd *cobra.Command, args []string) error {
|
||||
glToken := os.Getenv(git.GitLabTokenName)
|
||||
glToken := os.Getenv(glTokenEnvVar)
|
||||
if glToken == "" {
|
||||
return fmt.Errorf("%s environment variable not found", git.GitLabTokenName)
|
||||
return fmt.Errorf("%s environment variable not found", glTokenEnvVar)
|
||||
}
|
||||
|
||||
projectNameIsValid, err := regexp.MatchString(gitlabProjectRegex, gitlabArgs.repository)
|
||||
if err != nil {
|
||||
if projectNameIsValid, err := regexp.MatchString(gitlabProjectRegex, gitlabArgs.repository); err != nil || !projectNameIsValid {
|
||||
if err == nil {
|
||||
err = fmt.Errorf("%s is an invalid project name for gitlab.\nIt can contain only letters, digits, emojis, '_', '.', dash, space. It must start with letter, digit, emoji or '_'.", gitlabArgs.repository)
|
||||
}
|
||||
return err
|
||||
}
|
||||
if !projectNameIsValid {
|
||||
return fmt.Errorf("%s is an invalid project name for gitlab.\nIt can contain only letters, digits, emojis, '_', '.', dash, space. It must start with letter, digit, emoji or '_'.", gitlabArgs.repository)
|
||||
}
|
||||
|
||||
if err := bootstrapValidate(); err != nil {
|
||||
return err
|
||||
@@ -125,151 +130,138 @@ func bootstrapGitLabCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
usedPath, bootstrapPathDiffers := checkIfBootstrapPathDiffers(ctx, kubeClient, rootArgs.namespace, filepath.ToSlash(gitlabArgs.path.String()))
|
||||
|
||||
if bootstrapPathDiffers {
|
||||
return fmt.Errorf("cluster already bootstrapped to %v path", usedPath)
|
||||
// Manifest base
|
||||
if ver, err := getVersion(bootstrapArgs.version); err == nil {
|
||||
bootstrapArgs.version = ver
|
||||
}
|
||||
manifestsBase, err := buildEmbeddedManifestBase()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(manifestsBase)
|
||||
|
||||
repository, err := git.NewRepository(gitlabArgs.repository, gitlabArgs.owner, gitlabArgs.hostname, glToken, "flux", gitlabArgs.owner+"@users.noreply.gitlab.com")
|
||||
// Build GitLab provider
|
||||
providerCfg := provider.Config{
|
||||
Provider: provider.GitProviderGitLab,
|
||||
Hostname: gitlabArgs.hostname,
|
||||
Token: glToken,
|
||||
}
|
||||
// Workaround for: https://github.com/fluxcd/go-git-providers/issues/55
|
||||
if hostname := providerCfg.Hostname; hostname != glDefaultDomain &&
|
||||
!strings.HasPrefix(hostname, "https://") &&
|
||||
!strings.HasPrefix(hostname, "http://") {
|
||||
providerCfg.Hostname = "https://" + providerCfg.Hostname
|
||||
}
|
||||
providerClient, err := provider.BuildGitProvider(providerCfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if gitlabArgs.sshHostname != "" {
|
||||
repository.SSHHost = gitlabArgs.sshHostname
|
||||
}
|
||||
|
||||
tmpDir, err := ioutil.TempDir("", rootArgs.namespace)
|
||||
// Lazy go-git repository
|
||||
tmpDir, err := os.MkdirTemp("", "flux-bootstrap-")
|
||||
if err != nil {
|
||||
return err
|
||||
return fmt.Errorf("failed to create temporary working dir: %w", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
gitClient := gogit.New(tmpDir, &http.BasicAuth{
|
||||
Username: gitlabArgs.owner,
|
||||
Password: glToken,
|
||||
})
|
||||
|
||||
provider := &git.GitLabProvider{
|
||||
IsPrivate: gitlabArgs.private,
|
||||
IsPersonal: gitlabArgs.personal,
|
||||
// Install manifest config
|
||||
installOptions := install.Options{
|
||||
BaseURL: rootArgs.defaults.BaseURL,
|
||||
Version: bootstrapArgs.version,
|
||||
Namespace: rootArgs.namespace,
|
||||
Components: bootstrapComponents(),
|
||||
Registry: bootstrapArgs.registry,
|
||||
ImagePullSecret: bootstrapArgs.imagePullSecret,
|
||||
WatchAllNamespaces: bootstrapArgs.watchAllNamespaces,
|
||||
NetworkPolicy: bootstrapArgs.networkPolicy,
|
||||
LogLevel: bootstrapArgs.logLevel.String(),
|
||||
NotificationController: rootArgs.defaults.NotificationController,
|
||||
ManifestFile: rootArgs.defaults.ManifestFile,
|
||||
Timeout: rootArgs.timeout,
|
||||
TargetPath: gitlabArgs.path.ToSlash(),
|
||||
ClusterDomain: bootstrapArgs.clusterDomain,
|
||||
TolerationKeys: bootstrapArgs.tolerationKeys,
|
||||
}
|
||||
if customBaseURL := bootstrapArgs.manifestsPath; customBaseURL != "" {
|
||||
installOptions.BaseURL = customBaseURL
|
||||
}
|
||||
|
||||
// create GitLab project if doesn't exists
|
||||
logger.Actionf("connecting to %s", gitlabArgs.hostname)
|
||||
changed, err := provider.CreateRepository(ctx, repository)
|
||||
if err != nil {
|
||||
return err
|
||||
// Source generation and secret config
|
||||
secretOpts := sourcesecret.Options{
|
||||
Name: bootstrapArgs.secretName,
|
||||
Namespace: rootArgs.namespace,
|
||||
TargetPath: gitlabArgs.path.String(),
|
||||
ManifestFile: sourcesecret.MakeDefaultOptions().ManifestFile,
|
||||
}
|
||||
if changed {
|
||||
logger.Successf("repository created")
|
||||
}
|
||||
|
||||
// clone repository and checkout the master branch
|
||||
if err := repository.Checkout(ctx, bootstrapArgs.branch, tmpDir); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("repository cloned")
|
||||
|
||||
// generate install manifests
|
||||
logger.Generatef("generating manifests")
|
||||
installManifest, err := generateInstallManifests(gitlabArgs.path.String(), rootArgs.namespace, tmpDir, bootstrapArgs.manifestsPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// stage install manifests
|
||||
changed, err = repository.Commit(ctx, path.Join(gitlabArgs.path.String(), rootArgs.namespace), "Add manifests")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// push install manifests
|
||||
if changed {
|
||||
if err := repository.Push(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("components manifests pushed")
|
||||
} else {
|
||||
logger.Successf("components are up to date")
|
||||
}
|
||||
|
||||
// determine if repo synchronization is working
|
||||
isInstall := shouldInstallManifests(ctx, kubeClient, rootArgs.namespace)
|
||||
|
||||
if isInstall {
|
||||
// apply install manifests
|
||||
logger.Actionf("installing components in %s namespace", rootArgs.namespace)
|
||||
if err := applyInstallManifests(ctx, installManifest, bootstrapComponents()); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("install completed")
|
||||
}
|
||||
|
||||
repoURL := repository.GetURL()
|
||||
|
||||
if bootstrapArgs.tokenAuth {
|
||||
// setup HTTPS token auth
|
||||
secret := corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: rootArgs.namespace,
|
||||
Namespace: rootArgs.namespace,
|
||||
},
|
||||
StringData: map[string]string{
|
||||
"username": "git",
|
||||
"password": glToken,
|
||||
},
|
||||
}
|
||||
if err := upsertSecret(ctx, kubeClient, secret); err != nil {
|
||||
return err
|
||||
secretOpts.Username = "git"
|
||||
secretOpts.Password = glToken
|
||||
|
||||
if bootstrapArgs.caFile != "" {
|
||||
secretOpts.CAFilePath = bootstrapArgs.caFile
|
||||
}
|
||||
} else {
|
||||
// setup SSH deploy key
|
||||
repoURL = repository.GetSSH()
|
||||
if shouldCreateDeployKey(ctx, kubeClient, rootArgs.namespace) {
|
||||
logger.Actionf("configuring deploy key")
|
||||
u, err := url.Parse(repoURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("git URL parse failed: %w", err)
|
||||
}
|
||||
secretOpts.PrivateKeyAlgorithm = sourcesecret.PrivateKeyAlgorithm(bootstrapArgs.keyAlgorithm)
|
||||
secretOpts.RSAKeyBits = int(bootstrapArgs.keyRSABits)
|
||||
secretOpts.ECDSACurve = bootstrapArgs.keyECDSACurve.Curve
|
||||
secretOpts.SSHHostname = gitlabArgs.hostname
|
||||
|
||||
key, err := generateDeployKey(ctx, kubeClient, u, rootArgs.namespace)
|
||||
if err != nil {
|
||||
return fmt.Errorf("generating deploy key failed: %w", err)
|
||||
}
|
||||
|
||||
keyName := "flux"
|
||||
if gitlabArgs.path != "" {
|
||||
keyName = fmt.Sprintf("flux-%s", gitlabArgs.path)
|
||||
}
|
||||
|
||||
if changed, err := provider.AddDeployKey(ctx, repository, key, keyName); err != nil {
|
||||
return err
|
||||
} else if changed {
|
||||
logger.Successf("deploy key configured")
|
||||
}
|
||||
if bootstrapArgs.privateKeyFile != "" {
|
||||
secretOpts.PrivateKeyPath = bootstrapArgs.privateKeyFile
|
||||
}
|
||||
if bootstrapArgs.sshHostname != "" {
|
||||
secretOpts.SSHHostname = bootstrapArgs.sshHostname
|
||||
}
|
||||
}
|
||||
|
||||
// configure repo synchronization
|
||||
logger.Actionf("generating sync manifests")
|
||||
syncManifests, err := generateSyncManifests(repoURL, bootstrapArgs.branch, rootArgs.namespace, rootArgs.namespace, filepath.ToSlash(gitlabArgs.path.String()), tmpDir, gitlabArgs.interval)
|
||||
// Sync manifest config
|
||||
syncOpts := sync.Options{
|
||||
Interval: gitlabArgs.interval,
|
||||
Name: rootArgs.namespace,
|
||||
Namespace: rootArgs.namespace,
|
||||
Branch: bootstrapArgs.branch,
|
||||
Secret: bootstrapArgs.secretName,
|
||||
TargetPath: gitlabArgs.path.ToSlash(),
|
||||
ManifestFile: sync.MakeDefaultOptions().ManifestFile,
|
||||
GitImplementation: sourceGitArgs.gitImplementation.String(),
|
||||
RecurseSubmodules: bootstrapArgs.recurseSubmodules,
|
||||
}
|
||||
|
||||
// Bootstrap config
|
||||
bootstrapOpts := []bootstrap.GitProviderOption{
|
||||
bootstrap.WithProviderRepository(gitlabArgs.owner, gitlabArgs.repository, gitlabArgs.personal),
|
||||
bootstrap.WithBranch(bootstrapArgs.branch),
|
||||
bootstrap.WithBootstrapTransportType("https"),
|
||||
bootstrap.WithAuthor(bootstrapArgs.authorName, bootstrapArgs.authorEmail),
|
||||
bootstrap.WithCommitMessageAppendix(bootstrapArgs.commitMessageAppendix),
|
||||
bootstrap.WithProviderTeamPermissions(mapTeamSlice(gitlabArgs.teams, glDefaultPermission)),
|
||||
bootstrap.WithReadWriteKeyPermissions(gitlabArgs.readWriteKey),
|
||||
bootstrap.WithKubeconfig(rootArgs.kubeconfig, rootArgs.kubecontext),
|
||||
bootstrap.WithLogger(logger),
|
||||
}
|
||||
if bootstrapArgs.sshHostname != "" {
|
||||
bootstrapOpts = append(bootstrapOpts, bootstrap.WithSSHHostname(bootstrapArgs.sshHostname))
|
||||
}
|
||||
if bootstrapArgs.tokenAuth {
|
||||
bootstrapOpts = append(bootstrapOpts, bootstrap.WithSyncTransportType("https"))
|
||||
}
|
||||
if !gitlabArgs.private {
|
||||
bootstrapOpts = append(bootstrapOpts, bootstrap.WithProviderRepositoryConfig("", "", "public"))
|
||||
}
|
||||
if gitlabArgs.reconcile {
|
||||
bootstrapOpts = append(bootstrapOpts, bootstrap.WithReconcile())
|
||||
}
|
||||
|
||||
// Setup bootstrapper with constructed configs
|
||||
b, err := bootstrap.NewGitProviderBootstrapper(gitClient, providerClient, kubeClient, bootstrapOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// commit and push manifests
|
||||
if changed, err = repository.Commit(ctx, path.Join(gitlabArgs.path.String(), rootArgs.namespace), "Add manifests"); err != nil {
|
||||
return err
|
||||
} else if changed {
|
||||
if err := repository.Push(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("sync manifests pushed")
|
||||
}
|
||||
|
||||
// apply manifests and waiting for sync
|
||||
logger.Actionf("applying sync manifests")
|
||||
if err := applySyncManifests(ctx, kubeClient, rootArgs.namespace, rootArgs.namespace, syncManifests); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Successf("bootstrap finished")
|
||||
return nil
|
||||
// Run
|
||||
return bootstrap.Run(ctx, b, manifestsBase, installOptions, secretOpts, syncOpts, rootArgs.pollInterval, rootArgs.timeout)
|
||||
}
|
||||
|
||||
@@ -21,13 +21,20 @@ import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/blang/semver/v4"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/Masterminds/semver/v3"
|
||||
"github.com/spf13/cobra"
|
||||
v1 "k8s.io/api/apps/v1"
|
||||
apimachineryversion "k8s.io/apimachinery/pkg/version"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/pkg/version"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/install"
|
||||
"github.com/fluxcd/flux2/pkg/status"
|
||||
)
|
||||
|
||||
var checkCmd = &cobra.Command{
|
||||
@@ -39,14 +46,14 @@ the local environment is configured correctly and if the installed components ar
|
||||
flux check --pre
|
||||
|
||||
# Run installation checks
|
||||
flux check
|
||||
`,
|
||||
flux check`,
|
||||
RunE: runCheckCmd,
|
||||
}
|
||||
|
||||
type checkFlags struct {
|
||||
pre bool
|
||||
components []string
|
||||
pre bool
|
||||
components []string
|
||||
extraComponents []string
|
||||
}
|
||||
|
||||
type kubectlVersion struct {
|
||||
@@ -60,6 +67,8 @@ func init() {
|
||||
"only run pre-installation checks")
|
||||
checkCmd.Flags().StringSliceVar(&checkArgs.components, "components", rootArgs.defaults.Components,
|
||||
"list of components, accepts comma-separated values")
|
||||
checkCmd.Flags().StringSliceVar(&checkArgs.extraComponents, "components-extra", nil,
|
||||
"list of components in addition to those supplied or defaulted, accepts comma-separated values")
|
||||
rootCmd.AddCommand(checkCmd)
|
||||
}
|
||||
|
||||
@@ -70,11 +79,13 @@ func runCheckCmd(cmd *cobra.Command, args []string) error {
|
||||
logger.Actionf("checking prerequisites")
|
||||
checkFailed := false
|
||||
|
||||
if !kubectlCheck(ctx, ">=1.18.0") {
|
||||
fluxCheck()
|
||||
|
||||
if !kubectlCheck(ctx, ">=1.18.0-0") {
|
||||
checkFailed = true
|
||||
}
|
||||
|
||||
if !kubernetesCheck(">=1.16.0") {
|
||||
if !kubernetesCheck(">=1.16.0-0") {
|
||||
checkFailed = true
|
||||
}
|
||||
|
||||
@@ -97,7 +108,29 @@ func runCheckCmd(cmd *cobra.Command, args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func kubectlCheck(ctx context.Context, version string) bool {
|
||||
func fluxCheck() {
|
||||
curSv, err := version.ParseVersion(VERSION)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// Exclude development builds.
|
||||
if curSv.Prerelease() != "" {
|
||||
return
|
||||
}
|
||||
latest, err := install.GetLatestVersion()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
latestSv, err := version.ParseVersion(latest)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if latestSv.GreaterThan(curSv) {
|
||||
logger.Failuref("flux %s <%s (new version is available, please upgrade)", curSv, latestSv)
|
||||
}
|
||||
}
|
||||
|
||||
func kubectlCheck(ctx context.Context, constraint string) bool {
|
||||
_, err := exec.LookPath("kubectl")
|
||||
if err != nil {
|
||||
logger.Failuref("kubectl not found")
|
||||
@@ -113,58 +146,58 @@ func kubectlCheck(ctx context.Context, version string) bool {
|
||||
|
||||
kv := &kubectlVersion{}
|
||||
if err = json.Unmarshal([]byte(output), kv); err != nil {
|
||||
logger.Failuref("kubectl version output can't be unmarshaled")
|
||||
logger.Failuref("kubectl version output can't be unmarshalled")
|
||||
return false
|
||||
}
|
||||
|
||||
v, err := semver.ParseTolerant(kv.ClientVersion.GitVersion)
|
||||
v, err := version.ParseVersion(kv.ClientVersion.GitVersion)
|
||||
if err != nil {
|
||||
logger.Failuref("kubectl version can't be parsed")
|
||||
return false
|
||||
}
|
||||
|
||||
rng, _ := semver.ParseRange(version)
|
||||
if !rng(v) {
|
||||
logger.Failuref("kubectl version must be %s", version)
|
||||
c, _ := semver.NewConstraint(constraint)
|
||||
if !c.Check(v) {
|
||||
logger.Failuref("kubectl version %s < %s", v.Original(), constraint)
|
||||
return false
|
||||
}
|
||||
|
||||
logger.Successf("kubectl %s %s", v.String(), version)
|
||||
logger.Successf("kubectl %s %s", v.String(), constraint)
|
||||
return true
|
||||
}
|
||||
|
||||
func kubernetesCheck(version string) bool {
|
||||
func kubernetesCheck(constraint string) bool {
|
||||
cfg, err := utils.KubeConfig(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
logger.Failuref("Kubernetes client initialization failed: %s", err.Error())
|
||||
return false
|
||||
}
|
||||
|
||||
client, err := kubernetes.NewForConfig(cfg)
|
||||
clientSet, err := kubernetes.NewForConfig(cfg)
|
||||
if err != nil {
|
||||
logger.Failuref("Kubernetes client initialization failed: %s", err.Error())
|
||||
return false
|
||||
}
|
||||
|
||||
ver, err := client.Discovery().ServerVersion()
|
||||
kv, err := clientSet.Discovery().ServerVersion()
|
||||
if err != nil {
|
||||
logger.Failuref("Kubernetes API call failed: %s", err.Error())
|
||||
return false
|
||||
}
|
||||
|
||||
v, err := semver.ParseTolerant(ver.String())
|
||||
v, err := version.ParseVersion(kv.String())
|
||||
if err != nil {
|
||||
logger.Failuref("Kubernetes version can't be determined")
|
||||
return false
|
||||
}
|
||||
|
||||
rng, _ := semver.ParseRange(version)
|
||||
if !rng(v) {
|
||||
logger.Failuref("Kubernetes version must be %s", version)
|
||||
c, _ := semver.NewConstraint(constraint)
|
||||
if !c.Check(v) {
|
||||
logger.Failuref("Kubernetes version %s < %s", v.Original(), constraint)
|
||||
return false
|
||||
}
|
||||
|
||||
logger.Successf("Kubernetes %s %s", v.String(), version)
|
||||
logger.Successf("Kubernetes %s %s", v.String(), constraint)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -172,18 +205,34 @@ func componentsCheck() bool {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeConfig, err := utils.KubeConfig(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
statusChecker, err := status.NewStatusChecker(kubeConfig, time.Second, rootArgs.timeout, logger)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
ok := true
|
||||
for _, deployment := range checkArgs.components {
|
||||
kubectlArgs := []string{"-n", rootArgs.namespace, "rollout", "status", "deployment", deployment, "--timeout", rootArgs.timeout.String()}
|
||||
if output, err := utils.ExecKubectlCommand(ctx, utils.ModeCapture, rootArgs.kubeconfig, rootArgs.kubecontext, kubectlArgs...); err != nil {
|
||||
logger.Failuref("%s: %s", deployment, strings.TrimSuffix(output, "\n"))
|
||||
ok = false
|
||||
} else {
|
||||
logger.Successf("%s is healthy", deployment)
|
||||
}
|
||||
kubectlArgs = []string{"-n", rootArgs.namespace, "get", "deployment", deployment, "-o", "jsonpath=\"{..image}\""}
|
||||
if output, err := utils.ExecKubectlCommand(ctx, utils.ModeCapture, rootArgs.kubeconfig, rootArgs.kubecontext, kubectlArgs...); err == nil {
|
||||
logger.Actionf(strings.TrimPrefix(strings.TrimSuffix(output, "\""), "\""))
|
||||
selector := client.MatchingLabels{"app.kubernetes.io/instance": rootArgs.namespace}
|
||||
var list v1.DeploymentList
|
||||
if err := kubeClient.List(ctx, &list, client.InNamespace(rootArgs.namespace), selector); err == nil {
|
||||
for _, d := range list.Items {
|
||||
if ref, err := buildComponentObjectRefs(d.Name); err == nil {
|
||||
if err := statusChecker.Assess(ref...); err != nil {
|
||||
ok = false
|
||||
}
|
||||
}
|
||||
for _, c := range d.Spec.Template.Spec.Containers {
|
||||
logger.Actionf(c.Image)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ok
|
||||
|
||||
37
cmd/flux/check_test.go
Normal file
37
cmd/flux/check_test.go
Normal file
@@ -0,0 +1,37 @@
|
||||
// +build e2e
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"k8s.io/apimachinery/pkg/version"
|
||||
)
|
||||
|
||||
func TestCheckPre(t *testing.T) {
|
||||
jsonOutput, err := utils.ExecKubectlCommand(context.TODO(), utils.ModeCapture, rootArgs.kubeconfig, rootArgs.kubecontext, "version", "--output", "json")
|
||||
if err != nil {
|
||||
t.Fatalf("Error running utils.ExecKubectlCommand: %v", err.Error())
|
||||
}
|
||||
|
||||
var versions map[string]version.Info
|
||||
if err := json.Unmarshal([]byte(jsonOutput), &versions); err != nil {
|
||||
t.Fatalf("Error unmarshalling: %v", err.Error())
|
||||
}
|
||||
|
||||
clientVersion := strings.TrimPrefix(versions["clientVersion"].GitVersion, "v")
|
||||
serverVersion := strings.TrimPrefix(versions["serverVersion"].GitVersion, "v")
|
||||
|
||||
cmd := cmdTestCase{
|
||||
args: "check --pre",
|
||||
assert: assertGoldenTemplateFile("testdata/check/check_pre.golden", map[string]string{
|
||||
"clientVersion": clientVersion,
|
||||
"serverVersion": serverVersion,
|
||||
}),
|
||||
}
|
||||
cmd.runTestCmd(t)
|
||||
}
|
||||
@@ -32,8 +32,7 @@ var completionBashCmd = &cobra.Command{
|
||||
To configure your bash shell to load completions for each session add to your bashrc
|
||||
|
||||
# ~/.bashrc or ~/.profile
|
||||
command -v flux >/dev/null && . <(flux completion bash)
|
||||
`,
|
||||
command -v flux >/dev/null && . <(flux completion bash)`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
rootCmd.GenBashCompletion(os.Stdout)
|
||||
},
|
||||
|
||||
@@ -25,16 +25,11 @@ import (
|
||||
var completionFishCmd = &cobra.Command{
|
||||
Use: "fish",
|
||||
Short: "Generates fish completion scripts",
|
||||
Example: `To load completion run
|
||||
Example: `To configure your fish shell to load completions for each session write this script to your completions dir:
|
||||
|
||||
. <(flux completion fish)
|
||||
flux completion fish > ~/.config/fish/completions/flux.fish
|
||||
|
||||
To configure your fish shell to load completions for each session write this script to your completions dir:
|
||||
|
||||
flux completion fish > ~/.config/fish/completions/flux
|
||||
|
||||
See http://fishshell.com/docs/current/index.html#completion-own for more details
|
||||
`,
|
||||
See http://fishshell.com/docs/current/index.html#completion-own for more details`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
rootCmd.GenFishCompletion(os.Stdout, true)
|
||||
},
|
||||
|
||||
@@ -39,8 +39,7 @@ flux completion >> flux-completion.ps1
|
||||
Linux:
|
||||
|
||||
cd "${XDG_CONFIG_HOME:-"$HOME/.config/"}/powershell/modules"
|
||||
flux completion >> flux-completions.ps1
|
||||
`,
|
||||
flux completion >> flux-completions.ps1`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
rootCmd.GenPowerShellCompletion(os.Stdout)
|
||||
},
|
||||
|
||||
@@ -40,8 +40,7 @@ echo "${fpath// /\n}" | grep -i completion
|
||||
flux completion zsh > _flux
|
||||
|
||||
mv _flux ~/.oh-my-zsh/completions # oh-my-zsh
|
||||
mv _flux ~/.zprezto/modules/completion/external/src/ # zprezto
|
||||
`,
|
||||
mv _flux ~/.zprezto/modules/completion/external/src/ # zprezto`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
rootCmd.GenZshCompletion(os.Stdout)
|
||||
},
|
||||
|
||||
@@ -43,8 +43,7 @@ var createAlertCmd = &cobra.Command{
|
||||
--event-severity info \
|
||||
--event-source Kustomization/flux-system \
|
||||
--provider-ref slack \
|
||||
flux-system
|
||||
`,
|
||||
flux-system`,
|
||||
RunE: createAlertCmdRun,
|
||||
}
|
||||
|
||||
@@ -59,7 +58,7 @@ var alertArgs alertFlags
|
||||
func init() {
|
||||
createAlertCmd.Flags().StringVar(&alertArgs.providerRef, "provider-ref", "", "reference to provider")
|
||||
createAlertCmd.Flags().StringVar(&alertArgs.eventSeverity, "event-severity", "", "severity of events to send alerts for")
|
||||
createAlertCmd.Flags().StringArrayVar(&alertArgs.eventSources, "event-source", []string{}, "sources that should generate alerts (<kind>/<name>)")
|
||||
createAlertCmd.Flags().StringSliceVar(&alertArgs.eventSources, "event-source", []string{}, "sources that should generate alerts (<kind>/<name>), also accepts comma-separated values")
|
||||
createCmd.AddCommand(createAlertCmd)
|
||||
}
|
||||
|
||||
@@ -75,14 +74,15 @@ func createAlertCmdRun(cmd *cobra.Command, args []string) error {
|
||||
|
||||
eventSources := []notificationv1.CrossNamespaceObjectReference{}
|
||||
for _, eventSource := range alertArgs.eventSources {
|
||||
kind, name := utils.ParseObjectKindName(eventSource)
|
||||
kind, name, namespace := utils.ParseObjectKindNameNamespace(eventSource)
|
||||
if kind == "" {
|
||||
return fmt.Errorf("invalid event source '%s', must be in format <kind>/<name>", eventSource)
|
||||
}
|
||||
|
||||
eventSources = append(eventSources, notificationv1.CrossNamespaceObjectReference{
|
||||
Kind: kind,
|
||||
Name: name,
|
||||
Kind: kind,
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -116,7 +116,7 @@ func createAlertCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
return exportAlert(alert)
|
||||
return printExport(exportAlert(&alert))
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
|
||||
@@ -49,8 +49,7 @@ var createAlertProviderCmd = &cobra.Command{
|
||||
flux create alert-provider github-podinfo \
|
||||
--type github \
|
||||
--address https://github.com/stefanprodan/podinfo \
|
||||
--secret-ref github-token
|
||||
`,
|
||||
--secret-ref github-token`,
|
||||
RunE: createAlertProviderCmdRun,
|
||||
}
|
||||
|
||||
@@ -113,7 +112,7 @@ func createAlertProviderCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
return exportAlertProvider(provider)
|
||||
return printExport(exportAlertProvider(&provider))
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
|
||||
@@ -18,12 +18,14 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
"github.com/fluxcd/pkg/runtime/transform"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
|
||||
@@ -62,11 +64,12 @@ var createHelmReleaseCmd = &cobra.Command{
|
||||
--source=Bucket/podinfo \
|
||||
--chart=./charts/podinfo
|
||||
|
||||
# Create a HelmRelease with values from a local YAML file
|
||||
# Create a HelmRelease with values from local YAML files
|
||||
flux create hr podinfo \
|
||||
--source=HelmRepository/podinfo \
|
||||
--chart=podinfo \
|
||||
--values=./my-values.yaml
|
||||
--values=./my-values1.yaml \
|
||||
--values=./my-values2.yaml
|
||||
|
||||
# Create a HelmRelease with values from a Kubernetes secret
|
||||
kubectl -n app create secret generic my-secret-values \
|
||||
@@ -84,17 +87,23 @@ var createHelmReleaseCmd = &cobra.Command{
|
||||
|
||||
# Create a HelmRelease targeting another namespace than the resource
|
||||
flux create hr podinfo \
|
||||
--target-namespace=default \
|
||||
--target-namespace=test \
|
||||
--create-target-namespace=true \
|
||||
--source=HelmRepository/podinfo \
|
||||
--chart=podinfo
|
||||
|
||||
# Create a HelmRelease using a source from a different namespace
|
||||
flux create hr podinfo \
|
||||
--namespace=default \
|
||||
--source=HelmRepository/podinfo.flux-system \
|
||||
--chart=podinfo
|
||||
|
||||
# Create a HelmRelease definition on disk without applying it on the cluster
|
||||
flux create hr podinfo \
|
||||
--source=HelmRepository/podinfo \
|
||||
--chart=podinfo \
|
||||
--values=./values.yaml \
|
||||
--export > podinfo-release.yaml
|
||||
`,
|
||||
--export > podinfo-release.yaml`,
|
||||
RunE: createHelmReleaseCmdRun,
|
||||
}
|
||||
|
||||
@@ -105,9 +114,11 @@ type helmReleaseFlags struct {
|
||||
chart string
|
||||
chartVersion string
|
||||
targetNamespace string
|
||||
valuesFile string
|
||||
createNamespace bool
|
||||
valuesFiles []string
|
||||
valuesFrom flags.HelmReleaseValuesFrom
|
||||
saName string
|
||||
crds flags.CRDsPolicy
|
||||
}
|
||||
|
||||
var helmReleaseArgs helmReleaseFlags
|
||||
@@ -117,11 +128,13 @@ func init() {
|
||||
createHelmReleaseCmd.Flags().Var(&helmReleaseArgs.source, "source", helmReleaseArgs.source.Description())
|
||||
createHelmReleaseCmd.Flags().StringVar(&helmReleaseArgs.chart, "chart", "", "Helm chart name or path")
|
||||
createHelmReleaseCmd.Flags().StringVar(&helmReleaseArgs.chartVersion, "chart-version", "", "Helm chart version, accepts a semver range (ignored for charts from GitRepository sources)")
|
||||
createHelmReleaseCmd.Flags().StringArrayVar(&helmReleaseArgs.dependsOn, "depends-on", nil, "HelmReleases that must be ready before this release can be installed, supported formats '<name>' and '<namespace>/<name>'")
|
||||
createHelmReleaseCmd.Flags().StringSliceVar(&helmReleaseArgs.dependsOn, "depends-on", nil, "HelmReleases that must be ready before this release can be installed, supported formats '<name>' and '<namespace>/<name>'")
|
||||
createHelmReleaseCmd.Flags().StringVar(&helmReleaseArgs.targetNamespace, "target-namespace", "", "namespace to install this release, defaults to the HelmRelease namespace")
|
||||
createHelmReleaseCmd.Flags().BoolVar(&helmReleaseArgs.createNamespace, "create-target-namespace", false, "create the target namespace if it does not exist")
|
||||
createHelmReleaseCmd.Flags().StringVar(&helmReleaseArgs.saName, "service-account", "", "the name of the service account to impersonate when reconciling this HelmRelease")
|
||||
createHelmReleaseCmd.Flags().StringVar(&helmReleaseArgs.valuesFile, "values", "", "local path to the values.yaml file")
|
||||
createHelmReleaseCmd.Flags().StringSliceVar(&helmReleaseArgs.valuesFiles, "values", nil, "local path to values.yaml files, also accepts comma-separated values")
|
||||
createHelmReleaseCmd.Flags().Var(&helmReleaseArgs.valuesFrom, "values-from", helmReleaseArgs.valuesFrom.Description())
|
||||
createHelmReleaseCmd.Flags().Var(&helmReleaseArgs.crds, "crds", helmReleaseArgs.crds.Description())
|
||||
createCmd.AddCommand(createHelmReleaseCmd)
|
||||
}
|
||||
|
||||
@@ -157,16 +170,21 @@ func createHelmReleaseCmdRun(cmd *cobra.Command, args []string) error {
|
||||
Duration: createArgs.interval,
|
||||
},
|
||||
TargetNamespace: helmReleaseArgs.targetNamespace,
|
||||
|
||||
Chart: helmv2.HelmChartTemplate{
|
||||
Spec: helmv2.HelmChartTemplateSpec{
|
||||
Chart: helmReleaseArgs.chart,
|
||||
Version: helmReleaseArgs.chartVersion,
|
||||
SourceRef: helmv2.CrossNamespaceObjectReference{
|
||||
Kind: helmReleaseArgs.source.Kind,
|
||||
Name: helmReleaseArgs.source.Name,
|
||||
Kind: helmReleaseArgs.source.Kind,
|
||||
Name: helmReleaseArgs.source.Name,
|
||||
Namespace: helmReleaseArgs.source.Namespace,
|
||||
},
|
||||
},
|
||||
},
|
||||
Install: &helmv2.Install{
|
||||
CreateNamespace: helmReleaseArgs.createNamespace,
|
||||
},
|
||||
Suspend: false,
|
||||
},
|
||||
}
|
||||
@@ -175,18 +193,38 @@ func createHelmReleaseCmdRun(cmd *cobra.Command, args []string) error {
|
||||
helmRelease.Spec.ServiceAccountName = helmReleaseArgs.saName
|
||||
}
|
||||
|
||||
if helmReleaseArgs.valuesFile != "" {
|
||||
data, err := ioutil.ReadFile(helmReleaseArgs.valuesFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading values from %s failed: %w", helmReleaseArgs.valuesFile, err)
|
||||
if helmReleaseArgs.crds != "" {
|
||||
helmRelease.Spec.Install.CRDs = helmv2.Create
|
||||
helmRelease.Spec.Upgrade = &helmv2.Upgrade{CRDs: helmv2.CRDsPolicy(helmReleaseArgs.crds.String())}
|
||||
}
|
||||
|
||||
if len(helmReleaseArgs.valuesFiles) > 0 {
|
||||
valuesMap := make(map[string]interface{})
|
||||
for _, v := range helmReleaseArgs.valuesFiles {
|
||||
data, err := os.ReadFile(v)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading values from %s failed: %w", v, err)
|
||||
}
|
||||
|
||||
jsonBytes, err := yaml.YAMLToJSON(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("converting values to JSON from %s failed: %w", v, err)
|
||||
}
|
||||
|
||||
jsonMap := make(map[string]interface{})
|
||||
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
|
||||
return fmt.Errorf("unmarshaling values from %s failed: %w", v, err)
|
||||
}
|
||||
|
||||
valuesMap = transform.MergeMaps(valuesMap, jsonMap)
|
||||
}
|
||||
|
||||
json, err := yaml.YAMLToJSON(data)
|
||||
jsonRaw, err := json.Marshal(valuesMap)
|
||||
if err != nil {
|
||||
return fmt.Errorf("converting values to JSON from %s failed: %w", helmReleaseArgs.valuesFile, err)
|
||||
return fmt.Errorf("marshaling values failed: %w", err)
|
||||
}
|
||||
|
||||
helmRelease.Spec.Values = &apiextensionsv1.JSON{Raw: json}
|
||||
helmRelease.Spec.Values = &apiextensionsv1.JSON{Raw: jsonRaw}
|
||||
}
|
||||
|
||||
if helmReleaseArgs.valuesFrom.String() != "" {
|
||||
@@ -197,7 +235,7 @@ func createHelmReleaseCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
return exportHelmRelease(helmRelease)
|
||||
return printExport(exportHelmRelease(&helmRelease))
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
|
||||
@@ -17,20 +17,17 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const createImageLong = `
|
||||
The create image sub-commands work with image automation objects; that is,
|
||||
const createImageLong = `The create image sub-commands work with image automation objects; that is,
|
||||
object controlling updates to git based on e.g., new container images
|
||||
being available.`
|
||||
|
||||
var createImageCmd = &cobra.Command{
|
||||
Use: "image",
|
||||
Short: "Create or update resources dealing with image automation",
|
||||
Long: strings.TrimSpace(createImageLong),
|
||||
Long: createImageLong,
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
@@ -18,17 +18,21 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp/syntax"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var createImagePolicyCmd = &cobra.Command{
|
||||
Use: "policy <name>",
|
||||
Use: "policy [name]",
|
||||
Short: "Create or update an ImagePolicy object",
|
||||
Long: `The create image policy command generates an ImagePolicy resource.
|
||||
An ImagePolicy object calculates a "latest image" given an image
|
||||
@@ -36,12 +40,27 @@ repository and a policy, e.g., semver.
|
||||
|
||||
The image that sorts highest according to the policy is recorded in
|
||||
the status of the object.`,
|
||||
Example: ` # Create an ImagePolicy to select the latest stable release
|
||||
flux create image policy podinfo \
|
||||
--image-ref=podinfo \
|
||||
--select-semver=">=1.0.0"
|
||||
|
||||
# Create an ImagePolicy to select the latest main branch build tagged as "${GIT_BRANCH}-${GIT_SHA:0:7}-$(date +%s)"
|
||||
flux create image policy podinfo \
|
||||
--image-ref=podinfo \
|
||||
--select-numeric=asc \
|
||||
--filter-regex='^main-[a-f0-9]+-(?P<ts>[0-9]+)' \
|
||||
--filter-extract='$ts'`,
|
||||
RunE: createImagePolicyRun}
|
||||
|
||||
type imagePolicyFlags struct {
|
||||
imageRef string
|
||||
semver string
|
||||
filterRegex string
|
||||
imageRef string
|
||||
semver string
|
||||
alpha string
|
||||
numeric string
|
||||
filterRegex string
|
||||
filterExtract string
|
||||
filterNumerical string
|
||||
}
|
||||
|
||||
var imagePolicyArgs = imagePolicyFlags{}
|
||||
@@ -49,8 +68,11 @@ var imagePolicyArgs = imagePolicyFlags{}
|
||||
func init() {
|
||||
flags := createImagePolicyCmd.Flags()
|
||||
flags.StringVar(&imagePolicyArgs.imageRef, "image-ref", "", "the name of an image repository object")
|
||||
flags.StringVar(&imagePolicyArgs.semver, "semver", "", "a semver range to apply to tags; e.g., '1.x'")
|
||||
flags.StringVar(&imagePolicyArgs.filterRegex, "filter-regex", "", " regular expression pattern used to filter the image tags")
|
||||
flags.StringVar(&imagePolicyArgs.semver, "select-semver", "", "a semver range to apply to tags; e.g., '1.x'")
|
||||
flags.StringVar(&imagePolicyArgs.alpha, "select-alpha", "", "use alphabetical sorting to select image; either \"asc\" meaning select the last, or \"desc\" meaning select the first")
|
||||
flags.StringVar(&imagePolicyArgs.numeric, "select-numeric", "", "use numeric sorting to select image; either \"asc\" meaning select the last, or \"desc\" meaning select the first")
|
||||
flags.StringVar(&imagePolicyArgs.filterRegex, "filter-regex", "", "regular expression pattern used to filter the image tags")
|
||||
flags.StringVar(&imagePolicyArgs.filterExtract, "filter-extract", "", "replacement pattern (using capture groups from --filter-regex) to use for sorting")
|
||||
|
||||
createImageCmd.AddCommand(createImagePolicyCmd)
|
||||
}
|
||||
@@ -90,18 +112,49 @@ func createImagePolicyRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
switch {
|
||||
case imagePolicyArgs.semver != "" && imagePolicyArgs.alpha != "":
|
||||
case imagePolicyArgs.semver != "" && imagePolicyArgs.numeric != "":
|
||||
case imagePolicyArgs.alpha != "" && imagePolicyArgs.numeric != "":
|
||||
return fmt.Errorf("only one of --select-semver, --select-alpha or --select-numeric can be specified")
|
||||
case imagePolicyArgs.semver != "":
|
||||
policy.Spec.Policy.SemVer = &imagev1.SemVerPolicy{
|
||||
Range: imagePolicyArgs.semver,
|
||||
}
|
||||
case imagePolicyArgs.alpha != "":
|
||||
if imagePolicyArgs.alpha != "desc" && imagePolicyArgs.alpha != "asc" {
|
||||
return fmt.Errorf("--select-alpha must be one of [\"asc\", \"desc\"]")
|
||||
}
|
||||
policy.Spec.Policy.Alphabetical = &imagev1.AlphabeticalPolicy{
|
||||
Order: imagePolicyArgs.alpha,
|
||||
}
|
||||
case imagePolicyArgs.numeric != "":
|
||||
if imagePolicyArgs.numeric != "desc" && imagePolicyArgs.numeric != "asc" {
|
||||
return fmt.Errorf("--select-numeric must be one of [\"asc\", \"desc\"]")
|
||||
}
|
||||
policy.Spec.Policy.Numerical = &imagev1.NumericalPolicy{
|
||||
Order: imagePolicyArgs.numeric,
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("a policy must be provided with --semver")
|
||||
return fmt.Errorf("a policy must be provided with either --select-semver or --select-alpha")
|
||||
}
|
||||
|
||||
if imagePolicyArgs.filterRegex != "" {
|
||||
exp, err := syntax.Parse(imagePolicyArgs.filterRegex, syntax.Perl)
|
||||
if err != nil {
|
||||
return fmt.Errorf("--filter-regex is an invalid regex pattern")
|
||||
}
|
||||
policy.Spec.FilterTags = &imagev1.TagFilter{
|
||||
Pattern: imagePolicyArgs.filterRegex,
|
||||
}
|
||||
|
||||
if imagePolicyArgs.filterExtract != "" {
|
||||
if err := validateExtractStr(imagePolicyArgs.filterExtract, exp.CapNames()); err != nil {
|
||||
return err
|
||||
}
|
||||
policy.Spec.FilterTags.Extract = imagePolicyArgs.filterExtract
|
||||
}
|
||||
} else if imagePolicyArgs.filterExtract != "" {
|
||||
return fmt.Errorf("cannot specify --filter-extract without specifying --filter-regex")
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
@@ -117,3 +170,94 @@ func createImagePolicyRun(cmd *cobra.Command, args []string) error {
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// Performs a dry-run of the extract function in Regexp to validate the template
|
||||
func validateExtractStr(template string, capNames []string) error {
|
||||
for len(template) > 0 {
|
||||
i := strings.Index(template, "$")
|
||||
if i < 0 {
|
||||
return nil
|
||||
}
|
||||
template = template[i:]
|
||||
if len(template) > 1 && template[1] == '$' {
|
||||
template = template[2:]
|
||||
continue
|
||||
}
|
||||
name, num, rest, ok := extract(template)
|
||||
if !ok {
|
||||
// Malformed extract string, assume user didn't want this
|
||||
template = template[1:]
|
||||
return fmt.Errorf("--filter-extract is malformed")
|
||||
}
|
||||
template = rest
|
||||
if num >= 0 {
|
||||
// we won't worry about numbers as we can't validate these
|
||||
continue
|
||||
} else {
|
||||
found := false
|
||||
for _, capName := range capNames {
|
||||
if name == capName {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return fmt.Errorf("capture group $%s used in --filter-extract not found in --filter-regex", name)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// extract method from the regexp package
|
||||
// returns the name or number of the value prepended by $
|
||||
func extract(str string) (name string, num int, rest string, ok bool) {
|
||||
if len(str) < 2 || str[0] != '$' {
|
||||
return
|
||||
}
|
||||
brace := false
|
||||
if str[1] == '{' {
|
||||
brace = true
|
||||
str = str[2:]
|
||||
} else {
|
||||
str = str[1:]
|
||||
}
|
||||
i := 0
|
||||
for i < len(str) {
|
||||
rune, size := utf8.DecodeRuneInString(str[i:])
|
||||
if !unicode.IsLetter(rune) && !unicode.IsDigit(rune) && rune != '_' {
|
||||
break
|
||||
}
|
||||
i += size
|
||||
}
|
||||
if i == 0 {
|
||||
// empty name is not okay
|
||||
return
|
||||
}
|
||||
name = str[:i]
|
||||
if brace {
|
||||
if i >= len(str) || str[i] != '}' {
|
||||
// missing closing brace
|
||||
return
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
// Parse number.
|
||||
num = 0
|
||||
for i := 0; i < len(name); i++ {
|
||||
if name[i] < '0' || '9' < name[i] || num >= 1e8 {
|
||||
num = -1
|
||||
break
|
||||
}
|
||||
num = num*10 + int(name[i]) - '0'
|
||||
}
|
||||
// Disallow leading zeros.
|
||||
if name[0] == '0' && len(name) > 1 {
|
||||
num = -1
|
||||
}
|
||||
|
||||
rest = str[i:]
|
||||
ok = true
|
||||
return
|
||||
}
|
||||
|
||||
@@ -26,21 +26,46 @@ import (
|
||||
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var createImageRepositoryCmd = &cobra.Command{
|
||||
Use: "repository <name>",
|
||||
Use: "repository [name]",
|
||||
Short: "Create or update an ImageRepository object",
|
||||
Long: `The create image repository command generates an ImageRepository resource.
|
||||
An ImageRepository object specifies an image repository to scan.`,
|
||||
Example: ` # Create an ImageRepository object to scan the alpine image repository:
|
||||
flux create image repository alpine-repo --image alpine --interval 20m
|
||||
|
||||
# Create an image repository that uses an image pull secret (assumed to
|
||||
# have been created already):
|
||||
flux create image repository myapp-repo \
|
||||
--secret-ref image-pull \
|
||||
--image ghcr.io/example.com/myapp --interval 5m
|
||||
|
||||
# Create a TLS secret for a local image registry using a self-signed
|
||||
# host certificate, and use it to scan an image. ca.pem is a file
|
||||
# containing the CA certificate used to sign the host certificate.
|
||||
flux create secret tls local-registry-cert --ca-file ./ca.pem
|
||||
flux create image repository app-repo \
|
||||
--cert-secret-ref local-registry-cert \
|
||||
--image local-registry:5000/app --interval 5m
|
||||
|
||||
# Create a TLS secret with a client certificate and key, and use it
|
||||
# to scan a private image registry.
|
||||
flux create secret tls client-cert \
|
||||
--cert-file client.crt --key-file client.key
|
||||
flux create image repository app-repo \
|
||||
--cert-secret-ref client-cert \
|
||||
--image registry.example.com/private/app --interval 5m`,
|
||||
RunE: createImageRepositoryRun,
|
||||
}
|
||||
|
||||
type imageRepoFlags struct {
|
||||
image string
|
||||
secretRef string
|
||||
timeout time.Duration
|
||||
image string
|
||||
secretRef string
|
||||
certSecretRef string
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
var imageRepoArgs = imageRepoFlags{}
|
||||
@@ -49,6 +74,7 @@ func init() {
|
||||
flags := createImageRepositoryCmd.Flags()
|
||||
flags.StringVar(&imageRepoArgs.image, "image", "", "the image repository to scan; e.g., library/alpine")
|
||||
flags.StringVar(&imageRepoArgs.secretRef, "secret-ref", "", "the name of a docker-registry secret to use for credentials")
|
||||
flags.StringVar(&imageRepoArgs.certSecretRef, "cert-ref", "", "the name of a secret to use for TLS certificates")
|
||||
// NB there is already a --timeout in the global flags, for
|
||||
// controlling timeout on operations while e.g., creating objects.
|
||||
flags.DurationVar(&imageRepoArgs.timeout, "scan-timeout", 0, "a timeout for scanning; this defaults to the interval if not set")
|
||||
@@ -94,6 +120,11 @@ func createImageRepositoryRun(cmd *cobra.Command, args []string) error {
|
||||
Name: imageRepoArgs.secretRef,
|
||||
}
|
||||
}
|
||||
if imageRepoArgs.certSecretRef != "" {
|
||||
repo.Spec.CertSecretRef = &meta.LocalObjectReference{
|
||||
Name: imageRepoArgs.certSecretRef,
|
||||
}
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
return printExport(exportImageRepository(&repo))
|
||||
|
||||
165
cmd/flux/create_image_update.go
Normal file
165
cmd/flux/create_image_update.go
Normal file
@@ -0,0 +1,165 @@
|
||||
/*
|
||||
Copyright 2020 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var createImageUpdateCmd = &cobra.Command{
|
||||
Use: "update [name]",
|
||||
Short: "Create or update an ImageUpdateAutomation object",
|
||||
Long: `The create image update command generates an ImageUpdateAutomation resource.
|
||||
An ImageUpdateAutomation object specifies an automated update to images
|
||||
mentioned in YAMLs in a git repository.`,
|
||||
Example: ` # Configure image updates for the main repository created by flux bootstrap
|
||||
flux create image update flux-system \
|
||||
--git-repo-ref=flux-system \
|
||||
--git-repo-path="./clusters/my-cluster" \
|
||||
--checkout-branch=main \
|
||||
--author-name=flux \
|
||||
--author-email=flux@example.com \
|
||||
--commit-template="{{range .Updated.Images}}{{println .}}{{end}}"
|
||||
|
||||
# Configure image updates to push changes to a different branch, if the branch doesn't exists it will be created
|
||||
flux create image update flux-system \
|
||||
--git-repo-ref=flux-system \
|
||||
--git-repo-path="./clusters/my-cluster" \
|
||||
--checkout-branch=main \
|
||||
--push-branch=image-updates \
|
||||
--author-name=flux \
|
||||
--author-email=flux@example.com \
|
||||
--commit-template="{{range .Updated.Images}}{{println .}}{{end}}"`,
|
||||
RunE: createImageUpdateRun,
|
||||
}
|
||||
|
||||
type imageUpdateFlags struct {
|
||||
gitRepoRef string
|
||||
gitRepoPath string
|
||||
checkoutBranch string
|
||||
pushBranch string
|
||||
commitTemplate string
|
||||
authorName string
|
||||
authorEmail string
|
||||
}
|
||||
|
||||
var imageUpdateArgs = imageUpdateFlags{}
|
||||
|
||||
func init() {
|
||||
flags := createImageUpdateCmd.Flags()
|
||||
flags.StringVar(&imageUpdateArgs.gitRepoRef, "git-repo-ref", "", "the name of a GitRepository resource with details of the upstream Git repository")
|
||||
flags.StringVar(&imageUpdateArgs.gitRepoPath, "git-repo-path", "", "path to the directory containing the manifests to be updated, defaults to the repository root")
|
||||
flags.StringVar(&imageUpdateArgs.checkoutBranch, "checkout-branch", "", "the branch to checkout")
|
||||
flags.StringVar(&imageUpdateArgs.pushBranch, "push-branch", "", "the branch to push commits to, defaults to the checkout branch if not specified")
|
||||
flags.StringVar(&imageUpdateArgs.commitTemplate, "commit-template", "", "a template for commit messages")
|
||||
flags.StringVar(&imageUpdateArgs.authorName, "author-name", "", "the name to use for commit author")
|
||||
flags.StringVar(&imageUpdateArgs.authorEmail, "author-email", "", "the email to use for commit author")
|
||||
|
||||
createImageCmd.AddCommand(createImageUpdateCmd)
|
||||
}
|
||||
|
||||
func createImageUpdateRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("ImageUpdateAutomation name is required")
|
||||
}
|
||||
objectName := args[0]
|
||||
|
||||
if imageUpdateArgs.gitRepoRef == "" {
|
||||
return fmt.Errorf("a reference to a GitRepository is required (--git-repo-ref)")
|
||||
}
|
||||
|
||||
if imageUpdateArgs.checkoutBranch == "" {
|
||||
return fmt.Errorf("the Git repository branch is required (--checkout-branch)")
|
||||
}
|
||||
|
||||
if imageUpdateArgs.authorName == "" {
|
||||
return fmt.Errorf("the author name is required (--author-name)")
|
||||
}
|
||||
|
||||
if imageUpdateArgs.authorEmail == "" {
|
||||
return fmt.Errorf("the author email is required (--author-email)")
|
||||
}
|
||||
|
||||
labels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var update = autov1.ImageUpdateAutomation{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: objectName,
|
||||
Namespace: rootArgs.namespace,
|
||||
Labels: labels,
|
||||
},
|
||||
Spec: autov1.ImageUpdateAutomationSpec{
|
||||
SourceRef: autov1.SourceReference{
|
||||
Kind: sourcev1.GitRepositoryKind,
|
||||
Name: imageUpdateArgs.gitRepoRef,
|
||||
},
|
||||
|
||||
GitSpec: &autov1.GitSpec{
|
||||
Checkout: &autov1.GitCheckoutSpec{
|
||||
Reference: sourcev1.GitRepositoryRef{
|
||||
Branch: imageUpdateArgs.checkoutBranch,
|
||||
},
|
||||
},
|
||||
Commit: autov1.CommitSpec{
|
||||
Author: autov1.CommitUser{
|
||||
Name: imageUpdateArgs.authorName,
|
||||
Email: imageUpdateArgs.authorEmail,
|
||||
},
|
||||
MessageTemplate: imageUpdateArgs.commitTemplate,
|
||||
},
|
||||
},
|
||||
Interval: metav1.Duration{
|
||||
Duration: createArgs.interval,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if imageUpdateArgs.pushBranch != "" {
|
||||
update.Spec.GitSpec.Push = &autov1.PushSpec{
|
||||
Branch: imageUpdateArgs.pushBranch,
|
||||
}
|
||||
}
|
||||
|
||||
if imageUpdateArgs.gitRepoPath != "" {
|
||||
update.Spec.Update = &autov1.UpdateStrategy{
|
||||
Path: imageUpdateArgs.gitRepoPath,
|
||||
Strategy: autov1.UpdateStrategySetters,
|
||||
}
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
return printExport(exportImageUpdate(&update))
|
||||
}
|
||||
|
||||
var existing autov1.ImageUpdateAutomation
|
||||
copyName(&existing, &update)
|
||||
err = imageUpdateAutomationType.upsertAndWait(imageUpdateAutomationAdapter{&existing}, func() error {
|
||||
existing.Spec = update.Spec
|
||||
existing.Labels = update.Labels
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
/*
|
||||
Copyright 2020 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var createImageUpdateCmd = &cobra.Command{
|
||||
Use: "update <name>",
|
||||
Short: "Create or update an ImageUpdateAutomation object",
|
||||
Long: `The create image update command generates an ImageUpdateAutomation resource.
|
||||
An ImageUpdateAutomation object specifies an automated update to images
|
||||
mentioned in YAMLs in a git repository.`,
|
||||
RunE: createImageUpdateRun,
|
||||
}
|
||||
|
||||
type imageUpdateFlags struct {
|
||||
// git checkout spec
|
||||
gitRepoRef string
|
||||
branch string
|
||||
// commit spec
|
||||
commitTemplate string
|
||||
authorName string
|
||||
authorEmail string
|
||||
}
|
||||
|
||||
var imageUpdateArgs = imageUpdateFlags{}
|
||||
|
||||
func init() {
|
||||
flags := createImageUpdateCmd.Flags()
|
||||
flags.StringVar(&imageUpdateArgs.gitRepoRef, "git-repo-ref", "", "the name of a GitRepository resource with details of the upstream git repository")
|
||||
flags.StringVar(&imageUpdateArgs.branch, "branch", "", "the branch to checkout and push commits to")
|
||||
flags.StringVar(&imageUpdateArgs.commitTemplate, "commit-template", "", "a template for commit messages")
|
||||
flags.StringVar(&imageUpdateArgs.authorName, "author-name", "", "the name to use for commit author")
|
||||
flags.StringVar(&imageUpdateArgs.authorEmail, "author-email", "", "the email to use for commit author")
|
||||
|
||||
createImageCmd.AddCommand(createImageUpdateCmd)
|
||||
}
|
||||
|
||||
func createImageUpdateRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("ImageUpdateAutomation name is required")
|
||||
}
|
||||
objectName := args[0]
|
||||
|
||||
if imageUpdateArgs.gitRepoRef == "" {
|
||||
return fmt.Errorf("a reference to a GitRepository is required (--git-repo-ref)")
|
||||
}
|
||||
|
||||
if imageUpdateArgs.branch == "" {
|
||||
return fmt.Errorf("the Git repoistory branch is required (--branch)")
|
||||
}
|
||||
|
||||
labels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var update = autov1.ImageUpdateAutomation{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: objectName,
|
||||
Namespace: rootArgs.namespace,
|
||||
Labels: labels,
|
||||
},
|
||||
Spec: autov1.ImageUpdateAutomationSpec{
|
||||
Checkout: autov1.GitCheckoutSpec{
|
||||
GitRepositoryRef: meta.LocalObjectReference{
|
||||
Name: imageUpdateArgs.gitRepoRef,
|
||||
},
|
||||
Branch: imageUpdateArgs.branch,
|
||||
},
|
||||
Interval: metav1.Duration{Duration: createArgs.interval},
|
||||
Commit: autov1.CommitSpec{
|
||||
AuthorName: imageUpdateArgs.authorName,
|
||||
AuthorEmail: imageUpdateArgs.authorEmail,
|
||||
MessageTemplate: imageUpdateArgs.commitTemplate,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
return printExport(exportImageUpdate(&update))
|
||||
}
|
||||
|
||||
var existing autov1.ImageUpdateAutomation
|
||||
copyName(&existing, &update)
|
||||
err = imageUpdateAutomationType.upsertAndWait(imageUpdateAutomationAdapter{&existing}, func() error {
|
||||
existing.Spec = update.Spec
|
||||
existing.Labels = update.Labels
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
@@ -45,7 +45,7 @@ var createKsCmd = &cobra.Command{
|
||||
Long: "The kustomization source create command generates a Kustomize resource for a given source.",
|
||||
Example: ` # Create a Kustomization resource from a source at a given path
|
||||
flux create kustomization contour \
|
||||
--source=contour \
|
||||
--source=GitRepository/contour \
|
||||
--path="./examples/contour/" \
|
||||
--prune=true \
|
||||
--interval=10m \
|
||||
@@ -57,7 +57,16 @@ var createKsCmd = &cobra.Command{
|
||||
# Create a Kustomization resource that depends on the previous one
|
||||
flux create kustomization webapp \
|
||||
--depends-on=contour \
|
||||
--source=webapp \
|
||||
--source=GitRepository/webapp \
|
||||
--path="./deploy/overlays/dev" \
|
||||
--prune=true \
|
||||
--interval=5m \
|
||||
--validation=client
|
||||
|
||||
# Create a Kustomization using a source from a different namespace
|
||||
flux create kustomization podinfo \
|
||||
--namespace=default \
|
||||
--source=GitRepository/podinfo.flux-system \
|
||||
--path="./deploy/overlays/dev" \
|
||||
--prune=true \
|
||||
--interval=5m \
|
||||
@@ -67,8 +76,7 @@ var createKsCmd = &cobra.Command{
|
||||
flux create kustomization secrets \
|
||||
--source=Bucket/secrets \
|
||||
--prune=true \
|
||||
--interval=5m
|
||||
`,
|
||||
--interval=5m`,
|
||||
RunE: createKsCmdRun,
|
||||
}
|
||||
|
||||
@@ -92,10 +100,10 @@ func init() {
|
||||
createKsCmd.Flags().Var(&kustomizationArgs.source, "source", kustomizationArgs.source.Description())
|
||||
createKsCmd.Flags().Var(&kustomizationArgs.path, "path", "path to the directory containing a kustomization.yaml file")
|
||||
createKsCmd.Flags().BoolVar(&kustomizationArgs.prune, "prune", false, "enable garbage collection")
|
||||
createKsCmd.Flags().StringArrayVar(&kustomizationArgs.healthCheck, "health-check", nil, "workload to be included in the health assessment, in the format '<kind>/<name>.<namespace>'")
|
||||
createKsCmd.Flags().StringSliceVar(&kustomizationArgs.healthCheck, "health-check", nil, "workload to be included in the health assessment, in the format '<kind>/<name>.<namespace>'")
|
||||
createKsCmd.Flags().DurationVar(&kustomizationArgs.healthTimeout, "health-check-timeout", 2*time.Minute, "timeout of health checking operations")
|
||||
createKsCmd.Flags().StringVar(&kustomizationArgs.validation, "validation", "", "validate the manifests before applying them on the cluster, can be 'client' or 'server'")
|
||||
createKsCmd.Flags().StringArrayVar(&kustomizationArgs.dependsOn, "depends-on", nil, "Kustomization that must be ready before this Kustomization can be applied, supported formats '<name>' and '<namespace>/<name>'")
|
||||
createKsCmd.Flags().StringSliceVar(&kustomizationArgs.dependsOn, "depends-on", nil, "Kustomization that must be ready before this Kustomization can be applied, supported formats '<name>' and '<namespace>/<name>', also accepts comma-separated values")
|
||||
createKsCmd.Flags().StringVar(&kustomizationArgs.saName, "service-account", "", "the name of the service account to impersonate when reconciling this Kustomization")
|
||||
createKsCmd.Flags().Var(&kustomizationArgs.decryptionProvider, "decryption-provider", kustomizationArgs.decryptionProvider.Description())
|
||||
createKsCmd.Flags().StringVar(&kustomizationArgs.decryptionSecret, "decryption-secret", "", "set the Kubernetes secret name that contains the OpenPGP private keys used for sops decryption")
|
||||
@@ -142,11 +150,12 @@ func createKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
Interval: metav1.Duration{
|
||||
Duration: createArgs.interval,
|
||||
},
|
||||
Path: kustomizationArgs.path.String(),
|
||||
Path: kustomizationArgs.path.ToSlash(),
|
||||
Prune: kustomizationArgs.prune,
|
||||
SourceRef: kustomizev1.CrossNamespaceSourceReference{
|
||||
Kind: kustomizationArgs.source.Kind,
|
||||
Name: kustomizationArgs.source.Name,
|
||||
Kind: kustomizationArgs.source.Kind,
|
||||
Name: kustomizationArgs.source.Name,
|
||||
Namespace: kustomizationArgs.source.Namespace,
|
||||
},
|
||||
Suspend: false,
|
||||
Validation: kustomizationArgs.validation,
|
||||
@@ -210,7 +219,7 @@ func createKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
return exportKs(kustomization)
|
||||
return printExport(exportKs(&kustomization))
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
|
||||
@@ -45,8 +45,7 @@ var createReceiverCmd = &cobra.Command{
|
||||
--event push \
|
||||
--secret-ref webhook-token \
|
||||
--resource GitRepository/webapp \
|
||||
--resource HelmRepository/webapp
|
||||
`,
|
||||
--resource HelmRepository/webapp`,
|
||||
RunE: createReceiverCmdRun,
|
||||
}
|
||||
|
||||
@@ -62,8 +61,8 @@ var receiverArgs receiverFlags
|
||||
func init() {
|
||||
createReceiverCmd.Flags().StringVar(&receiverArgs.receiverType, "type", "", "")
|
||||
createReceiverCmd.Flags().StringVar(&receiverArgs.secretRef, "secret-ref", "", "")
|
||||
createReceiverCmd.Flags().StringArrayVar(&receiverArgs.events, "event", []string{}, "")
|
||||
createReceiverCmd.Flags().StringArrayVar(&receiverArgs.resources, "resource", []string{}, "")
|
||||
createReceiverCmd.Flags().StringSliceVar(&receiverArgs.events, "event", []string{}, "also accepts comma-separated values")
|
||||
createReceiverCmd.Flags().StringSliceVar(&receiverArgs.resources, "resource", []string{}, "also accepts comma-separated values")
|
||||
createCmd.AddCommand(createReceiverCmd)
|
||||
}
|
||||
|
||||
@@ -125,7 +124,7 @@ func createReceiverCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
return exportReceiver(receiver)
|
||||
return printExport(exportReceiver(&receiver))
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
|
||||
@@ -18,15 +18,12 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
var createSecretCmd = &cobra.Command{
|
||||
@@ -39,23 +36,6 @@ func init() {
|
||||
createCmd.AddCommand(createSecretCmd)
|
||||
}
|
||||
|
||||
func makeSecret(name string) (corev1.Secret, error) {
|
||||
secretLabels, err := parseLabels()
|
||||
if err != nil {
|
||||
return corev1.Secret{}, err
|
||||
}
|
||||
|
||||
return corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: rootArgs.namespace,
|
||||
Labels: secretLabels,
|
||||
},
|
||||
StringData: map[string]string{},
|
||||
Data: nil,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func upsertSecret(ctx context.Context, kubeClient client.Client, secret corev1.Secret) error {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: secret.GetNamespace(),
|
||||
@@ -81,19 +61,3 @@ func upsertSecret(ctx context.Context, kubeClient client.Client, secret corev1.S
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportSecret(secret corev1.Secret) error {
|
||||
secret.TypeMeta = metav1.TypeMeta{
|
||||
APIVersion: "v1",
|
||||
Kind: "Secret",
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(secret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -21,20 +21,20 @@ import (
|
||||
"crypto/elliptic"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/ssh"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/sourcesecret"
|
||||
)
|
||||
|
||||
var createSecretGitCmd = &cobra.Command{
|
||||
Use: "git [name]",
|
||||
Short: "Create or update a Kubernetes secret for Git authentication",
|
||||
Long: `
|
||||
The create secret git command generates a Kubernetes secret with Git credentials.
|
||||
Long: `The create secret git command generates a Kubernetes secret with Git credentials.
|
||||
For Git over SSH, the host and SSH keys are automatically generated and stored in the secret.
|
||||
For Git over HTTP/S, the provided basic authentication credentials are stored in the secret.`,
|
||||
Example: ` # Create a Git SSH authentication secret using an ECDSA P-521 curve public key
|
||||
@@ -44,38 +44,48 @@ For Git over HTTP/S, the provided basic authentication credentials are stored in
|
||||
--ssh-key-algorithm=ecdsa \
|
||||
--ssh-ecdsa-curve=p521
|
||||
|
||||
# Create a Git SSH authentication secret with a passwordless private key from file
|
||||
# The public SSH host key will still be gathered from the host
|
||||
flux create secret git podinfo-auth \
|
||||
--url=ssh://git@github.com/stefanprodan/podinfo \
|
||||
--private-key-file=./private.key
|
||||
|
||||
# Create a Git SSH authentication secret with a passworded private key from file
|
||||
# The public SSH host key will still be gathered from the host
|
||||
flux create secret git podinfo-auth \
|
||||
--url=ssh://git@github.com/stefanprodan/podinfo \
|
||||
--private-key-file=./private.key \
|
||||
--password=<password>
|
||||
|
||||
# Create a secret for a Git repository using basic authentication
|
||||
flux create secret git podinfo-auth \
|
||||
--url=https://github.com/stefanprodan/podinfo \
|
||||
--username=username \
|
||||
--password=password
|
||||
|
||||
# Create a Git SSH secret on disk and print the deploy key
|
||||
# Create a Git SSH secret on disk
|
||||
flux create secret git podinfo-auth \
|
||||
--url=ssh://git@github.com/stefanprodan/podinfo \
|
||||
--export > podinfo-auth.yaml
|
||||
|
||||
yq read podinfo-auth.yaml 'data."identity.pub"' | base64 --decode
|
||||
|
||||
# Create a Git SSH secret on disk and encrypt it with Mozilla SOPS
|
||||
flux create secret git podinfo-auth \
|
||||
--namespace=apps \
|
||||
--url=ssh://git@github.com/stefanprodan/podinfo \
|
||||
--export > podinfo-auth.yaml
|
||||
# Print the deploy key
|
||||
yq eval '.stringData."identity.pub"' podinfo-auth.yaml
|
||||
|
||||
# Encrypt the secret on disk with Mozilla SOPS
|
||||
sops --encrypt --encrypted-regex '^(data|stringData)$' \
|
||||
--in-place podinfo-auth.yaml
|
||||
`,
|
||||
--in-place podinfo-auth.yaml`,
|
||||
RunE: createSecretGitCmdRun,
|
||||
}
|
||||
|
||||
type secretGitFlags struct {
|
||||
url string
|
||||
username string
|
||||
password string
|
||||
keyAlgorithm flags.PublicKeyAlgorithm
|
||||
rsaBits flags.RSAKeyBits
|
||||
ecdsaCurve flags.ECDSACurve
|
||||
url string
|
||||
username string
|
||||
password string
|
||||
keyAlgorithm flags.PublicKeyAlgorithm
|
||||
rsaBits flags.RSAKeyBits
|
||||
ecdsaCurve flags.ECDSACurve
|
||||
caFile string
|
||||
privateKeyFile string
|
||||
}
|
||||
|
||||
var secretGitArgs = NewSecretGitFlags()
|
||||
@@ -87,13 +97,15 @@ func init() {
|
||||
createSecretGitCmd.Flags().Var(&secretGitArgs.keyAlgorithm, "ssh-key-algorithm", secretGitArgs.keyAlgorithm.Description())
|
||||
createSecretGitCmd.Flags().Var(&secretGitArgs.rsaBits, "ssh-rsa-bits", secretGitArgs.rsaBits.Description())
|
||||
createSecretGitCmd.Flags().Var(&secretGitArgs.ecdsaCurve, "ssh-ecdsa-curve", secretGitArgs.ecdsaCurve.Description())
|
||||
createSecretGitCmd.Flags().StringVar(&secretGitArgs.caFile, "ca-file", "", "path to TLS CA file used for validating self-signed certificates")
|
||||
createSecretGitCmd.Flags().StringVar(&secretGitArgs.privateKeyFile, "private-key-file", "", "path to a passwordless private key file used for authenticating to the Git SSH server")
|
||||
|
||||
createSecretCmd.AddCommand(createSecretGitCmd)
|
||||
}
|
||||
|
||||
func NewSecretGitFlags() secretGitFlags {
|
||||
return secretGitFlags{
|
||||
keyAlgorithm: "rsa",
|
||||
keyAlgorithm: flags.PublicKeyAlgorithm(sourcesecret.RSAPrivateKeyAlgorithm),
|
||||
rsaBits: 2048,
|
||||
ecdsaCurve: flags.ECDSACurve{Curve: elliptic.P384()},
|
||||
}
|
||||
@@ -104,11 +116,6 @@ func createSecretGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return fmt.Errorf("secret name is required")
|
||||
}
|
||||
name := args[0]
|
||||
secret, err := makeSecret(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if secretGitArgs.url == "" {
|
||||
return fmt.Errorf("url is required")
|
||||
}
|
||||
@@ -118,88 +125,65 @@ func createSecretGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return fmt.Errorf("git URL parse failed: %w", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
labels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
opts := sourcesecret.Options{
|
||||
Name: name,
|
||||
Namespace: rootArgs.namespace,
|
||||
Labels: labels,
|
||||
ManifestFile: sourcesecret.MakeDefaultOptions().ManifestFile,
|
||||
}
|
||||
switch u.Scheme {
|
||||
case "ssh":
|
||||
pair, err := generateKeyPair(ctx, secretGitArgs.keyAlgorithm, secretGitArgs.rsaBits, secretGitArgs.ecdsaCurve)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
hostKey, err := scanHostKey(ctx, u)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
secret.StringData = map[string]string{
|
||||
"identity": string(pair.PrivateKey),
|
||||
"identity.pub": string(pair.PublicKey),
|
||||
"known_hosts": string(hostKey),
|
||||
}
|
||||
|
||||
if !createArgs.export {
|
||||
logger.Generatef("deploy key: %s", string(pair.PublicKey))
|
||||
}
|
||||
opts.SSHHostname = u.Host
|
||||
opts.PrivateKeyPath = secretGitArgs.privateKeyFile
|
||||
opts.PrivateKeyAlgorithm = sourcesecret.PrivateKeyAlgorithm(secretGitArgs.keyAlgorithm)
|
||||
opts.RSAKeyBits = int(secretGitArgs.rsaBits)
|
||||
opts.ECDSACurve = secretGitArgs.ecdsaCurve.Curve
|
||||
opts.Password = secretGitArgs.password
|
||||
case "http", "https":
|
||||
if secretGitArgs.username == "" || secretGitArgs.password == "" {
|
||||
return fmt.Errorf("for Git over HTTP/S the username and password are required")
|
||||
}
|
||||
|
||||
// TODO: add cert data when it's implemented in source-controller
|
||||
secret.StringData = map[string]string{
|
||||
"username": secretGitArgs.username,
|
||||
"password": secretGitArgs.password,
|
||||
}
|
||||
opts.Username = secretGitArgs.username
|
||||
opts.Password = secretGitArgs.password
|
||||
opts.CAFilePath = secretGitArgs.caFile
|
||||
default:
|
||||
return fmt.Errorf("git URL scheme '%s' not supported, can be: ssh, http and https", u.Scheme)
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
return exportSecret(secret)
|
||||
secret, err := sourcesecret.Generate(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
fmt.Println(secret.Content)
|
||||
return nil
|
||||
}
|
||||
|
||||
var s corev1.Secret
|
||||
if err := yaml.Unmarshal([]byte(secret.Content), &s); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if ppk, ok := s.StringData[sourcesecret.PublicKeySecretKey]; ok {
|
||||
logger.Generatef("deploy key: %s", ppk)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := upsertSecret(ctx, kubeClient, secret); err != nil {
|
||||
if err := upsertSecret(ctx, kubeClient, s); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Actionf("secret '%s' created in '%s' namespace", name, rootArgs.namespace)
|
||||
logger.Actionf("git secret '%s' created in '%s' namespace", name, rootArgs.namespace)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateKeyPair(ctx context.Context, alg flags.PublicKeyAlgorithm, rsa flags.RSAKeyBits, ecdsa flags.ECDSACurve) (*ssh.KeyPair, error) {
|
||||
var keyGen ssh.KeyPairGenerator
|
||||
switch algorithm := alg.String(); algorithm {
|
||||
case "rsa":
|
||||
keyGen = ssh.NewRSAGenerator(int(rsa))
|
||||
case "ecdsa":
|
||||
keyGen = ssh.NewECDSAGenerator(ecdsa.Curve)
|
||||
case "ed25519":
|
||||
keyGen = ssh.NewEd25519Generator()
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported public key algorithm: %s", algorithm)
|
||||
}
|
||||
pair, err := keyGen.Generate()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("key pair generation failed, error: %w", err)
|
||||
}
|
||||
return pair, nil
|
||||
}
|
||||
|
||||
func scanHostKey(ctx context.Context, url *url.URL) ([]byte, error) {
|
||||
host := url.Host
|
||||
if url.Port() == "" {
|
||||
host = host + ":22"
|
||||
}
|
||||
hostKey, err := ssh.ScanHostKey(host, 30*time.Second)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SSH key scan for host %s failed, error: %w", host, err)
|
||||
}
|
||||
return hostKey, nil
|
||||
}
|
||||
|
||||
@@ -21,17 +21,18 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/sourcesecret"
|
||||
)
|
||||
|
||||
var createSecretHelmCmd = &cobra.Command{
|
||||
Use: "helm [name]",
|
||||
Short: "Create or update a Kubernetes secret for Helm repository authentication",
|
||||
Long: `
|
||||
The create secret helm command generates a Kubernetes secret with basic authentication credentials.`,
|
||||
Example: ` # Create a Helm authentication secret on disk and encrypt it with Mozilla SOPS
|
||||
|
||||
Long: `The create secret helm command generates a Kubernetes secret with basic authentication credentials.`,
|
||||
Example: ` # Create a Helm authentication secret on disk and encrypt it with Mozilla SOPS
|
||||
flux create secret helm repo-auth \
|
||||
--namespace=my-namespace \
|
||||
--username=my-username \
|
||||
@@ -41,14 +42,13 @@ The create secret helm command generates a Kubernetes secret with basic authenti
|
||||
sops --encrypt --encrypted-regex '^(data|stringData)$' \
|
||||
--in-place repo-auth.yaml
|
||||
|
||||
# Create an authentication secret using a custom TLS cert
|
||||
# Create a Helm authentication secret using a custom TLS cert
|
||||
flux create secret helm repo-auth \
|
||||
--username=username \
|
||||
--password=password \
|
||||
--cert-file=./cert.crt \
|
||||
--key-file=./key.crt \
|
||||
--ca-file=./ca.crt
|
||||
`,
|
||||
--ca-file=./ca.crt`,
|
||||
RunE: createSecretHelmCmdRun,
|
||||
}
|
||||
|
||||
@@ -72,36 +72,46 @@ func createSecretHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return fmt.Errorf("secret name is required")
|
||||
}
|
||||
name := args[0]
|
||||
secret, err := makeSecret(name)
|
||||
|
||||
labels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if secretHelmArgs.username != "" && secretHelmArgs.password != "" {
|
||||
secret.StringData["username"] = secretHelmArgs.username
|
||||
secret.StringData["password"] = secretHelmArgs.password
|
||||
opts := sourcesecret.Options{
|
||||
Name: name,
|
||||
Namespace: rootArgs.namespace,
|
||||
Labels: labels,
|
||||
Username: secretHelmArgs.username,
|
||||
Password: secretHelmArgs.password,
|
||||
CAFilePath: secretHelmArgs.caFile,
|
||||
CertFilePath: secretHelmArgs.certFile,
|
||||
KeyFilePath: secretHelmArgs.keyFile,
|
||||
}
|
||||
|
||||
if err = populateSecretTLS(&secret, secretHelmArgs.secretTLSFlags); err != nil {
|
||||
secret, err := sourcesecret.Generate(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
return exportSecret(secret)
|
||||
fmt.Println(secret.Content)
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := upsertSecret(ctx, kubeClient, secret); err != nil {
|
||||
var s corev1.Secret
|
||||
if err := yaml.Unmarshal([]byte(secret.Content), &s); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := upsertSecret(ctx, kubeClient, s); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Actionf("secret '%s' created in '%s' namespace", name, rootArgs.namespace)
|
||||
|
||||
logger.Actionf("helm secret '%s' created in '%s' namespace", name, rootArgs.namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -19,22 +19,21 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/sourcesecret"
|
||||
)
|
||||
|
||||
var createSecretTLSCmd = &cobra.Command{
|
||||
Use: "tls [name]",
|
||||
Short: "Create or update a Kubernetes secret with TLS certificates",
|
||||
Long: `
|
||||
The create secret tls command generates a Kubernetes secret with certificates for use with TLS.`,
|
||||
Example: `
|
||||
# Create a TLS secret on disk and encrypt it with Mozilla SOPS.
|
||||
Long: `The create secret tls command generates a Kubernetes secret with certificates for use with TLS.`,
|
||||
Example: ` # Create a TLS secret on disk and encrypt it with Mozilla SOPS.
|
||||
# Files are expected to be PEM-encoded.
|
||||
flux create secret tls certs \
|
||||
--namespace=my-namespace \
|
||||
@@ -43,8 +42,7 @@ The create secret tls command generates a Kubernetes secret with certificates fo
|
||||
--export > certs.yaml
|
||||
|
||||
sops --encrypt --encrypted-regex '^(data|stringData)$' \
|
||||
--in-place certs.yaml
|
||||
`,
|
||||
--in-place certs.yaml`,
|
||||
RunE: createSecretTLSCmdRun,
|
||||
}
|
||||
|
||||
@@ -68,61 +66,49 @@ func init() {
|
||||
createSecretCmd.AddCommand(createSecretTLSCmd)
|
||||
}
|
||||
|
||||
func populateSecretTLS(secret *corev1.Secret, args secretTLSFlags) error {
|
||||
if args.certFile != "" && args.keyFile != "" {
|
||||
cert, err := ioutil.ReadFile(args.certFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read repository cert file '%s': %w", args.certFile, err)
|
||||
}
|
||||
secret.StringData["certFile"] = string(cert)
|
||||
|
||||
key, err := ioutil.ReadFile(args.keyFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read repository key file '%s': %w", args.keyFile, err)
|
||||
}
|
||||
secret.StringData["keyFile"] = string(key)
|
||||
}
|
||||
|
||||
if args.caFile != "" {
|
||||
ca, err := ioutil.ReadFile(args.caFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read repository CA file '%s': %w", args.caFile, err)
|
||||
}
|
||||
secret.StringData["caFile"] = string(ca)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func createSecretTLSCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("secret name is required")
|
||||
}
|
||||
name := args[0]
|
||||
secret, err := makeSecret(name)
|
||||
|
||||
labels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = populateSecretTLS(&secret, secretTLSArgs); err != nil {
|
||||
opts := sourcesecret.Options{
|
||||
Name: name,
|
||||
Namespace: rootArgs.namespace,
|
||||
Labels: labels,
|
||||
CAFilePath: secretTLSArgs.caFile,
|
||||
CertFilePath: secretTLSArgs.certFile,
|
||||
KeyFilePath: secretTLSArgs.keyFile,
|
||||
}
|
||||
secret, err := sourcesecret.Generate(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
return exportSecret(secret)
|
||||
fmt.Println(secret.Content)
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := upsertSecret(ctx, kubeClient, secret); err != nil {
|
||||
var s corev1.Secret
|
||||
if err := yaml.Unmarshal([]byte(secret.Content), &s); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := upsertSecret(ctx, kubeClient, s); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Actionf("secret '%s' created in '%s' namespace", name, rootArgs.namespace)
|
||||
|
||||
logger.Actionf("tls secret '%s' created in '%s' namespace", name, rootArgs.namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
@@ -40,10 +39,9 @@ import (
|
||||
var createSourceBucketCmd = &cobra.Command{
|
||||
Use: "bucket [name]",
|
||||
Short: "Create or update a Bucket source",
|
||||
Long: `
|
||||
The create source bucket command generates a Bucket resource and waits for it to be downloaded.
|
||||
Long: `The create source bucket command generates a Bucket resource and waits for it to be downloaded.
|
||||
For Buckets with static authentication, the credentials are stored in a Kubernetes secret.`,
|
||||
Example: ` # Create a source from a Buckets using static authentication
|
||||
Example: ` # Create a source for a Bucket using static authentication
|
||||
flux create source bucket podinfo \
|
||||
--bucket-name=podinfo \
|
||||
--endpoint=minio.minio.svc.cluster.local:9000 \
|
||||
@@ -52,14 +50,13 @@ For Buckets with static authentication, the credentials are stored in a Kubernet
|
||||
--secret-key=mysecretkey \
|
||||
--interval=10m
|
||||
|
||||
# Create a source from an Amazon S3 Bucket using IAM authentication
|
||||
# Create a source for an Amazon S3 Bucket using IAM authentication
|
||||
flux create source bucket podinfo \
|
||||
--bucket-name=podinfo \
|
||||
--provider=aws \
|
||||
--endpoint=s3.amazonaws.com \
|
||||
--region=us-east-1 \
|
||||
--interval=10m
|
||||
`,
|
||||
--interval=10m`,
|
||||
RunE: createSourceBucketCmdRun,
|
||||
}
|
||||
|
||||
@@ -114,7 +111,7 @@ func createSourceBucketCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
tmpDir, err := ioutil.TempDir("", name)
|
||||
tmpDir, err := os.MkdirTemp("", name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -144,7 +141,7 @@ func createSourceBucketCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
return exportBucket(*bucket)
|
||||
return printExport(exportBucket(bucket))
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
|
||||
@@ -20,10 +20,11 @@ import (
|
||||
"context"
|
||||
"crypto/elliptic"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"os"
|
||||
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"github.com/manifoldco/promptui"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
@@ -33,34 +34,34 @@ import (
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/sourcesecret"
|
||||
)
|
||||
|
||||
type SourceGitFlags struct {
|
||||
GitURL string
|
||||
GitBranch string
|
||||
GitTag string
|
||||
GitSemver string
|
||||
GitUsername string
|
||||
GitPassword string
|
||||
|
||||
GitKeyAlgorithm flags.PublicKeyAlgorithm
|
||||
GitRSABits flags.RSAKeyBits
|
||||
GitECDSACurve flags.ECDSACurve
|
||||
GitSecretRef string
|
||||
GitImplementation flags.GitImplementation
|
||||
type sourceGitFlags struct {
|
||||
url string
|
||||
branch string
|
||||
tag string
|
||||
semver string
|
||||
username string
|
||||
password string
|
||||
keyAlgorithm flags.PublicKeyAlgorithm
|
||||
keyRSABits flags.RSAKeyBits
|
||||
keyECDSACurve flags.ECDSACurve
|
||||
secretRef string
|
||||
gitImplementation flags.GitImplementation
|
||||
caFile string
|
||||
privateKeyFile string
|
||||
recurseSubmodules bool
|
||||
}
|
||||
|
||||
var createSourceGitCmd = &cobra.Command{
|
||||
Use: "git [name]",
|
||||
Short: "Create or update a GitRepository source",
|
||||
Long: `
|
||||
The create source git command generates a GitRepository resource and waits for it to sync.
|
||||
Long: `The create source git command generates a GitRepository resource and waits for it to sync.
|
||||
For Git over SSH, host and SSH keys are automatically generated and stored in a Kubernetes secret.
|
||||
For private Git repositories, the basic authentication credentials are stored in a Kubernetes secret.`,
|
||||
Example: ` # Create a source from a public Git repository master branch
|
||||
@@ -68,7 +69,7 @@ For private Git repositories, the basic authentication credentials are stored in
|
||||
--url=https://github.com/stefanprodan/podinfo \
|
||||
--branch=master
|
||||
|
||||
# Create a source from a Git repository pinned to specific git tag
|
||||
# Create a source for a Git repository pinned to specific git tag
|
||||
flux create source git podinfo \
|
||||
--url=https://github.com/stefanprodan/podinfo \
|
||||
--tag="3.2.3"
|
||||
@@ -78,12 +79,12 @@ For private Git repositories, the basic authentication credentials are stored in
|
||||
--url=https://github.com/stefanprodan/podinfo \
|
||||
--tag-semver=">=3.2.0 <3.3.0"
|
||||
|
||||
# Create a source from a Git repository using SSH authentication
|
||||
# Create a source for a Git repository using SSH authentication
|
||||
flux create source git podinfo \
|
||||
--url=ssh://git@github.com/stefanprodan/podinfo \
|
||||
--branch=master
|
||||
|
||||
# Create a source from a Git repository using SSH authentication and an
|
||||
# Create a source for a Git repository using SSH authentication and an
|
||||
# ECDSA P-521 curve public key
|
||||
flux create source git podinfo \
|
||||
--url=ssh://git@github.com/stefanprodan/podinfo \
|
||||
@@ -91,38 +92,58 @@ For private Git repositories, the basic authentication credentials are stored in
|
||||
--ssh-key-algorithm=ecdsa \
|
||||
--ssh-ecdsa-curve=p521
|
||||
|
||||
# Create a source from a Git repository using basic authentication
|
||||
# Create a source for a Git repository using SSH authentication and a
|
||||
# passwordless private key from file
|
||||
# The public SSH host key will still be gathered from the host
|
||||
flux create source git podinfo \
|
||||
--url=ssh://git@github.com/stefanprodan/podinfo \
|
||||
--branch=master \
|
||||
--private-key-file=./private.key
|
||||
|
||||
# Create a source for a Git repository using SSH authentication and a
|
||||
# private key with a password from file
|
||||
# The public SSH host key will still be gathered from the host
|
||||
flux create source git podinfo \
|
||||
--url=ssh://git@github.com/stefanprodan/podinfo \
|
||||
--branch=master \
|
||||
--private-key-file=./private.key \
|
||||
--password=<password>
|
||||
|
||||
# Create a source for a Git repository using basic authentication
|
||||
flux create source git podinfo \
|
||||
--url=https://github.com/stefanprodan/podinfo \
|
||||
--username=username \
|
||||
--password=password
|
||||
`,
|
||||
--password=password`,
|
||||
RunE: createSourceGitCmdRun,
|
||||
}
|
||||
|
||||
var sourceArgs = NewSourceGitFlags()
|
||||
var sourceGitArgs = newSourceGitFlags()
|
||||
|
||||
func init() {
|
||||
createSourceGitCmd.Flags().StringVar(&sourceArgs.GitURL, "url", "", "git address, e.g. ssh://git@host/org/repository")
|
||||
createSourceGitCmd.Flags().StringVar(&sourceArgs.GitBranch, "branch", "master", "git branch")
|
||||
createSourceGitCmd.Flags().StringVar(&sourceArgs.GitTag, "tag", "", "git tag")
|
||||
createSourceGitCmd.Flags().StringVar(&sourceArgs.GitSemver, "tag-semver", "", "git tag semver range")
|
||||
createSourceGitCmd.Flags().StringVarP(&sourceArgs.GitUsername, "username", "u", "", "basic authentication username")
|
||||
createSourceGitCmd.Flags().StringVarP(&sourceArgs.GitPassword, "password", "p", "", "basic authentication password")
|
||||
createSourceGitCmd.Flags().Var(&sourceArgs.GitKeyAlgorithm, "ssh-key-algorithm", sourceArgs.GitKeyAlgorithm.Description())
|
||||
createSourceGitCmd.Flags().Var(&sourceArgs.GitRSABits, "ssh-rsa-bits", sourceArgs.GitRSABits.Description())
|
||||
createSourceGitCmd.Flags().Var(&sourceArgs.GitECDSACurve, "ssh-ecdsa-curve", sourceArgs.GitECDSACurve.Description())
|
||||
createSourceGitCmd.Flags().StringVarP(&sourceArgs.GitSecretRef, "secret-ref", "", "", "the name of an existing secret containing SSH or basic credentials")
|
||||
createSourceGitCmd.Flags().Var(&sourceArgs.GitImplementation, "git-implementation", sourceArgs.GitImplementation.Description())
|
||||
createSourceGitCmd.Flags().StringVar(&sourceGitArgs.url, "url", "", "git address, e.g. ssh://git@host/org/repository")
|
||||
createSourceGitCmd.Flags().StringVar(&sourceGitArgs.branch, "branch", "", "git branch")
|
||||
createSourceGitCmd.Flags().StringVar(&sourceGitArgs.tag, "tag", "", "git tag")
|
||||
createSourceGitCmd.Flags().StringVar(&sourceGitArgs.semver, "tag-semver", "", "git tag semver range")
|
||||
createSourceGitCmd.Flags().StringVarP(&sourceGitArgs.username, "username", "u", "", "basic authentication username")
|
||||
createSourceGitCmd.Flags().StringVarP(&sourceGitArgs.password, "password", "p", "", "basic authentication password")
|
||||
createSourceGitCmd.Flags().Var(&sourceGitArgs.keyAlgorithm, "ssh-key-algorithm", sourceGitArgs.keyAlgorithm.Description())
|
||||
createSourceGitCmd.Flags().Var(&sourceGitArgs.keyRSABits, "ssh-rsa-bits", sourceGitArgs.keyRSABits.Description())
|
||||
createSourceGitCmd.Flags().Var(&sourceGitArgs.keyECDSACurve, "ssh-ecdsa-curve", sourceGitArgs.keyECDSACurve.Description())
|
||||
createSourceGitCmd.Flags().StringVar(&sourceGitArgs.secretRef, "secret-ref", "", "the name of an existing secret containing SSH or basic credentials")
|
||||
createSourceGitCmd.Flags().Var(&sourceGitArgs.gitImplementation, "git-implementation", sourceGitArgs.gitImplementation.Description())
|
||||
createSourceGitCmd.Flags().StringVar(&sourceGitArgs.caFile, "ca-file", "", "path to TLS CA file used for validating self-signed certificates")
|
||||
createSourceGitCmd.Flags().StringVar(&sourceGitArgs.privateKeyFile, "private-key-file", "", "path to a passwordless private key file used for authenticating to the Git SSH server")
|
||||
createSourceGitCmd.Flags().BoolVar(&sourceGitArgs.recurseSubmodules, "recurse-submodules", false,
|
||||
"when enabled, configures the GitRepository source to initialize and include Git submodules in the artifact it produces")
|
||||
|
||||
createSourceCmd.AddCommand(createSourceGitCmd)
|
||||
}
|
||||
|
||||
func NewSourceGitFlags() SourceGitFlags {
|
||||
return SourceGitFlags{
|
||||
GitKeyAlgorithm: "rsa",
|
||||
GitRSABits: 2048,
|
||||
GitECDSACurve: flags.ECDSACurve{Curve: elliptic.P384()},
|
||||
func newSourceGitFlags() sourceGitFlags {
|
||||
return sourceGitFlags{
|
||||
keyAlgorithm: flags.PublicKeyAlgorithm(sourcesecret.RSAPrivateKeyAlgorithm),
|
||||
keyRSABits: 2048,
|
||||
keyECDSACurve: flags.ECDSACurve{Curve: elliptic.P384()},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,21 +153,36 @@ func createSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
if sourceArgs.GitURL == "" {
|
||||
if sourceGitArgs.url == "" {
|
||||
return fmt.Errorf("url is required")
|
||||
}
|
||||
|
||||
tmpDir, err := ioutil.TempDir("", name)
|
||||
u, err := url.Parse(sourceGitArgs.url)
|
||||
if err != nil {
|
||||
return fmt.Errorf("git URL parse failed: %w", err)
|
||||
}
|
||||
if u.Scheme != "ssh" && u.Scheme != "http" && u.Scheme != "https" {
|
||||
return fmt.Errorf("git URL scheme '%s' not supported, can be: ssh, http and https", u.Scheme)
|
||||
}
|
||||
|
||||
if sourceGitArgs.branch == "" && sourceGitArgs.tag == "" && sourceGitArgs.semver == "" {
|
||||
return fmt.Errorf("a Git ref is required, use one of the following: --branch, --tag or --tag-semver")
|
||||
}
|
||||
|
||||
if sourceGitArgs.caFile != "" && u.Scheme == "ssh" {
|
||||
return fmt.Errorf("specifing a CA file is not supported for Git over SSH")
|
||||
}
|
||||
|
||||
if sourceGitArgs.recurseSubmodules && sourceGitArgs.gitImplementation == sourcev1.LibGit2Implementation {
|
||||
return fmt.Errorf("recurse submodules requires --git-implementation=%s", sourcev1.GoGitImplementation)
|
||||
}
|
||||
|
||||
tmpDir, err := os.MkdirTemp("", name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
u, err := url.Parse(sourceArgs.GitURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("git URL parse failed: %w", err)
|
||||
}
|
||||
|
||||
sourceLabels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -159,33 +195,35 @@ func createSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
Labels: sourceLabels,
|
||||
},
|
||||
Spec: sourcev1.GitRepositorySpec{
|
||||
URL: sourceArgs.GitURL,
|
||||
URL: sourceGitArgs.url,
|
||||
Interval: metav1.Duration{
|
||||
Duration: createArgs.interval,
|
||||
},
|
||||
Reference: &sourcev1.GitRepositoryRef{},
|
||||
RecurseSubmodules: sourceGitArgs.recurseSubmodules,
|
||||
Reference: &sourcev1.GitRepositoryRef{},
|
||||
},
|
||||
}
|
||||
|
||||
if sourceArgs.GitImplementation != "" {
|
||||
gitRepository.Spec.GitImplementation = sourceArgs.GitImplementation.String()
|
||||
if sourceGitArgs.gitImplementation != "" {
|
||||
gitRepository.Spec.GitImplementation = sourceGitArgs.gitImplementation.String()
|
||||
}
|
||||
|
||||
if sourceArgs.GitSemver != "" {
|
||||
gitRepository.Spec.Reference.SemVer = sourceArgs.GitSemver
|
||||
} else if sourceArgs.GitTag != "" {
|
||||
gitRepository.Spec.Reference.Tag = sourceArgs.GitTag
|
||||
if sourceGitArgs.semver != "" {
|
||||
gitRepository.Spec.Reference.SemVer = sourceGitArgs.semver
|
||||
} else if sourceGitArgs.tag != "" {
|
||||
gitRepository.Spec.Reference.Tag = sourceGitArgs.tag
|
||||
} else {
|
||||
gitRepository.Spec.Reference.Branch = sourceArgs.GitBranch
|
||||
gitRepository.Spec.Reference.Branch = sourceGitArgs.branch
|
||||
}
|
||||
|
||||
if sourceGitArgs.secretRef != "" {
|
||||
gitRepository.Spec.SecretRef = &meta.LocalObjectReference{
|
||||
Name: sourceGitArgs.secretRef,
|
||||
}
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
if sourceArgs.GitSecretRef != "" {
|
||||
gitRepository.Spec.SecretRef = &meta.LocalObjectReference{
|
||||
Name: sourceArgs.GitSecretRef,
|
||||
}
|
||||
}
|
||||
return exportGit(gitRepository)
|
||||
return printExport(exportGit(&gitRepository))
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
@@ -196,82 +234,60 @@ func createSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
withAuth := false
|
||||
// TODO(hidde): move all auth prep to separate func?
|
||||
if sourceArgs.GitSecretRef != "" {
|
||||
withAuth = true
|
||||
} else if u.Scheme == "ssh" {
|
||||
logger.Generatef("generating deploy key pair")
|
||||
pair, err := generateKeyPair(ctx, sourceArgs.GitKeyAlgorithm, sourceArgs.GitRSABits, sourceArgs.GitECDSACurve)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Successf("deploy key: %s", pair.PublicKey)
|
||||
prompt := promptui.Prompt{
|
||||
Label: "Have you added the deploy key to your repository",
|
||||
IsConfirm: true,
|
||||
}
|
||||
if _, err := prompt.Run(); err != nil {
|
||||
return fmt.Errorf("aborting")
|
||||
}
|
||||
|
||||
logger.Actionf("collecting preferred public key from SSH server")
|
||||
hostKey, err := scanHostKey(ctx, u)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("collected public key from SSH server:\n%s", hostKey)
|
||||
|
||||
logger.Actionf("applying secret with keys")
|
||||
secret := corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: rootArgs.namespace,
|
||||
Labels: sourceLabels,
|
||||
},
|
||||
StringData: map[string]string{
|
||||
"identity": string(pair.PrivateKey),
|
||||
"identity.pub": string(pair.PublicKey),
|
||||
"known_hosts": string(hostKey),
|
||||
},
|
||||
}
|
||||
if err := upsertSecret(ctx, kubeClient, secret); err != nil {
|
||||
return err
|
||||
}
|
||||
withAuth = true
|
||||
} else if sourceArgs.GitUsername != "" && sourceArgs.GitPassword != "" {
|
||||
logger.Actionf("applying secret with basic auth credentials")
|
||||
secret := corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: rootArgs.namespace,
|
||||
Labels: sourceLabels,
|
||||
},
|
||||
StringData: map[string]string{
|
||||
"username": sourceArgs.GitUsername,
|
||||
"password": sourceArgs.GitPassword,
|
||||
},
|
||||
}
|
||||
if err := upsertSecret(ctx, kubeClient, secret); err != nil {
|
||||
return err
|
||||
}
|
||||
withAuth = true
|
||||
}
|
||||
|
||||
if withAuth {
|
||||
logger.Successf("authentication configured")
|
||||
}
|
||||
|
||||
logger.Generatef("generating GitRepository source")
|
||||
|
||||
if withAuth {
|
||||
secretName := name
|
||||
if sourceArgs.GitSecretRef != "" {
|
||||
secretName = sourceArgs.GitSecretRef
|
||||
if sourceGitArgs.secretRef == "" {
|
||||
secretOpts := sourcesecret.Options{
|
||||
Name: name,
|
||||
Namespace: rootArgs.namespace,
|
||||
ManifestFile: sourcesecret.MakeDefaultOptions().ManifestFile,
|
||||
}
|
||||
gitRepository.Spec.SecretRef = &meta.LocalObjectReference{
|
||||
Name: secretName,
|
||||
switch u.Scheme {
|
||||
case "ssh":
|
||||
secretOpts.SSHHostname = u.Host
|
||||
secretOpts.PrivateKeyPath = sourceGitArgs.privateKeyFile
|
||||
secretOpts.PrivateKeyAlgorithm = sourcesecret.PrivateKeyAlgorithm(sourceGitArgs.keyAlgorithm)
|
||||
secretOpts.RSAKeyBits = int(sourceGitArgs.keyRSABits)
|
||||
secretOpts.ECDSACurve = sourceGitArgs.keyECDSACurve.Curve
|
||||
secretOpts.Password = sourceGitArgs.password
|
||||
case "https":
|
||||
secretOpts.Username = sourceGitArgs.username
|
||||
secretOpts.Password = sourceGitArgs.password
|
||||
secretOpts.CAFilePath = sourceGitArgs.caFile
|
||||
case "http":
|
||||
logger.Warningf("insecure configuration: credentials configured for an HTTP URL")
|
||||
secretOpts.Username = sourceGitArgs.username
|
||||
secretOpts.Password = sourceGitArgs.password
|
||||
}
|
||||
secret, err := sourcesecret.Generate(secretOpts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var s corev1.Secret
|
||||
if err = yaml.Unmarshal([]byte(secret.Content), &s); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(s.StringData) > 0 {
|
||||
if hk, ok := s.StringData[sourcesecret.KnownHostsSecretKey]; ok {
|
||||
logger.Successf("collected public key from SSH server:\n%s", hk)
|
||||
}
|
||||
if ppk, ok := s.StringData[sourcesecret.PublicKeySecretKey]; ok {
|
||||
logger.Generatef("deploy key: %s", ppk)
|
||||
prompt := promptui.Prompt{
|
||||
Label: "Have you added the deploy key to your repository",
|
||||
IsConfirm: true,
|
||||
}
|
||||
if _, err := prompt.Run(); err != nil {
|
||||
return fmt.Errorf("aborting")
|
||||
}
|
||||
}
|
||||
logger.Actionf("applying secret with repository credentials")
|
||||
if err := upsertSecret(ctx, kubeClient, s); err != nil {
|
||||
return err
|
||||
}
|
||||
gitRepository.Spec.SecretRef = &meta.LocalObjectReference{
|
||||
Name: s.Name,
|
||||
}
|
||||
logger.Successf("authentication configured")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"os"
|
||||
|
||||
@@ -32,47 +31,48 @@ import (
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/sourcesecret"
|
||||
)
|
||||
|
||||
var createSourceHelmCmd = &cobra.Command{
|
||||
Use: "helm [name]",
|
||||
Short: "Create or update a HelmRepository source",
|
||||
Long: `
|
||||
The create source helm command generates a HelmRepository resource and waits for it to fetch the index.
|
||||
Long: `The create source helm command generates a HelmRepository resource and waits for it to fetch the index.
|
||||
For private Helm repositories, the basic authentication credentials are stored in a Kubernetes secret.`,
|
||||
Example: ` # Create a source from a public Helm repository
|
||||
Example: ` # Create a source for a public Helm repository
|
||||
flux create source helm podinfo \
|
||||
--url=https://stefanprodan.github.io/podinfo \
|
||||
--interval=10m
|
||||
|
||||
# Create a source from a Helm repository using basic authentication
|
||||
# Create a source for a Helm repository using basic authentication
|
||||
flux create source helm podinfo \
|
||||
--url=https://stefanprodan.github.io/podinfo \
|
||||
--username=username \
|
||||
--password=password
|
||||
|
||||
# Create a source from a Helm repository using TLS authentication
|
||||
# Create a source for a Helm repository using TLS authentication
|
||||
flux create source helm podinfo \
|
||||
--url=https://stefanprodan.github.io/podinfo \
|
||||
--cert-file=./cert.crt \
|
||||
--key-file=./key.crt \
|
||||
--ca-file=./ca.crt
|
||||
`,
|
||||
--ca-file=./ca.crt`,
|
||||
RunE: createSourceHelmCmdRun,
|
||||
}
|
||||
|
||||
type sourceHelmFlags struct {
|
||||
url string
|
||||
username string
|
||||
password string
|
||||
certFile string
|
||||
keyFile string
|
||||
caFile string
|
||||
secretRef string
|
||||
url string
|
||||
username string
|
||||
password string
|
||||
certFile string
|
||||
keyFile string
|
||||
caFile string
|
||||
secretRef string
|
||||
passCredentials bool
|
||||
}
|
||||
|
||||
var sourceHelmArgs sourceHelmFlags
|
||||
@@ -85,6 +85,7 @@ func init() {
|
||||
createSourceHelmCmd.Flags().StringVar(&sourceHelmArgs.keyFile, "key-file", "", "TLS authentication key file path")
|
||||
createSourceHelmCmd.Flags().StringVar(&sourceHelmArgs.caFile, "ca-file", "", "TLS authentication CA file path")
|
||||
createSourceHelmCmd.Flags().StringVarP(&sourceHelmArgs.secretRef, "secret-ref", "", "", "the name of an existing secret containing TLS or basic auth credentials")
|
||||
createSourceHelmCmd.Flags().BoolVarP(&sourceHelmArgs.passCredentials, "pass-credentials", "", false, "pass credentials to all domains")
|
||||
|
||||
createSourceCmd.AddCommand(createSourceHelmCmd)
|
||||
}
|
||||
@@ -104,7 +105,7 @@ func createSourceHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
tmpDir, err := ioutil.TempDir("", name)
|
||||
tmpDir, err := os.MkdirTemp("", name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -132,10 +133,11 @@ func createSourceHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
helmRepository.Spec.SecretRef = &meta.LocalObjectReference{
|
||||
Name: sourceHelmArgs.secretRef,
|
||||
}
|
||||
helmRepository.Spec.PassCredentials = sourceHelmArgs.passCredentials
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
return exportHelmRepository(*helmRepository)
|
||||
return printExport(exportHelmRepository(helmRepository))
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
@@ -149,51 +151,33 @@ func createSourceHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
logger.Generatef("generating HelmRepository source")
|
||||
if sourceHelmArgs.secretRef == "" {
|
||||
secretName := fmt.Sprintf("helm-%s", name)
|
||||
|
||||
secret := corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: secretName,
|
||||
Namespace: rootArgs.namespace,
|
||||
Labels: sourceLabels,
|
||||
},
|
||||
StringData: map[string]string{},
|
||||
secretOpts := sourcesecret.Options{
|
||||
Name: secretName,
|
||||
Namespace: rootArgs.namespace,
|
||||
Username: sourceHelmArgs.username,
|
||||
Password: sourceHelmArgs.password,
|
||||
CertFilePath: sourceHelmArgs.certFile,
|
||||
KeyFilePath: sourceHelmArgs.keyFile,
|
||||
CAFilePath: sourceHelmArgs.caFile,
|
||||
ManifestFile: sourcesecret.MakeDefaultOptions().ManifestFile,
|
||||
}
|
||||
|
||||
if sourceHelmArgs.username != "" && sourceHelmArgs.password != "" {
|
||||
secret.StringData["username"] = sourceHelmArgs.username
|
||||
secret.StringData["password"] = sourceHelmArgs.password
|
||||
secret, err := sourcesecret.Generate(secretOpts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if sourceHelmArgs.certFile != "" && sourceHelmArgs.keyFile != "" {
|
||||
cert, err := ioutil.ReadFile(sourceHelmArgs.certFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read repository cert file '%s': %w", sourceHelmArgs.certFile, err)
|
||||
}
|
||||
secret.StringData["certFile"] = string(cert)
|
||||
|
||||
key, err := ioutil.ReadFile(sourceHelmArgs.keyFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read repository key file '%s': %w", sourceHelmArgs.keyFile, err)
|
||||
}
|
||||
secret.StringData["keyFile"] = string(key)
|
||||
var s corev1.Secret
|
||||
if err = yaml.Unmarshal([]byte(secret.Content), &s); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if sourceHelmArgs.caFile != "" {
|
||||
ca, err := ioutil.ReadFile(sourceHelmArgs.caFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read repository CA file '%s': %w", sourceHelmArgs.caFile, err)
|
||||
}
|
||||
secret.StringData["caFile"] = string(ca)
|
||||
}
|
||||
|
||||
if len(secret.StringData) > 0 {
|
||||
if len(s.StringData) > 0 {
|
||||
logger.Actionf("applying secret with repository credentials")
|
||||
if err := upsertSecret(ctx, kubeClient, secret); err != nil {
|
||||
if err := upsertSecret(ctx, kubeClient, s); err != nil {
|
||||
return err
|
||||
}
|
||||
helmRepository.Spec.SecretRef = &meta.LocalObjectReference{
|
||||
Name: secretName,
|
||||
}
|
||||
helmRepository.Spec.PassCredentials = sourceHelmArgs.passCredentials
|
||||
logger.Successf("authentication configured")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,8 +37,7 @@ import (
|
||||
var createTenantCmd = &cobra.Command{
|
||||
Use: "tenant",
|
||||
Short: "Create or update a tenant",
|
||||
Long: `
|
||||
The create tenant command generates namespaces, service accounts and role bindings to limit the
|
||||
Long: `The create tenant command generates namespaces, service accounts and role bindings to limit the
|
||||
reconcilers scope to the tenant namespaces.`,
|
||||
Example: ` # Create a tenant with access to a namespace
|
||||
flux create tenant dev-team \
|
||||
@@ -49,8 +48,7 @@ reconcilers scope to the tenant namespaces.`,
|
||||
flux create tenant dev-team \
|
||||
--with-namespace=frontend \
|
||||
--with-namespace=backend \
|
||||
--export > dev-team.yaml
|
||||
`,
|
||||
--export > dev-team.yaml`,
|
||||
RunE: createTenantCmdRun,
|
||||
}
|
||||
|
||||
@@ -150,7 +148,7 @@ func createTenantCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
if createArgs.export {
|
||||
for i, _ := range tenantArgs.namespaces {
|
||||
for i := range tenantArgs.namespaces {
|
||||
if err := exportTenant(namespaces[i], accounts[i], roleBindings[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -166,7 +164,7 @@ func createTenantCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
for i, _ := range tenantArgs.namespaces {
|
||||
for i := range tenantArgs.namespaces {
|
||||
logger.Actionf("applying namespace %s", namespaces[i].Name)
|
||||
if err := upsertNamespace(ctx, kubeClient, namespaces[i]); err != nil {
|
||||
return err
|
||||
|
||||
@@ -17,14 +17,8 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/manifoldco/promptui"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
@@ -33,56 +27,13 @@ var deleteAlertCmd = &cobra.Command{
|
||||
Short: "Delete a Alert resource",
|
||||
Long: "The delete alert command removes the given Alert from the cluster.",
|
||||
Example: ` # Delete an Alert and the Kubernetes resources created by it
|
||||
flux delete alert main
|
||||
`,
|
||||
RunE: deleteAlertCmdRun,
|
||||
flux delete alert main`,
|
||||
RunE: deleteCommand{
|
||||
apiType: alertType,
|
||||
object: universalAdapter{¬ificationv1.Alert{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
deleteCmd.AddCommand(deleteAlertCmd)
|
||||
}
|
||||
|
||||
func deleteAlertCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("alert name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: rootArgs.namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
var alert notificationv1.Alert
|
||||
err = kubeClient.Get(ctx, namespacedName, &alert)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !deleteArgs.silent {
|
||||
prompt := promptui.Prompt{
|
||||
Label: "Are you sure you want to delete this Alert",
|
||||
IsConfirm: true,
|
||||
}
|
||||
if _, err := prompt.Run(); err != nil {
|
||||
return fmt.Errorf("aborting")
|
||||
}
|
||||
}
|
||||
|
||||
logger.Actionf("deleting alert %s in %s namespace", name, rootArgs.namespace)
|
||||
err = kubeClient.Delete(ctx, &alert)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("alert deleted")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -17,14 +17,8 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/manifoldco/promptui"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
@@ -33,56 +27,13 @@ var deleteAlertProviderCmd = &cobra.Command{
|
||||
Short: "Delete a Provider resource",
|
||||
Long: "The delete alert-provider command removes the given Provider from the cluster.",
|
||||
Example: ` # Delete a Provider and the Kubernetes resources created by it
|
||||
flux delete alert-provider slack
|
||||
`,
|
||||
RunE: deleteAlertProviderCmdRun,
|
||||
flux delete alert-provider slack`,
|
||||
RunE: deleteCommand{
|
||||
apiType: alertProviderType,
|
||||
object: universalAdapter{¬ificationv1.Provider{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
deleteCmd.AddCommand(deleteAlertProviderCmd)
|
||||
}
|
||||
|
||||
func deleteAlertProviderCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("provider name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: rootArgs.namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
var alertProvider notificationv1.Provider
|
||||
err = kubeClient.Get(ctx, namespacedName, &alertProvider)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !deleteArgs.silent {
|
||||
prompt := promptui.Prompt{
|
||||
Label: "Are you sure you want to delete this Provider",
|
||||
IsConfirm: true,
|
||||
}
|
||||
if _, err := prompt.Run(); err != nil {
|
||||
return fmt.Errorf("aborting")
|
||||
}
|
||||
}
|
||||
|
||||
logger.Actionf("deleting provider %s in %s namespace", name, rootArgs.namespace)
|
||||
err = kubeClient.Delete(ctx, &alertProvider)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("provider deleted")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -17,8 +17,9 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
|
||||
)
|
||||
|
||||
var deleteHelmReleaseCmd = &cobra.Command{
|
||||
@@ -27,8 +28,7 @@ var deleteHelmReleaseCmd = &cobra.Command{
|
||||
Short: "Delete a HelmRelease resource",
|
||||
Long: "The delete helmrelease command removes the given HelmRelease from the cluster.",
|
||||
Example: ` # Delete a Helm release and the Kubernetes resources created by it
|
||||
flux delete hr podinfo
|
||||
`,
|
||||
flux delete hr podinfo`,
|
||||
RunE: deleteCommand{
|
||||
apiType: helmReleaseType,
|
||||
object: universalAdapter{&helmv2.HelmRelease{}},
|
||||
|
||||
@@ -20,12 +20,12 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var deleteAutoCmd = &cobra.Command{
|
||||
Use: "auto",
|
||||
Short: "Delete automation objects",
|
||||
Long: "The delete auto sub-commands delete automation objects.",
|
||||
var deleteImageCmd = &cobra.Command{
|
||||
Use: "image",
|
||||
Short: "Delete image automation objects",
|
||||
Long: "The delete image sub-commands delete image automation objects.",
|
||||
}
|
||||
|
||||
func init() {
|
||||
deleteCmd.AddCommand(deleteAutoCmd)
|
||||
deleteCmd.AddCommand(deleteImageCmd)
|
||||
}
|
||||
|
||||
@@ -19,16 +19,15 @@ package main
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var deleteImagePolicyCmd = &cobra.Command{
|
||||
Use: "image-policy [name]",
|
||||
Use: "policy [name]",
|
||||
Short: "Delete an ImagePolicy object",
|
||||
Long: "The delete auto image-policy command deletes the given ImagePolicy from the cluster.",
|
||||
Long: "The delete image policy command deletes the given ImagePolicy from the cluster.",
|
||||
Example: ` # Delete an image policy
|
||||
flux delete auto image-policy alpine3.x
|
||||
`,
|
||||
flux delete image policy alpine3.x`,
|
||||
RunE: deleteCommand{
|
||||
apiType: imagePolicyType,
|
||||
object: universalAdapter{&imagev1.ImagePolicy{}},
|
||||
@@ -36,5 +35,5 @@ var deleteImagePolicyCmd = &cobra.Command{
|
||||
}
|
||||
|
||||
func init() {
|
||||
deleteAutoCmd.AddCommand(deleteImagePolicyCmd)
|
||||
deleteImageCmd.AddCommand(deleteImagePolicyCmd)
|
||||
}
|
||||
|
||||
@@ -19,16 +19,15 @@ package main
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var deleteImageRepositoryCmd = &cobra.Command{
|
||||
Use: "image-repository [name]",
|
||||
Use: "repository [name]",
|
||||
Short: "Delete an ImageRepository object",
|
||||
Long: "The delete auto image-repository command deletes the given ImageRepository from the cluster.",
|
||||
Long: "The delete image repository command deletes the given ImageRepository from the cluster.",
|
||||
Example: ` # Delete an image repository
|
||||
flux delete auto image-repository alpine
|
||||
`,
|
||||
flux delete image repository alpine`,
|
||||
RunE: deleteCommand{
|
||||
apiType: imageRepositoryType,
|
||||
object: universalAdapter{&imagev1.ImageRepository{}},
|
||||
@@ -36,5 +35,5 @@ var deleteImageRepositoryCmd = &cobra.Command{
|
||||
}
|
||||
|
||||
func init() {
|
||||
deleteAutoCmd.AddCommand(deleteImageRepositoryCmd)
|
||||
deleteImageCmd.AddCommand(deleteImageRepositoryCmd)
|
||||
}
|
||||
|
||||
@@ -19,16 +19,15 @@ package main
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha1"
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var deleteImageUpdateCmd = &cobra.Command{
|
||||
Use: "image-update [name]",
|
||||
Use: "update [name]",
|
||||
Short: "Delete an ImageUpdateAutomation object",
|
||||
Long: "The delete auto image-update command deletes the given ImageUpdateAutomation from the cluster.",
|
||||
Long: "The delete image update command deletes the given ImageUpdateAutomation from the cluster.",
|
||||
Example: ` # Delete an image update automation
|
||||
flux delete auto image-update latest-images
|
||||
`,
|
||||
flux delete image update latest-images`,
|
||||
RunE: deleteCommand{
|
||||
apiType: imageUpdateAutomationType,
|
||||
object: universalAdapter{&autov1.ImageUpdateAutomation{}},
|
||||
@@ -36,5 +35,5 @@ var deleteImageUpdateCmd = &cobra.Command{
|
||||
}
|
||||
|
||||
func init() {
|
||||
deleteAutoCmd.AddCommand(deleteImageUpdateCmd)
|
||||
deleteImageCmd.AddCommand(deleteImageUpdateCmd)
|
||||
}
|
||||
@@ -17,8 +17,9 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var deleteKsCmd = &cobra.Command{
|
||||
@@ -27,8 +28,7 @@ var deleteKsCmd = &cobra.Command{
|
||||
Short: "Delete a Kustomization resource",
|
||||
Long: "The delete kustomization command deletes the given Kustomization from the cluster.",
|
||||
Example: ` # Delete a kustomization and the Kubernetes resources created by it
|
||||
flux delete kustomization podinfo
|
||||
`,
|
||||
flux delete kustomization podinfo`,
|
||||
RunE: deleteCommand{
|
||||
apiType: kustomizationType,
|
||||
object: universalAdapter{&kustomizev1.Kustomization{}},
|
||||
|
||||
@@ -17,14 +17,8 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/manifoldco/promptui"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
@@ -33,56 +27,13 @@ var deleteReceiverCmd = &cobra.Command{
|
||||
Short: "Delete a Receiver resource",
|
||||
Long: "The delete receiver command removes the given Receiver from the cluster.",
|
||||
Example: ` # Delete an Receiver and the Kubernetes resources created by it
|
||||
flux delete receiver main
|
||||
`,
|
||||
RunE: deleteReceiverCmdRun,
|
||||
flux delete receiver main`,
|
||||
RunE: deleteCommand{
|
||||
apiType: receiverType,
|
||||
object: universalAdapter{¬ificationv1.Receiver{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
deleteCmd.AddCommand(deleteReceiverCmd)
|
||||
}
|
||||
|
||||
func deleteReceiverCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("receiver name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: rootArgs.namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
var receiver notificationv1.Receiver
|
||||
err = kubeClient.Get(ctx, namespacedName, &receiver)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !deleteArgs.silent {
|
||||
prompt := promptui.Prompt{
|
||||
Label: "Are you sure you want to delete this Receiver",
|
||||
IsConfirm: true,
|
||||
}
|
||||
if _, err := prompt.Run(); err != nil {
|
||||
return fmt.Errorf("aborting")
|
||||
}
|
||||
}
|
||||
|
||||
logger.Actionf("deleting receiver %s in %s namespace", name, rootArgs.namespace)
|
||||
err = kubeClient.Delete(ctx, &receiver)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("receiver deleted")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -17,8 +17,9 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var deleteSourceBucketCmd = &cobra.Command{
|
||||
@@ -26,8 +27,7 @@ var deleteSourceBucketCmd = &cobra.Command{
|
||||
Short: "Delete a Bucket source",
|
||||
Long: "The delete source bucket command deletes the given Bucket from the cluster.",
|
||||
Example: ` # Delete a Bucket source
|
||||
flux delete source bucket podinfo
|
||||
`,
|
||||
flux delete source bucket podinfo`,
|
||||
RunE: deleteCommand{
|
||||
apiType: bucketType,
|
||||
object: universalAdapter{&sourcev1.Bucket{}},
|
||||
|
||||
@@ -17,8 +17,9 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var deleteSourceGitCmd = &cobra.Command{
|
||||
@@ -26,8 +27,7 @@ var deleteSourceGitCmd = &cobra.Command{
|
||||
Short: "Delete a GitRepository source",
|
||||
Long: "The delete source git command deletes the given GitRepository from the cluster.",
|
||||
Example: ` # Delete a Git repository
|
||||
flux delete source git podinfo
|
||||
`,
|
||||
flux delete source git podinfo`,
|
||||
RunE: deleteCommand{
|
||||
apiType: gitRepositoryType,
|
||||
object: universalAdapter{&sourcev1.GitRepository{}},
|
||||
|
||||
@@ -17,14 +17,9 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"github.com/manifoldco/promptui"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var deleteSourceHelmCmd = &cobra.Command{
|
||||
@@ -32,8 +27,7 @@ var deleteSourceHelmCmd = &cobra.Command{
|
||||
Short: "Delete a HelmRepository source",
|
||||
Long: "The delete source helm command deletes the given HelmRepository from the cluster.",
|
||||
Example: ` # Delete a Helm repository
|
||||
flux delete source helm podinfo
|
||||
`,
|
||||
flux delete source helm podinfo`,
|
||||
RunE: deleteCommand{
|
||||
apiType: helmRepositoryType,
|
||||
object: universalAdapter{&sourcev1.HelmRepository{}},
|
||||
@@ -43,48 +37,3 @@ var deleteSourceHelmCmd = &cobra.Command{
|
||||
func init() {
|
||||
deleteSourceCmd.AddCommand(deleteSourceHelmCmd)
|
||||
}
|
||||
|
||||
func deleteSourceHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: rootArgs.namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
var helmRepository sourcev1.HelmRepository
|
||||
err = kubeClient.Get(ctx, namespacedName, &helmRepository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !deleteArgs.silent {
|
||||
prompt := promptui.Prompt{
|
||||
Label: "Are you sure you want to delete this source",
|
||||
IsConfirm: true,
|
||||
}
|
||||
if _, err := prompt.Run(); err != nil {
|
||||
return fmt.Errorf("aborting")
|
||||
}
|
||||
}
|
||||
|
||||
logger.Actionf("deleting source %s in %s namespace", name, rootArgs.namespace)
|
||||
err = kubeClient.Delete(ctx, &helmRepository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("source deleted")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
69
cmd/flux/docgen.go
Normal file
69
cmd/flux/docgen.go
Normal file
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
Copyright 2021 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
const fmTemplate = `---
|
||||
title: "%s"
|
||||
---
|
||||
`
|
||||
|
||||
var (
|
||||
cmdDocPath string
|
||||
)
|
||||
|
||||
var docgenCmd = &cobra.Command{
|
||||
Use: "docgen",
|
||||
Short: "Generate the documentation for the CLI commands.",
|
||||
Hidden: true,
|
||||
RunE: docgenCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
docgenCmd.Flags().StringVar(&cmdDocPath, "path", "./docs/cmd", "path to write the generated documentation to")
|
||||
|
||||
rootCmd.AddCommand(docgenCmd)
|
||||
}
|
||||
|
||||
func docgenCmdRun(cmd *cobra.Command, args []string) error {
|
||||
err := doc.GenMarkdownTreeCustom(rootCmd, cmdDocPath, frontmatterPrepender, linkHandler)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func frontmatterPrepender(filename string) string {
|
||||
name := filepath.Base(filename)
|
||||
base := strings.TrimSuffix(name, path.Ext(name))
|
||||
title := strings.Replace(base, "_", " ", -1)
|
||||
return fmt.Sprintf(fmTemplate, title)
|
||||
}
|
||||
|
||||
func linkHandler(name string) string {
|
||||
base := strings.TrimSuffix(name, path.Ext(name))
|
||||
return "../" + strings.ToLower(base) + "/"
|
||||
}
|
||||
@@ -20,7 +20,6 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
@@ -86,8 +85,7 @@ func (export exportCommand) run(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
if export.list.len() == 0 {
|
||||
logger.Failuref("no objects found in %s namespace", rootArgs.namespace)
|
||||
return nil
|
||||
return fmt.Errorf("no objects found in %s namespace", rootArgs.namespace)
|
||||
}
|
||||
|
||||
for i := 0; i < export.list.len(); i++ {
|
||||
|
||||
@@ -17,16 +17,9 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
@@ -38,62 +31,18 @@ var exportAlertCmd = &cobra.Command{
|
||||
flux export alert --all > alerts.yaml
|
||||
|
||||
# Export a Alert
|
||||
flux export alert main > main.yaml
|
||||
`,
|
||||
RunE: exportAlertCmdRun,
|
||||
flux export alert main > main.yaml`,
|
||||
RunE: exportCommand{
|
||||
object: alertAdapter{¬ificationv1.Alert{}},
|
||||
list: alertListAdapter{¬ificationv1.AlertList{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportCmd.AddCommand(exportAlertCmd)
|
||||
}
|
||||
|
||||
func exportAlertCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if !exportArgs.all && len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportArgs.all {
|
||||
var list notificationv1.AlertList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(rootArgs.namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no alerts found in %s namespace", rootArgs.namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, alert := range list.Items {
|
||||
if err := exportAlert(alert); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
name := args[0]
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: rootArgs.namespace,
|
||||
Name: name,
|
||||
}
|
||||
var alert notificationv1.Alert
|
||||
err = kubeClient.Get(ctx, namespacedName, &alert)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return exportAlert(alert)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportAlert(alert notificationv1.Alert) error {
|
||||
func exportAlert(alert *notificationv1.Alert) interface{} {
|
||||
gvk := notificationv1.GroupVersion.WithKind("Alert")
|
||||
export := notificationv1.Alert{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
@@ -109,12 +58,13 @@ func exportAlert(alert notificationv1.Alert) error {
|
||||
Spec: alert.Spec,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(export)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
return export
|
||||
}
|
||||
|
||||
func (ex alertAdapter) export() interface{} {
|
||||
return exportAlert(ex.Alert)
|
||||
}
|
||||
|
||||
func (ex alertListAdapter) exportItem(i int) interface{} {
|
||||
return exportAlert(&ex.AlertList.Items[i])
|
||||
}
|
||||
|
||||
@@ -17,16 +17,9 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
@@ -38,62 +31,18 @@ var exportAlertProviderCmd = &cobra.Command{
|
||||
flux export alert-provider --all > alert-providers.yaml
|
||||
|
||||
# Export a Provider
|
||||
flux export alert-provider slack > slack.yaml
|
||||
`,
|
||||
RunE: exportAlertProviderCmdRun,
|
||||
flux export alert-provider slack > slack.yaml`,
|
||||
RunE: exportCommand{
|
||||
object: alertProviderAdapter{¬ificationv1.Provider{}},
|
||||
list: alertProviderListAdapter{¬ificationv1.ProviderList{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportCmd.AddCommand(exportAlertProviderCmd)
|
||||
}
|
||||
|
||||
func exportAlertProviderCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if !exportArgs.all && len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportArgs.all {
|
||||
var list notificationv1.ProviderList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(rootArgs.namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no alertproviders found in %s namespace", rootArgs.namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, alertProvider := range list.Items {
|
||||
if err := exportAlertProvider(alertProvider); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
name := args[0]
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: rootArgs.namespace,
|
||||
Name: name,
|
||||
}
|
||||
var alertProvider notificationv1.Provider
|
||||
err = kubeClient.Get(ctx, namespacedName, &alertProvider)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return exportAlertProvider(alertProvider)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportAlertProvider(alertProvider notificationv1.Provider) error {
|
||||
func exportAlertProvider(alertProvider *notificationv1.Provider) interface{} {
|
||||
gvk := notificationv1.GroupVersion.WithKind("Provider")
|
||||
export := notificationv1.Provider{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
@@ -108,13 +57,13 @@ func exportAlertProvider(alertProvider notificationv1.Provider) error {
|
||||
},
|
||||
Spec: alertProvider.Spec,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(export)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
return export
|
||||
}
|
||||
|
||||
func (ex alertProviderAdapter) export() interface{} {
|
||||
return exportAlertProvider(ex.Provider)
|
||||
}
|
||||
|
||||
func (ex alertProviderListAdapter) exportItem(i int) interface{} {
|
||||
return exportAlertProvider(&ex.ProviderList.Items[i])
|
||||
}
|
||||
|
||||
@@ -17,16 +17,9 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
|
||||
)
|
||||
|
||||
@@ -39,62 +32,18 @@ var exportHelmReleaseCmd = &cobra.Command{
|
||||
flux export helmrelease --all > kustomizations.yaml
|
||||
|
||||
# Export a HelmRelease
|
||||
flux export hr my-app > app-release.yaml
|
||||
`,
|
||||
RunE: exportHelmReleaseCmdRun,
|
||||
flux export hr my-app > app-release.yaml`,
|
||||
RunE: exportCommand{
|
||||
object: helmReleaseAdapter{&helmv2.HelmRelease{}},
|
||||
list: helmReleaseListAdapter{&helmv2.HelmReleaseList{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportCmd.AddCommand(exportHelmReleaseCmd)
|
||||
}
|
||||
|
||||
func exportHelmReleaseCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if !exportArgs.all && len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportArgs.all {
|
||||
var list helmv2.HelmReleaseList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(rootArgs.namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no helmrelease found in %s namespace", rootArgs.namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, helmRelease := range list.Items {
|
||||
if err := exportHelmRelease(helmRelease); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
name := args[0]
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: rootArgs.namespace,
|
||||
Name: name,
|
||||
}
|
||||
var helmRelease helmv2.HelmRelease
|
||||
err = kubeClient.Get(ctx, namespacedName, &helmRelease)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return exportHelmRelease(helmRelease)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportHelmRelease(helmRelease helmv2.HelmRelease) error {
|
||||
func exportHelmRelease(helmRelease *helmv2.HelmRelease) interface{} {
|
||||
gvk := helmv2.GroupVersion.WithKind(helmv2.HelmReleaseKind)
|
||||
export := helmv2.HelmRelease{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
@@ -109,13 +58,13 @@ func exportHelmRelease(helmRelease helmv2.HelmRelease) error {
|
||||
},
|
||||
Spec: helmRelease.Spec,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(export)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
return export
|
||||
}
|
||||
|
||||
func (ex helmReleaseAdapter) export() interface{} {
|
||||
return exportHelmRelease(ex.HelmRelease)
|
||||
}
|
||||
|
||||
func (ex helmReleaseListAdapter) exportItem(i int) interface{} {
|
||||
return exportHelmRelease(&ex.HelmReleaseList.Items[i])
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var exportImagePolicyCmd = &cobra.Command{
|
||||
@@ -31,8 +31,7 @@ var exportImagePolicyCmd = &cobra.Command{
|
||||
flux export image policy --all > image-policies.yaml
|
||||
|
||||
# Export a specific policy
|
||||
flux export image policy alpine1x > alpine1x.yaml
|
||||
`,
|
||||
flux export image policy alpine1x > alpine1x.yaml`,
|
||||
RunE: exportCommand{
|
||||
object: imagePolicyAdapter{&imagev1.ImagePolicy{}},
|
||||
list: imagePolicyListAdapter{&imagev1.ImagePolicyList{}},
|
||||
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var exportImageRepositoryCmd = &cobra.Command{
|
||||
@@ -31,8 +31,7 @@ var exportImageRepositoryCmd = &cobra.Command{
|
||||
flux export image repository --all > image-repositories.yaml
|
||||
|
||||
# Export a specific ImageRepository resource
|
||||
flux export image repository alpine > alpine.yaml
|
||||
`,
|
||||
flux export image repository alpine > alpine.yaml`,
|
||||
RunE: exportCommand{
|
||||
object: imageRepositoryAdapter{&imagev1.ImageRepository{}},
|
||||
list: imageRepositoryListAdapter{&imagev1.ImageRepositoryList{}},
|
||||
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha1"
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var exportImageUpdateCmd = &cobra.Command{
|
||||
@@ -31,8 +31,7 @@ var exportImageUpdateCmd = &cobra.Command{
|
||||
flux export image update --all > updates.yaml
|
||||
|
||||
# Export a specific automation
|
||||
flux export image update latest-images > latest.yaml
|
||||
`,
|
||||
flux export image update latest-images > latest.yaml`,
|
||||
RunE: exportCommand{
|
||||
object: imageUpdateAutomationAdapter{&autov1.ImageUpdateAutomation{}},
|
||||
list: imageUpdateAutomationListAdapter{&autov1.ImageUpdateAutomationList{}},
|
||||
@@ -17,16 +17,9 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
@@ -39,62 +32,18 @@ var exportKsCmd = &cobra.Command{
|
||||
flux export kustomization --all > kustomizations.yaml
|
||||
|
||||
# Export a Kustomization
|
||||
flux export kustomization my-app > kustomization.yaml
|
||||
`,
|
||||
RunE: exportKsCmdRun,
|
||||
flux export kustomization my-app > kustomization.yaml`,
|
||||
RunE: exportCommand{
|
||||
object: kustomizationAdapter{&kustomizev1.Kustomization{}},
|
||||
list: kustomizationListAdapter{&kustomizev1.KustomizationList{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportCmd.AddCommand(exportKsCmd)
|
||||
}
|
||||
|
||||
func exportKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if !exportArgs.all && len(args) < 1 {
|
||||
return fmt.Errorf("kustomization name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportArgs.all {
|
||||
var list kustomizev1.KustomizationList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(rootArgs.namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no kustomizations found in %s namespace", rootArgs.namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, kustomization := range list.Items {
|
||||
if err := exportKs(kustomization); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
name := args[0]
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: rootArgs.namespace,
|
||||
Name: name,
|
||||
}
|
||||
var kustomization kustomizev1.Kustomization
|
||||
err = kubeClient.Get(ctx, namespacedName, &kustomization)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return exportKs(kustomization)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportKs(kustomization kustomizev1.Kustomization) error {
|
||||
func exportKs(kustomization *kustomizev1.Kustomization) interface{} {
|
||||
gvk := kustomizev1.GroupVersion.WithKind("Kustomization")
|
||||
export := kustomizev1.Kustomization{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
@@ -110,12 +59,13 @@ func exportKs(kustomization kustomizev1.Kustomization) error {
|
||||
Spec: kustomization.Spec,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(export)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
return export
|
||||
}
|
||||
|
||||
func (ex kustomizationAdapter) export() interface{} {
|
||||
return exportKs(ex.Kustomization)
|
||||
}
|
||||
|
||||
func (ex kustomizationListAdapter) exportItem(i int) interface{} {
|
||||
return exportKs(&ex.KustomizationList.Items[i])
|
||||
}
|
||||
|
||||
@@ -17,16 +17,9 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
@@ -38,62 +31,18 @@ var exportReceiverCmd = &cobra.Command{
|
||||
flux export receiver --all > receivers.yaml
|
||||
|
||||
# Export a Receiver
|
||||
flux export receiver main > main.yaml
|
||||
`,
|
||||
RunE: exportReceiverCmdRun,
|
||||
flux export receiver main > main.yaml`,
|
||||
RunE: exportCommand{
|
||||
list: receiverListAdapter{¬ificationv1.ReceiverList{}},
|
||||
object: receiverAdapter{¬ificationv1.Receiver{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportCmd.AddCommand(exportReceiverCmd)
|
||||
}
|
||||
|
||||
func exportReceiverCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if !exportArgs.all && len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportArgs.all {
|
||||
var list notificationv1.ReceiverList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(rootArgs.namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no receivers found in %s namespace", rootArgs.namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, receiver := range list.Items {
|
||||
if err := exportReceiver(receiver); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
name := args[0]
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: rootArgs.namespace,
|
||||
Name: name,
|
||||
}
|
||||
var receiver notificationv1.Receiver
|
||||
err = kubeClient.Get(ctx, namespacedName, &receiver)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return exportReceiver(receiver)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportReceiver(receiver notificationv1.Receiver) error {
|
||||
func exportReceiver(receiver *notificationv1.Receiver) interface{} {
|
||||
gvk := notificationv1.GroupVersion.WithKind("Receiver")
|
||||
export := notificationv1.Receiver{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
@@ -109,12 +58,13 @@ func exportReceiver(receiver notificationv1.Receiver) error {
|
||||
Spec: receiver.Spec,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(export)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
return export
|
||||
}
|
||||
|
||||
func (ex receiverAdapter) export() interface{} {
|
||||
return exportReceiver(ex.Receiver)
|
||||
}
|
||||
|
||||
func (ex receiverListAdapter) exportItem(i int) interface{} {
|
||||
return exportReceiver(&ex.ReceiverList.Items[i])
|
||||
}
|
||||
|
||||
134
cmd/flux/export_secret.go
Normal file
134
cmd/flux/export_secret.go
Normal file
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
Copyright 2021 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
)
|
||||
|
||||
// exportableWithSecret represents a type that you can fetch from the Kubernetes
|
||||
// API, get a secretRef from the spec, then tidy up for serialising.
|
||||
type exportableWithSecret interface {
|
||||
adapter
|
||||
exportable
|
||||
secret() *types.NamespacedName
|
||||
}
|
||||
|
||||
// exportableWithSecretList represents a type that has a list of values, each of
|
||||
// which is exportableWithSecret.
|
||||
type exportableWithSecretList interface {
|
||||
listAdapter
|
||||
exportableList
|
||||
secretItem(i int) *types.NamespacedName
|
||||
}
|
||||
|
||||
type exportWithSecretCommand struct {
|
||||
apiType
|
||||
object exportableWithSecret
|
||||
list exportableWithSecretList
|
||||
}
|
||||
|
||||
func (export exportWithSecretCommand) run(cmd *cobra.Command, args []string) error {
|
||||
if !exportArgs.all && len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportArgs.all {
|
||||
err = kubeClient.List(ctx, export.list.asClientList(), client.InNamespace(rootArgs.namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if export.list.len() == 0 {
|
||||
return fmt.Errorf("no objects found in %s namespace", rootArgs.namespace)
|
||||
}
|
||||
|
||||
for i := 0; i < export.list.len(); i++ {
|
||||
if err = printExport(export.list.exportItem(i)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportSourceWithCred {
|
||||
if export.list.secretItem(i) != nil {
|
||||
namespacedName := *export.list.secretItem(i)
|
||||
return printSecretCredentials(ctx, kubeClient, namespacedName)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
name := args[0]
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: rootArgs.namespace,
|
||||
Name: name,
|
||||
}
|
||||
err = kubeClient.Get(ctx, namespacedName, export.object.asClientObject())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := printExport(export.object.export()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportSourceWithCred {
|
||||
if export.object.secret() != nil {
|
||||
namespacedName := *export.object.secret()
|
||||
return printSecretCredentials(ctx, kubeClient, namespacedName)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func printSecretCredentials(ctx context.Context, kubeClient client.Client, nsName types.NamespacedName) error {
|
||||
var cred corev1.Secret
|
||||
err := kubeClient.Get(ctx, nsName, &cred)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to retrieve secret %s, error: %w", nsName.Name, err)
|
||||
}
|
||||
|
||||
exported := corev1.Secret{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
APIVersion: "v1",
|
||||
Kind: "Secret",
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: nsName.Name,
|
||||
Namespace: nsName.Namespace,
|
||||
},
|
||||
Data: cred.Data,
|
||||
Type: cred.Type,
|
||||
}
|
||||
return printExport(exported)
|
||||
}
|
||||
@@ -17,94 +17,33 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var exportSourceBucketCmd = &cobra.Command{
|
||||
Use: "bucket [name]",
|
||||
Short: "Export Bucket sources in YAML format",
|
||||
Long: "The export source git command exports on or all Bucket sources in YAML format.",
|
||||
Long: "The export source git command exports one or all Bucket sources in YAML format.",
|
||||
Example: ` # Export all Bucket sources
|
||||
flux export source bucket --all > sources.yaml
|
||||
|
||||
# Export a Bucket source including the static credentials
|
||||
flux export source bucket my-bucket --with-credentials > source.yaml
|
||||
`,
|
||||
RunE: exportSourceBucketCmdRun,
|
||||
flux export source bucket my-bucket --with-credentials > source.yaml`,
|
||||
RunE: exportWithSecretCommand{
|
||||
list: bucketListAdapter{&sourcev1.BucketList{}},
|
||||
object: bucketAdapter{&sourcev1.Bucket{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportSourceCmd.AddCommand(exportSourceBucketCmd)
|
||||
}
|
||||
|
||||
func exportSourceBucketCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if !exportArgs.all && len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportArgs.all {
|
||||
var list sourcev1.BucketList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(rootArgs.namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no source found in %s namespace", rootArgs.namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, bucket := range list.Items {
|
||||
if err := exportBucket(bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
if exportSourceWithCred {
|
||||
if err := exportBucketCredentials(ctx, kubeClient, bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
name := args[0]
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: rootArgs.namespace,
|
||||
Name: name,
|
||||
}
|
||||
var bucket sourcev1.Bucket
|
||||
err = kubeClient.Get(ctx, namespacedName, &bucket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := exportBucket(bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
if exportSourceWithCred {
|
||||
return exportBucketCredentials(ctx, kubeClient, bucket)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportBucket(source sourcev1.Bucket) error {
|
||||
func exportBucket(source *sourcev1.Bucket) interface{} {
|
||||
gvk := sourcev1.GroupVersion.WithKind(sourcev1.BucketKind)
|
||||
export := sourcev1.Bucket{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
@@ -119,49 +58,34 @@ func exportBucket(source sourcev1.Bucket) error {
|
||||
},
|
||||
Spec: source.Spec,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(export)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
return export
|
||||
}
|
||||
|
||||
func exportBucketCredentials(ctx context.Context, kubeClient client.Client, source sourcev1.Bucket) error {
|
||||
func getBucketSecret(source *sourcev1.Bucket) *types.NamespacedName {
|
||||
if source.Spec.SecretRef != nil {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: source.Namespace,
|
||||
Name: source.Spec.SecretRef.Name,
|
||||
}
|
||||
var cred corev1.Secret
|
||||
err := kubeClient.Get(ctx, namespacedName, &cred)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to retrieve secret %s, error: %w", namespacedName.Name, err)
|
||||
}
|
||||
|
||||
exported := corev1.Secret{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
APIVersion: "v1",
|
||||
Kind: "Secret",
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: namespacedName.Name,
|
||||
Namespace: namespacedName.Namespace,
|
||||
},
|
||||
Data: cred.Data,
|
||||
Type: cred.Type,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(exported)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return &namespacedName
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ex bucketAdapter) secret() *types.NamespacedName {
|
||||
return getBucketSecret(ex.Bucket)
|
||||
}
|
||||
|
||||
func (ex bucketListAdapter) secretItem(i int) *types.NamespacedName {
|
||||
return getBucketSecret(&ex.BucketList.Items[i])
|
||||
}
|
||||
|
||||
func (ex bucketAdapter) export() interface{} {
|
||||
return exportBucket(ex.Bucket)
|
||||
}
|
||||
|
||||
func (ex bucketListAdapter) exportItem(i int) interface{} {
|
||||
return exportBucket(&ex.BucketList.Items[i])
|
||||
}
|
||||
|
||||
@@ -17,94 +17,33 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var exportSourceGitCmd = &cobra.Command{
|
||||
Use: "git [name]",
|
||||
Short: "Export GitRepository sources in YAML format",
|
||||
Long: "The export source git command exports on or all GitRepository sources in YAML format.",
|
||||
Long: "The export source git command exports one or all GitRepository sources in YAML format.",
|
||||
Example: ` # Export all GitRepository sources
|
||||
flux export source git --all > sources.yaml
|
||||
|
||||
# Export a GitRepository source including the SSH key pair or basic auth credentials
|
||||
flux export source git my-private-repo --with-credentials > source.yaml
|
||||
`,
|
||||
RunE: exportSourceGitCmdRun,
|
||||
flux export source git my-private-repo --with-credentials > source.yaml`,
|
||||
RunE: exportWithSecretCommand{
|
||||
object: gitRepositoryAdapter{&sourcev1.GitRepository{}},
|
||||
list: gitRepositoryListAdapter{&sourcev1.GitRepositoryList{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportSourceCmd.AddCommand(exportSourceGitCmd)
|
||||
}
|
||||
|
||||
func exportSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if !exportArgs.all && len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportArgs.all {
|
||||
var list sourcev1.GitRepositoryList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(rootArgs.namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no source found in %s namespace", rootArgs.namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, repository := range list.Items {
|
||||
if err := exportGit(repository); err != nil {
|
||||
return err
|
||||
}
|
||||
if exportSourceWithCred {
|
||||
if err := exportGitCredentials(ctx, kubeClient, repository); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
name := args[0]
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: rootArgs.namespace,
|
||||
Name: name,
|
||||
}
|
||||
var repository sourcev1.GitRepository
|
||||
err = kubeClient.Get(ctx, namespacedName, &repository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := exportGit(repository); err != nil {
|
||||
return err
|
||||
}
|
||||
if exportSourceWithCred {
|
||||
return exportGitCredentials(ctx, kubeClient, repository)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportGit(source sourcev1.GitRepository) error {
|
||||
func exportGit(source *sourcev1.GitRepository) interface{} {
|
||||
gvk := sourcev1.GroupVersion.WithKind(sourcev1.GitRepositoryKind)
|
||||
export := sourcev1.GitRepository{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
@@ -120,48 +59,33 @@ func exportGit(source sourcev1.GitRepository) error {
|
||||
Spec: source.Spec,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(export)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
return export
|
||||
}
|
||||
|
||||
func exportGitCredentials(ctx context.Context, kubeClient client.Client, source sourcev1.GitRepository) error {
|
||||
func getGitSecret(source *sourcev1.GitRepository) *types.NamespacedName {
|
||||
if source.Spec.SecretRef != nil {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: source.Namespace,
|
||||
Name: source.Spec.SecretRef.Name,
|
||||
}
|
||||
var cred corev1.Secret
|
||||
err := kubeClient.Get(ctx, namespacedName, &cred)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to retrieve secret %s, error: %w", namespacedName.Name, err)
|
||||
}
|
||||
|
||||
exported := corev1.Secret{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
APIVersion: "v1",
|
||||
Kind: "Secret",
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: namespacedName.Name,
|
||||
Namespace: namespacedName.Namespace,
|
||||
},
|
||||
Data: cred.Data,
|
||||
Type: cred.Type,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(exported)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return &namespacedName
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ex gitRepositoryAdapter) secret() *types.NamespacedName {
|
||||
return getGitSecret(ex.GitRepository)
|
||||
}
|
||||
|
||||
func (ex gitRepositoryListAdapter) secretItem(i int) *types.NamespacedName {
|
||||
return getGitSecret(&ex.GitRepositoryList.Items[i])
|
||||
}
|
||||
|
||||
func (ex gitRepositoryAdapter) export() interface{} {
|
||||
return exportGit(ex.GitRepository)
|
||||
}
|
||||
|
||||
func (ex gitRepositoryListAdapter) exportItem(i int) interface{} {
|
||||
return exportGit(&ex.GitRepositoryList.Items[i])
|
||||
}
|
||||
|
||||
@@ -17,94 +17,33 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var exportSourceHelmCmd = &cobra.Command{
|
||||
Use: "helm [name]",
|
||||
Short: "Export HelmRepository sources in YAML format",
|
||||
Long: "The export source git command exports on or all HelmRepository sources in YAML format.",
|
||||
Long: "The export source git command exports one or all HelmRepository sources in YAML format.",
|
||||
Example: ` # Export all HelmRepository sources
|
||||
flux export source helm --all > sources.yaml
|
||||
|
||||
# Export a HelmRepository source including the basic auth credentials
|
||||
flux export source helm my-private-repo --with-credentials > source.yaml
|
||||
`,
|
||||
RunE: exportSourceHelmCmdRun,
|
||||
flux export source helm my-private-repo --with-credentials > source.yaml`,
|
||||
RunE: exportWithSecretCommand{
|
||||
list: helmRepositoryListAdapter{&sourcev1.HelmRepositoryList{}},
|
||||
object: helmRepositoryAdapter{&sourcev1.HelmRepository{}},
|
||||
}.run,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportSourceCmd.AddCommand(exportSourceHelmCmd)
|
||||
}
|
||||
|
||||
func exportSourceHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if !exportArgs.all && len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportArgs.all {
|
||||
var list sourcev1.HelmRepositoryList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(rootArgs.namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no source found in %s namespace", rootArgs.namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, repository := range list.Items {
|
||||
if err := exportHelmRepository(repository); err != nil {
|
||||
return err
|
||||
}
|
||||
if exportSourceWithCred {
|
||||
if err := exportHelmCredentials(ctx, kubeClient, repository); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
name := args[0]
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: rootArgs.namespace,
|
||||
Name: name,
|
||||
}
|
||||
var repository sourcev1.HelmRepository
|
||||
err = kubeClient.Get(ctx, namespacedName, &repository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := exportHelmRepository(repository); err != nil {
|
||||
return err
|
||||
}
|
||||
if exportSourceWithCred {
|
||||
return exportHelmCredentials(ctx, kubeClient, repository)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportHelmRepository(source sourcev1.HelmRepository) error {
|
||||
func exportHelmRepository(source *sourcev1.HelmRepository) interface{} {
|
||||
gvk := sourcev1.GroupVersion.WithKind(sourcev1.HelmRepositoryKind)
|
||||
export := sourcev1.HelmRepository{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
@@ -119,49 +58,32 @@ func exportHelmRepository(source sourcev1.HelmRepository) error {
|
||||
},
|
||||
Spec: source.Spec,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(export)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
return export
|
||||
}
|
||||
|
||||
func exportHelmCredentials(ctx context.Context, kubeClient client.Client, source sourcev1.HelmRepository) error {
|
||||
func getHelmSecret(source *sourcev1.HelmRepository) *types.NamespacedName {
|
||||
if source.Spec.SecretRef != nil {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: source.Namespace,
|
||||
Name: source.Spec.SecretRef.Name,
|
||||
}
|
||||
var cred corev1.Secret
|
||||
err := kubeClient.Get(ctx, namespacedName, &cred)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to retrieve secret %s, error: %w", namespacedName.Name, err)
|
||||
}
|
||||
|
||||
exported := corev1.Secret{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
APIVersion: "v1",
|
||||
Kind: "Secret",
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: namespacedName.Name,
|
||||
Namespace: namespacedName.Namespace,
|
||||
},
|
||||
Data: cred.Data,
|
||||
Type: cred.Type,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(exported)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return &namespacedName
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ex helmRepositoryAdapter) secret() *types.NamespacedName {
|
||||
return getHelmSecret(ex.HelmRepository)
|
||||
}
|
||||
|
||||
func (ex helmRepositoryListAdapter) secretItem(i int) *types.NamespacedName {
|
||||
return getHelmSecret(&ex.HelmRepositoryList.Items[i])
|
||||
}
|
||||
|
||||
func (ex helmRepositoryAdapter) export() interface{} {
|
||||
return exportHelmRepository(ex.HelmRepository)
|
||||
}
|
||||
|
||||
func (ex helmRepositoryListAdapter) exportItem(i int) interface{} {
|
||||
return exportHelmRepository(&ex.HelmRepositoryList.Items[i])
|
||||
}
|
||||
|
||||
184
cmd/flux/get.go
184
cmd/flux/get.go
@@ -18,11 +18,16 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/watch"
|
||||
watchtools "k8s.io/client-go/tools/watch"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
@@ -30,14 +35,37 @@ import (
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
)
|
||||
|
||||
type deriveType func(runtime.Object) (summarisable, error)
|
||||
|
||||
type typeMap map[string]deriveType
|
||||
|
||||
func (m typeMap) registerCommand(t string, f deriveType) error {
|
||||
if _, ok := m[t]; ok {
|
||||
return fmt.Errorf("duplicate type function %s", t)
|
||||
}
|
||||
m[t] = f
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m typeMap) execute(t string, obj runtime.Object) (summarisable, error) {
|
||||
f, ok := m[t]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unsupported type %s", t)
|
||||
}
|
||||
return f(obj)
|
||||
}
|
||||
|
||||
var getCmd = &cobra.Command{
|
||||
Use: "get",
|
||||
Short: "Get sources and resources",
|
||||
Long: "The get sub-commands print the statuses of sources and resources.",
|
||||
Short: "Get the resources and their status",
|
||||
Long: "The get sub-commands print the statuses of Flux resources.",
|
||||
}
|
||||
|
||||
type GetFlags struct {
|
||||
allNamespaces bool
|
||||
allNamespaces bool
|
||||
noHeader bool
|
||||
statusSelector string
|
||||
watch bool
|
||||
}
|
||||
|
||||
var getArgs GetFlags
|
||||
@@ -45,13 +73,18 @@ var getArgs GetFlags
|
||||
func init() {
|
||||
getCmd.PersistentFlags().BoolVarP(&getArgs.allNamespaces, "all-namespaces", "A", false,
|
||||
"list the requested object(s) across all namespaces")
|
||||
getCmd.PersistentFlags().BoolVarP(&getArgs.noHeader, "no-header", "", false, "skip the header when printing the results")
|
||||
getCmd.PersistentFlags().BoolVarP(&getArgs.watch, "watch", "w", false, "After listing/getting the requested object, watch for changes.")
|
||||
getCmd.PersistentFlags().StringVar(&getArgs.statusSelector, "status-selector", "",
|
||||
"specify the status condition name and the desired state to filter the get result, e.g. ready=false")
|
||||
rootCmd.AddCommand(getCmd)
|
||||
}
|
||||
|
||||
type summarisable interface {
|
||||
listAdapter
|
||||
summariseItem(i int, includeNamespace bool) []string
|
||||
summariseItem(i int, includeNamespace bool, includeKind bool) []string
|
||||
headers(includeNamespace bool) []string
|
||||
statusSelectorMatches(i int, conditionType, conditionStatus string) bool
|
||||
}
|
||||
|
||||
// --- these help with implementations of summarisable
|
||||
@@ -63,18 +96,39 @@ func statusAndMessage(conditions []metav1.Condition) (string, string) {
|
||||
return string(metav1.ConditionFalse), "waiting to be reconciled"
|
||||
}
|
||||
|
||||
func nameColumns(item named, includeNamespace bool) []string {
|
||||
if includeNamespace {
|
||||
return []string{item.GetNamespace(), item.GetName()}
|
||||
func statusMatches(conditionType, conditionStatus string, conditions []metav1.Condition) bool {
|
||||
// we don't use apimeta.FindStatusCondition because we'd like to use EqualFold to compare two strings
|
||||
var c *metav1.Condition
|
||||
for i := range conditions {
|
||||
if strings.EqualFold(conditions[i].Type, conditionType) {
|
||||
c = &conditions[i]
|
||||
}
|
||||
}
|
||||
return []string{item.GetName()}
|
||||
if c != nil {
|
||||
return strings.EqualFold(string(c.Status), conditionStatus)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func nameColumns(item named, includeNamespace bool, includeKind bool) []string {
|
||||
name := item.GetName()
|
||||
if includeKind {
|
||||
name = fmt.Sprintf("%s/%s",
|
||||
strings.ToLower(item.GetObjectKind().GroupVersionKind().Kind),
|
||||
item.GetName())
|
||||
}
|
||||
if includeNamespace {
|
||||
return []string{item.GetNamespace(), name}
|
||||
}
|
||||
return []string{name}
|
||||
}
|
||||
|
||||
var namespaceHeader = []string{"Namespace"}
|
||||
|
||||
type getCommand struct {
|
||||
apiType
|
||||
list summarisable
|
||||
list summarisable
|
||||
funcMap typeMap
|
||||
}
|
||||
|
||||
func (get getCommand) run(cmd *cobra.Command, args []string) error {
|
||||
@@ -90,22 +144,120 @@ func (get getCommand) run(cmd *cobra.Command, args []string) error {
|
||||
if !getArgs.allNamespaces {
|
||||
listOpts = append(listOpts, client.InNamespace(rootArgs.namespace))
|
||||
}
|
||||
|
||||
if len(args) > 0 {
|
||||
listOpts = append(listOpts, client.MatchingFields{"metadata.name": args[0]})
|
||||
}
|
||||
|
||||
getAll := cmd.Use == "all"
|
||||
|
||||
if getArgs.watch {
|
||||
return get.watch(ctx, kubeClient, cmd, args, listOpts)
|
||||
}
|
||||
|
||||
err = kubeClient.List(ctx, get.list.asClientList(), listOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if get.list.len() == 0 {
|
||||
logger.Failuref("no %s objects found in %s namespace", get.kind, rootArgs.namespace)
|
||||
if !getAll {
|
||||
logger.Failuref("no %s objects found in %s namespace", get.kind, rootArgs.namespace)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
header := get.list.headers(getArgs.allNamespaces)
|
||||
var rows [][]string
|
||||
for i := 0; i < get.list.len(); i++ {
|
||||
row := get.list.summariseItem(i, getArgs.allNamespaces)
|
||||
rows = append(rows, row)
|
||||
var header []string
|
||||
if !getArgs.noHeader {
|
||||
header = get.list.headers(getArgs.allNamespaces)
|
||||
}
|
||||
|
||||
rows, err := getRowsToPrint(getAll, get.list)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
utils.PrintTable(cmd.OutOrStderr(), header, rows)
|
||||
|
||||
if getAll {
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getRowsToPrint(getAll bool, list summarisable) ([][]string, error) {
|
||||
noFilter := true
|
||||
var conditionType, conditionStatus string
|
||||
if getArgs.statusSelector != "" {
|
||||
parts := strings.SplitN(getArgs.statusSelector, "=", 2)
|
||||
if len(parts) != 2 {
|
||||
return nil, fmt.Errorf("expected status selector in type=status format, but found: %s", getArgs.statusSelector)
|
||||
}
|
||||
conditionType = parts[0]
|
||||
conditionStatus = parts[1]
|
||||
noFilter = false
|
||||
}
|
||||
var rows [][]string
|
||||
for i := 0; i < list.len(); i++ {
|
||||
if noFilter || list.statusSelectorMatches(i, conditionType, conditionStatus) {
|
||||
row := list.summariseItem(i, getArgs.allNamespaces, getAll)
|
||||
rows = append(rows, row)
|
||||
}
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
//
|
||||
// watch starts a client-side watch of one or more resources.
|
||||
func (get *getCommand) watch(ctx context.Context, kubeClient client.WithWatch, cmd *cobra.Command, args []string, listOpts []client.ListOption) error {
|
||||
w, err := kubeClient.Watch(ctx, get.list.asClientList(), listOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = watchUntil(ctx, w, get)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func watchUntil(ctx context.Context, w watch.Interface, get *getCommand) (bool, error) {
|
||||
firstIteration := true
|
||||
_, error := watchtools.UntilWithoutRetry(ctx, w, func(e watch.Event) (bool, error) {
|
||||
objToPrint := e.Object
|
||||
sink, err := get.funcMap.execute(get.apiType.kind, objToPrint)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
var header []string
|
||||
if !getArgs.noHeader {
|
||||
header = sink.headers(getArgs.allNamespaces)
|
||||
}
|
||||
rows, err := getRowsToPrint(false, sink)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if firstIteration {
|
||||
utils.PrintTable(os.Stdout, header, rows)
|
||||
firstIteration = false
|
||||
} else {
|
||||
utils.PrintTable(os.Stdout, []string{}, rows)
|
||||
}
|
||||
|
||||
return false, nil
|
||||
})
|
||||
|
||||
return false, error
|
||||
}
|
||||
|
||||
func validateWatchOption(cmd *cobra.Command, toMatch string) error {
|
||||
w, _ := cmd.Flags().GetBool("watch")
|
||||
if cmd.Use == toMatch && w {
|
||||
return fmt.Errorf("expected a single resource type, but found %s", cmd.Use)
|
||||
}
|
||||
utils.PrintTable(os.Stdout, header, rows)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -17,86 +17,77 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
)
|
||||
|
||||
var getAlertCmd = &cobra.Command{
|
||||
Use: "alerts",
|
||||
Short: "Get Alert statuses",
|
||||
Long: "The get alert command prints the statuses of the resources.",
|
||||
Use: "alerts",
|
||||
Aliases: []string{"alert"},
|
||||
Short: "Get Alert statuses",
|
||||
Long: "The get alert command prints the statuses of the resources.",
|
||||
Example: ` # List all Alerts and their status
|
||||
flux get alerts
|
||||
`,
|
||||
RunE: getAlertCmdRun,
|
||||
flux get alerts`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
get := getCommand{
|
||||
apiType: alertType,
|
||||
list: &alertListAdapter{¬ificationv1.AlertList{}},
|
||||
funcMap: make(typeMap),
|
||||
}
|
||||
|
||||
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
|
||||
o, ok := obj.(*notificationv1.Alert)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Impossible to cast type %#v alert", obj)
|
||||
}
|
||||
|
||||
sink := alertListAdapter{
|
||||
¬ificationv1.AlertList{
|
||||
Items: []notificationv1.Alert{
|
||||
*o,
|
||||
},
|
||||
},
|
||||
}
|
||||
return sink, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := get.run(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
getCmd.AddCommand(getAlertCmd)
|
||||
}
|
||||
|
||||
func getAlertCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var listOpts []client.ListOption
|
||||
if !getArgs.allNamespaces {
|
||||
listOpts = append(listOpts, client.InNamespace(rootArgs.namespace))
|
||||
}
|
||||
var list notificationv1.AlertList
|
||||
err = kubeClient.List(ctx, &list, listOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no alerts found in %s namespace", rootArgs.namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Ready", "Message", "Suspended"}
|
||||
if getArgs.allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, alert := range list.Items {
|
||||
row := []string{}
|
||||
if c := apimeta.FindStatusCondition(alert.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
alert.GetName(),
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
strings.Title(strconv.FormatBool(alert.Spec.Suspend)),
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
alert.GetName(),
|
||||
string(metav1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
strings.Title(strconv.FormatBool(alert.Spec.Suspend)),
|
||||
}
|
||||
}
|
||||
if getArgs.allNamespaces {
|
||||
row = append([]string{alert.Namespace}, row...)
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
utils.PrintTable(os.Stdout, header, rows)
|
||||
return nil
|
||||
func (s alertListAdapter) summariseItem(i int, includeNamespace bool, includeKind bool) []string {
|
||||
item := s.Items[i]
|
||||
status, msg := statusAndMessage(item.Status.Conditions)
|
||||
return append(nameColumns(&item, includeNamespace, includeKind), status, msg, strings.Title(strconv.FormatBool(item.Spec.Suspend)))
|
||||
}
|
||||
|
||||
func (s alertListAdapter) headers(includeNamespace bool) []string {
|
||||
headers := []string{"Name", "Ready", "Message", "Suspended"}
|
||||
if includeNamespace {
|
||||
return append(namespaceHeader, headers...)
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
func (s alertListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
|
||||
item := s.Items[i]
|
||||
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
|
||||
}
|
||||
|
||||
@@ -17,82 +17,75 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
)
|
||||
|
||||
var getAlertProviderCmd = &cobra.Command{
|
||||
Use: "alert-providers",
|
||||
Short: "Get Provider statuses",
|
||||
Long: "The get alert-provider command prints the statuses of the resources.",
|
||||
Use: "alert-providers",
|
||||
Aliases: []string{"alert-provider"},
|
||||
Short: "Get Provider statuses",
|
||||
Long: "The get alert-provider command prints the statuses of the resources.",
|
||||
Example: ` # List all Providers and their status
|
||||
flux get alert-providers
|
||||
`,
|
||||
RunE: getAlertProviderCmdRun,
|
||||
flux get alert-providers`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
get := getCommand{
|
||||
apiType: alertProviderType,
|
||||
list: alertProviderListAdapter{¬ificationv1.ProviderList{}},
|
||||
funcMap: make(typeMap),
|
||||
}
|
||||
|
||||
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
|
||||
o, ok := obj.(*notificationv1.Provider)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Impossible to cast type %#v alert-provider", obj)
|
||||
}
|
||||
|
||||
sink := alertProviderListAdapter{
|
||||
¬ificationv1.ProviderList{
|
||||
Items: []notificationv1.Provider{
|
||||
*o,
|
||||
},
|
||||
},
|
||||
}
|
||||
return sink, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := get.run(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
getCmd.AddCommand(getAlertProviderCmd)
|
||||
}
|
||||
|
||||
func getAlertProviderCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var listOpts []client.ListOption
|
||||
if !getArgs.allNamespaces {
|
||||
listOpts = append(listOpts, client.InNamespace(rootArgs.namespace))
|
||||
}
|
||||
var list notificationv1.ProviderList
|
||||
err = kubeClient.List(ctx, &list, listOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no providers found in %s namespace", rootArgs.namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Ready", "Message"}
|
||||
if getArgs.allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, provider := range list.Items {
|
||||
row := []string{}
|
||||
if c := apimeta.FindStatusCondition(provider.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
provider.GetName(),
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
provider.GetName(),
|
||||
string(metav1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
}
|
||||
}
|
||||
if getArgs.allNamespaces {
|
||||
row = append([]string{provider.Namespace}, row...)
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
utils.PrintTable(os.Stdout, header, rows)
|
||||
return nil
|
||||
func (s alertProviderListAdapter) summariseItem(i int, includeNamespace bool, includeKind bool) []string {
|
||||
item := s.Items[i]
|
||||
status, msg := statusAndMessage(item.Status.Conditions)
|
||||
return append(nameColumns(&item, includeNamespace, includeKind), status, msg)
|
||||
}
|
||||
|
||||
func (s alertProviderListAdapter) headers(includeNamespace bool) []string {
|
||||
headers := []string{"Name", "Ready", "Message"}
|
||||
if includeNamespace {
|
||||
return append(namespaceHeader, headers...)
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
func (s alertProviderListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
|
||||
item := s.Items[i]
|
||||
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
|
||||
}
|
||||
|
||||
96
cmd/flux/get_all.go
Normal file
96
cmd/flux/get_all.go
Normal file
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
Copyright 2021 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var getAllCmd = &cobra.Command{
|
||||
Use: "all",
|
||||
Short: "Get all resources and statuses",
|
||||
Long: "The get all command print the statuses of all resources.",
|
||||
Example: ` # List all resources in a namespace
|
||||
flux get all --namespace=flux-system
|
||||
|
||||
# List all resources in all namespaces
|
||||
flux get all --all-namespaces`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
err := validateWatchOption(cmd, "all")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = getSourceAllCmd.RunE(cmd, args)
|
||||
if err != nil {
|
||||
logError(err)
|
||||
}
|
||||
|
||||
// all get command
|
||||
var allCmd = []getCommand{
|
||||
{
|
||||
apiType: helmReleaseType,
|
||||
list: &helmReleaseListAdapter{&helmv2.HelmReleaseList{}},
|
||||
},
|
||||
{
|
||||
apiType: kustomizationType,
|
||||
list: &kustomizationListAdapter{&kustomizev1.KustomizationList{}},
|
||||
},
|
||||
{
|
||||
apiType: receiverType,
|
||||
list: receiverListAdapter{¬ificationv1.ReceiverList{}},
|
||||
},
|
||||
{
|
||||
apiType: alertProviderType,
|
||||
list: alertProviderListAdapter{¬ificationv1.ProviderList{}},
|
||||
},
|
||||
{
|
||||
apiType: alertType,
|
||||
list: &alertListAdapter{¬ificationv1.AlertList{}},
|
||||
},
|
||||
}
|
||||
|
||||
err = getImageAllCmd.RunE(cmd, args)
|
||||
if err != nil {
|
||||
logError(err)
|
||||
}
|
||||
|
||||
for _, c := range allCmd {
|
||||
if err := c.run(cmd, args); err != nil {
|
||||
logError(err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func logError(err error) {
|
||||
if !strings.Contains(err.Error(), "no matches for kind") {
|
||||
logger.Failuref(err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
getCmd.AddCommand(getAllCmd)
|
||||
}
|
||||
@@ -17,36 +17,63 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
)
|
||||
|
||||
var getHelmReleaseCmd = &cobra.Command{
|
||||
Use: "helmreleases",
|
||||
Aliases: []string{"hr"},
|
||||
Aliases: []string{"hr", "helmrelease"},
|
||||
Short: "Get HelmRelease statuses",
|
||||
Long: "The get helmreleases command prints the statuses of the resources.",
|
||||
Example: ` # List all Helm releases and their status
|
||||
flux get helmreleases
|
||||
`,
|
||||
RunE: getCommand{
|
||||
apiType: helmReleaseType,
|
||||
list: &helmReleaseListAdapter{&helmv2.HelmReleaseList{}},
|
||||
}.run,
|
||||
flux get helmreleases`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
get := getCommand{
|
||||
apiType: helmReleaseType,
|
||||
list: &helmReleaseListAdapter{&helmv2.HelmReleaseList{}},
|
||||
funcMap: make(typeMap),
|
||||
}
|
||||
|
||||
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
|
||||
o, ok := obj.(*helmv2.HelmRelease)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Impossible to cast type %#v helmrelease", obj)
|
||||
}
|
||||
|
||||
sink := helmReleaseListAdapter{&helmv2.HelmReleaseList{
|
||||
Items: []helmv2.HelmRelease{
|
||||
*o,
|
||||
}}}
|
||||
return sink, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := get.run(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
getCmd.AddCommand(getHelmReleaseCmd)
|
||||
}
|
||||
|
||||
func (a helmReleaseListAdapter) summariseItem(i int, includeNamespace bool) []string {
|
||||
func (a helmReleaseListAdapter) summariseItem(i int, includeNamespace bool, includeKind bool) []string {
|
||||
item := a.Items[i]
|
||||
revision := item.Status.LastAppliedRevision
|
||||
status, msg := statusAndMessage(item.Status.Conditions)
|
||||
return append(nameColumns(&item, includeNamespace),
|
||||
return append(nameColumns(&item, includeNamespace, includeKind),
|
||||
status, msg, revision, strings.Title(strconv.FormatBool(item.Spec.Suspend)))
|
||||
}
|
||||
|
||||
@@ -57,3 +84,8 @@ func (a helmReleaseListAdapter) headers(includeNamespace bool) []string {
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
func (a helmReleaseListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
|
||||
item := a.Items[i]
|
||||
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
|
||||
}
|
||||
|
||||
@@ -21,9 +21,13 @@ import (
|
||||
)
|
||||
|
||||
var getImageCmd = &cobra.Command{
|
||||
Use: "image",
|
||||
Short: "Get image automation object status",
|
||||
Long: "The get image sub-commands print the status of image automation objects.",
|
||||
Use: "images",
|
||||
Aliases: []string{"image"},
|
||||
Short: "Get image automation object status",
|
||||
Long: "The get image sub-commands print the status of image automation objects.",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return validateWatchOption(cmd, "images")
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
72
cmd/flux/get_image_all.go
Normal file
72
cmd/flux/get_image_all.go
Normal file
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
Copyright 2021 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var getImageAllCmd = &cobra.Command{
|
||||
Use: "all",
|
||||
Short: "Get all image statuses",
|
||||
Long: "The get image sub-commands print the statuses of all image objects.",
|
||||
Example: ` # List all image objects in a namespace
|
||||
flux get images all --namespace=flux-system
|
||||
|
||||
# List all image objects in all namespaces
|
||||
flux get images all --all-namespaces`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
err := validateWatchOption(cmd, "all")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var allImageCmd = []getCommand{
|
||||
{
|
||||
apiType: imageRepositoryType,
|
||||
list: imageRepositoryListAdapter{&imagev1.ImageRepositoryList{}},
|
||||
},
|
||||
{
|
||||
apiType: imagePolicyType,
|
||||
list: &imagePolicyListAdapter{&imagev1.ImagePolicyList{}},
|
||||
},
|
||||
{
|
||||
apiType: imageUpdateAutomationType,
|
||||
list: &imageUpdateAutomationListAdapter{&autov1.ImageUpdateAutomationList{}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, c := range allImageCmd {
|
||||
if err := c.run(cmd, args); err != nil {
|
||||
if !strings.Contains(err.Error(), "no matches for kind") {
|
||||
logger.Failuref(err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
getImageCmd.AddCommand(getImageAllCmd)
|
||||
}
|
||||
@@ -17,9 +17,12 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
"fmt"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var getImagePolicyCmd = &cobra.Command{
|
||||
@@ -30,22 +33,47 @@ var getImagePolicyCmd = &cobra.Command{
|
||||
flux get image policy
|
||||
|
||||
# List image policies from all namespaces
|
||||
flux get image policy --all-namespaces
|
||||
`,
|
||||
RunE: getCommand{
|
||||
apiType: imagePolicyType,
|
||||
list: &imagePolicyListAdapter{&imagev1.ImagePolicyList{}},
|
||||
}.run,
|
||||
flux get image policy --all-namespaces`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
get := getCommand{
|
||||
apiType: imagePolicyType,
|
||||
list: &imagePolicyListAdapter{&imagev1.ImagePolicyList{}},
|
||||
funcMap: make(typeMap),
|
||||
}
|
||||
|
||||
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
|
||||
o, ok := obj.(*imagev1.ImagePolicy)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Impossible to cast type %#v policy", obj)
|
||||
}
|
||||
|
||||
sink := imagePolicyListAdapter{&imagev1.ImagePolicyList{
|
||||
Items: []imagev1.ImagePolicy{
|
||||
*o,
|
||||
}}}
|
||||
return sink, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := get.run(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
getImageCmd.AddCommand(getImagePolicyCmd)
|
||||
}
|
||||
|
||||
func (s imagePolicyListAdapter) summariseItem(i int, includeNamespace bool) []string {
|
||||
func (s imagePolicyListAdapter) summariseItem(i int, includeNamespace bool, includeKind bool) []string {
|
||||
item := s.Items[i]
|
||||
status, msg := statusAndMessage(item.Status.Conditions)
|
||||
return append(nameColumns(&item, includeNamespace), status, msg, item.Status.LatestImage)
|
||||
return append(nameColumns(&item, includeNamespace, includeKind), status, msg, item.Status.LatestImage)
|
||||
}
|
||||
|
||||
func (s imagePolicyListAdapter) headers(includeNamespace bool) []string {
|
||||
@@ -55,3 +83,8 @@ func (s imagePolicyListAdapter) headers(includeNamespace bool) []string {
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
func (s imagePolicyListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
|
||||
item := s.Items[i]
|
||||
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
|
||||
}
|
||||
|
||||
@@ -17,13 +17,15 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1alpha1"
|
||||
imagev1 "github.com/fluxcd/image-reflector-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var getImageRepositoryCmd = &cobra.Command{
|
||||
@@ -34,26 +36,51 @@ var getImageRepositoryCmd = &cobra.Command{
|
||||
flux get image repository
|
||||
|
||||
# List image repositories from all namespaces
|
||||
flux get image repository --all-namespaces
|
||||
`,
|
||||
RunE: getCommand{
|
||||
apiType: imageRepositoryType,
|
||||
list: imageRepositoryListAdapter{&imagev1.ImageRepositoryList{}},
|
||||
}.run,
|
||||
flux get image repository --all-namespaces`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
get := getCommand{
|
||||
apiType: imageRepositoryType,
|
||||
list: imageRepositoryListAdapter{&imagev1.ImageRepositoryList{}},
|
||||
funcMap: make(typeMap),
|
||||
}
|
||||
|
||||
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
|
||||
o, ok := obj.(*imagev1.ImageRepository)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Impossible to cast type %#v repository", obj)
|
||||
}
|
||||
|
||||
sink := imageRepositoryListAdapter{&imagev1.ImageRepositoryList{
|
||||
Items: []imagev1.ImageRepository{
|
||||
*o,
|
||||
}}}
|
||||
return sink, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := get.run(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
getImageCmd.AddCommand(getImageRepositoryCmd)
|
||||
}
|
||||
|
||||
func (s imageRepositoryListAdapter) summariseItem(i int, includeNamespace bool) []string {
|
||||
func (s imageRepositoryListAdapter) summariseItem(i int, includeNamespace bool, includeKind bool) []string {
|
||||
item := s.Items[i]
|
||||
status, msg := statusAndMessage(item.Status.Conditions)
|
||||
var lastScan string
|
||||
if item.Status.LastScanResult != nil {
|
||||
lastScan = item.Status.LastScanResult.ScanTime.Time.Format(time.RFC3339)
|
||||
}
|
||||
return append(nameColumns(&item, includeNamespace),
|
||||
return append(nameColumns(&item, includeNamespace, includeKind),
|
||||
status, msg, lastScan, strings.Title(strconv.FormatBool(item.Spec.Suspend)))
|
||||
}
|
||||
|
||||
@@ -64,3 +91,8 @@ func (s imageRepositoryListAdapter) headers(includeNamespace bool) []string {
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
func (s imageRepositoryListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
|
||||
item := s.Items[i]
|
||||
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
|
||||
}
|
||||
|
||||
@@ -17,13 +17,15 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1alpha1"
|
||||
autov1 "github.com/fluxcd/image-automation-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var getImageUpdateCmd = &cobra.Command{
|
||||
@@ -34,26 +36,51 @@ var getImageUpdateCmd = &cobra.Command{
|
||||
flux get image update
|
||||
|
||||
# List image update automations from all namespaces
|
||||
flux get image update --all-namespaces
|
||||
`,
|
||||
RunE: getCommand{
|
||||
apiType: imageUpdateAutomationType,
|
||||
list: &imageUpdateAutomationListAdapter{&autov1.ImageUpdateAutomationList{}},
|
||||
}.run,
|
||||
flux get image update --all-namespaces`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
get := getCommand{
|
||||
apiType: imageUpdateAutomationType,
|
||||
list: &imageUpdateAutomationListAdapter{&autov1.ImageUpdateAutomationList{}},
|
||||
funcMap: make(typeMap),
|
||||
}
|
||||
|
||||
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
|
||||
o, ok := obj.(*autov1.ImageUpdateAutomation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Impossible to cast type %#v update", obj)
|
||||
}
|
||||
|
||||
sink := imageUpdateAutomationListAdapter{&autov1.ImageUpdateAutomationList{
|
||||
Items: []autov1.ImageUpdateAutomation{
|
||||
*o,
|
||||
}}}
|
||||
return sink, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := get.run(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
getImageCmd.AddCommand(getImageUpdateCmd)
|
||||
}
|
||||
|
||||
func (s imageUpdateAutomationListAdapter) summariseItem(i int, includeNamespace bool) []string {
|
||||
func (s imageUpdateAutomationListAdapter) summariseItem(i int, includeNamespace bool, includeKind bool) []string {
|
||||
item := s.Items[i]
|
||||
status, msg := statusAndMessage(item.Status.Conditions)
|
||||
var lastRun string
|
||||
if item.Status.LastAutomationRunTime != nil {
|
||||
lastRun = item.Status.LastAutomationRunTime.Time.Format(time.RFC3339)
|
||||
}
|
||||
return append(nameColumns(&item, includeNamespace), status, msg, lastRun, strings.Title(strconv.FormatBool(item.Spec.Suspend)))
|
||||
return append(nameColumns(&item, includeNamespace, includeKind), status, msg, lastRun, strings.Title(strconv.FormatBool(item.Spec.Suspend)))
|
||||
}
|
||||
|
||||
func (s imageUpdateAutomationListAdapter) headers(includeNamespace bool) []string {
|
||||
@@ -63,3 +90,8 @@ func (s imageUpdateAutomationListAdapter) headers(includeNamespace bool) []strin
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
func (s imageUpdateAutomationListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
|
||||
item := s.Items[i]
|
||||
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
|
||||
}
|
||||
@@ -17,36 +17,67 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var getKsCmd = &cobra.Command{
|
||||
Use: "kustomizations",
|
||||
Aliases: []string{"ks"},
|
||||
Aliases: []string{"ks", "kustomization"},
|
||||
Short: "Get Kustomization statuses",
|
||||
Long: "The get kustomizations command prints the statuses of the resources.",
|
||||
Example: ` # List all kustomizations and their status
|
||||
flux get kustomizations
|
||||
`,
|
||||
RunE: getCommand{
|
||||
apiType: kustomizationType,
|
||||
list: &kustomizationListAdapter{&kustomizev1.KustomizationList{}},
|
||||
}.run,
|
||||
flux get kustomizations`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
get := getCommand{
|
||||
apiType: kustomizationType,
|
||||
list: &kustomizationListAdapter{&kustomizev1.KustomizationList{}},
|
||||
funcMap: make(typeMap),
|
||||
}
|
||||
|
||||
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
|
||||
o, ok := obj.(*kustomizev1.Kustomization)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Impossible to cast type %#v kustomization", obj)
|
||||
}
|
||||
|
||||
sink := kustomizationListAdapter{
|
||||
&kustomizev1.KustomizationList{
|
||||
Items: []kustomizev1.Kustomization{
|
||||
*o,
|
||||
},
|
||||
},
|
||||
}
|
||||
return sink, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := get.run(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
getCmd.AddCommand(getKsCmd)
|
||||
}
|
||||
|
||||
func (a kustomizationListAdapter) summariseItem(i int, includeNamespace bool) []string {
|
||||
func (a kustomizationListAdapter) summariseItem(i int, includeNamespace bool, includeKind bool) []string {
|
||||
item := a.Items[i]
|
||||
revision := item.Status.LastAppliedRevision
|
||||
status, msg := statusAndMessage(item.Status.Conditions)
|
||||
return append(nameColumns(&item, includeNamespace),
|
||||
return append(nameColumns(&item, includeNamespace, includeKind),
|
||||
status, msg, revision, strings.Title(strconv.FormatBool(item.Spec.Suspend)))
|
||||
}
|
||||
|
||||
@@ -57,3 +88,8 @@ func (a kustomizationListAdapter) headers(includeNamespace bool) []string {
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
func (a kustomizationListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
|
||||
item := a.Items[i]
|
||||
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
|
||||
}
|
||||
|
||||
@@ -17,83 +17,74 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
apimeta "k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
)
|
||||
|
||||
var getReceiverCmd = &cobra.Command{
|
||||
Use: "receivers",
|
||||
Short: "Get Receiver statuses",
|
||||
Long: "The get receiver command prints the statuses of the resources.",
|
||||
Use: "receivers",
|
||||
Aliases: []string{"receiver"},
|
||||
Short: "Get Receiver statuses",
|
||||
Long: "The get receiver command prints the statuses of the resources.",
|
||||
Example: ` # List all Receiver and their status
|
||||
flux get receivers
|
||||
`,
|
||||
RunE: getReceiverCmdRun,
|
||||
flux get receivers`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
get := getCommand{
|
||||
apiType: receiverType,
|
||||
list: receiverListAdapter{¬ificationv1.ReceiverList{}},
|
||||
funcMap: make(typeMap),
|
||||
}
|
||||
|
||||
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
|
||||
o, ok := obj.(*notificationv1.Receiver)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Impossible to cast type %#v receiver", obj)
|
||||
}
|
||||
|
||||
sink := receiverListAdapter{¬ificationv1.ReceiverList{
|
||||
Items: []notificationv1.Receiver{
|
||||
*o,
|
||||
}}}
|
||||
return sink, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := get.run(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
getCmd.AddCommand(getReceiverCmd)
|
||||
}
|
||||
|
||||
func getReceiverCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rootArgs.timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(rootArgs.kubeconfig, rootArgs.kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var listOpts []client.ListOption
|
||||
if !getArgs.allNamespaces {
|
||||
listOpts = append(listOpts, client.InNamespace(rootArgs.namespace))
|
||||
}
|
||||
var list notificationv1.ReceiverList
|
||||
err = kubeClient.List(ctx, &list, listOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no receivers found in %s namespace", rootArgs.namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Ready", "Message", "Suspended"}
|
||||
if getArgs.allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, receiver := range list.Items {
|
||||
row := []string{}
|
||||
if c := apimeta.FindStatusCondition(receiver.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
receiver.GetName(),
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
strings.Title(strconv.FormatBool(receiver.Spec.Suspend)),
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
receiver.GetName(),
|
||||
string(metav1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
strings.Title(strconv.FormatBool(receiver.Spec.Suspend)),
|
||||
}
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
utils.PrintTable(os.Stdout, header, rows)
|
||||
return nil
|
||||
func (s receiverListAdapter) summariseItem(i int, includeNamespace bool, includeKind bool) []string {
|
||||
item := s.Items[i]
|
||||
status, msg := statusAndMessage(item.Status.Conditions)
|
||||
return append(nameColumns(&item, includeNamespace, includeKind), status, msg, strings.Title(strconv.FormatBool(item.Spec.Suspend)))
|
||||
}
|
||||
|
||||
func (s receiverListAdapter) headers(includeNamespace bool) []string {
|
||||
headers := []string{"Name", "Ready", "Message", "Suspended"}
|
||||
if includeNamespace {
|
||||
return append(namespaceHeader, headers...)
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
func (s receiverListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
|
||||
item := s.Items[i]
|
||||
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
|
||||
}
|
||||
|
||||
@@ -21,9 +21,14 @@ import (
|
||||
)
|
||||
|
||||
var getSourceCmd = &cobra.Command{
|
||||
Use: "sources",
|
||||
Short: "Get source statuses",
|
||||
Long: "The get source sub-commands print the statuses of the sources.",
|
||||
Use: "sources",
|
||||
Aliases: []string{"source"},
|
||||
Short: "Get source statuses",
|
||||
Long: "The get source sub-commands print the statuses of the sources.",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
|
||||
return validateWatchOption(cmd, "sources")
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
75
cmd/flux/get_source_all.go
Normal file
75
cmd/flux/get_source_all.go
Normal file
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
Copyright 2021 The Flux authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var getSourceAllCmd = &cobra.Command{
|
||||
Use: "all",
|
||||
Short: "Get all source statuses",
|
||||
Long: "The get sources all command print the statuses of all sources.",
|
||||
Example: ` # List all sources in a namespace
|
||||
flux get sources all --namespace=flux-system
|
||||
|
||||
# List all sources in all namespaces
|
||||
flux get sources all --all-namespaces`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
err := validateWatchOption(cmd, "all")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var allSourceCmd = []getCommand{
|
||||
{
|
||||
apiType: bucketType,
|
||||
list: &bucketListAdapter{&sourcev1.BucketList{}},
|
||||
},
|
||||
{
|
||||
apiType: gitRepositoryType,
|
||||
list: &gitRepositoryListAdapter{&sourcev1.GitRepositoryList{}},
|
||||
},
|
||||
{
|
||||
apiType: helmRepositoryType,
|
||||
list: &helmRepositoryListAdapter{&sourcev1.HelmRepositoryList{}},
|
||||
},
|
||||
{
|
||||
apiType: helmChartType,
|
||||
list: &helmChartListAdapter{&sourcev1.HelmChartList{}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, c := range allSourceCmd {
|
||||
if err := c.run(cmd, args); err != nil {
|
||||
if !strings.Contains(err.Error(), "no matches for kind") {
|
||||
logger.Failuref(err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
getSourceCmd.AddCommand(getSourceAllCmd)
|
||||
}
|
||||
@@ -17,11 +17,14 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var getSourceBucketCmd = &cobra.Command{
|
||||
@@ -32,26 +35,51 @@ var getSourceBucketCmd = &cobra.Command{
|
||||
flux get sources bucket
|
||||
|
||||
# List buckets from all namespaces
|
||||
flux get sources helm --all-namespaces
|
||||
`,
|
||||
RunE: getCommand{
|
||||
apiType: bucketType,
|
||||
list: &bucketListAdapter{&sourcev1.BucketList{}},
|
||||
}.run,
|
||||
flux get sources helm --all-namespaces`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
get := getCommand{
|
||||
apiType: bucketType,
|
||||
list: &bucketListAdapter{&sourcev1.BucketList{}},
|
||||
funcMap: make(typeMap),
|
||||
}
|
||||
|
||||
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
|
||||
o, ok := obj.(*sourcev1.Bucket)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Impossible to cast type %#v bucket", obj)
|
||||
}
|
||||
|
||||
sink := &bucketListAdapter{&sourcev1.BucketList{
|
||||
Items: []sourcev1.Bucket{
|
||||
*o,
|
||||
}}}
|
||||
return sink, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := get.run(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
getSourceCmd.AddCommand(getSourceBucketCmd)
|
||||
}
|
||||
|
||||
func (a *bucketListAdapter) summariseItem(i int, includeNamespace bool) []string {
|
||||
func (a *bucketListAdapter) summariseItem(i int, includeNamespace bool, includeKind bool) []string {
|
||||
item := a.Items[i]
|
||||
var revision string
|
||||
if item.GetArtifact() != nil {
|
||||
revision = item.GetArtifact().Revision
|
||||
}
|
||||
status, msg := statusAndMessage(item.Status.Conditions)
|
||||
return append(nameColumns(&item, includeNamespace),
|
||||
return append(nameColumns(&item, includeNamespace, includeKind),
|
||||
status, msg, revision, strings.Title(strconv.FormatBool(item.Spec.Suspend)))
|
||||
}
|
||||
|
||||
@@ -62,3 +90,8 @@ func (a bucketListAdapter) headers(includeNamespace bool) []string {
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
func (a bucketListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
|
||||
item := a.Items[i]
|
||||
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
|
||||
}
|
||||
|
||||
@@ -17,11 +17,14 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var getSourceHelmChartCmd = &cobra.Command{
|
||||
@@ -32,26 +35,51 @@ var getSourceHelmChartCmd = &cobra.Command{
|
||||
flux get sources chart
|
||||
|
||||
# List Helm charts from all namespaces
|
||||
flux get sources chart --all-namespaces
|
||||
`,
|
||||
RunE: getCommand{
|
||||
apiType: helmChartType,
|
||||
list: &helmChartListAdapter{&sourcev1.HelmChartList{}},
|
||||
}.run,
|
||||
flux get sources chart --all-namespaces`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
get := getCommand{
|
||||
apiType: helmChartType,
|
||||
list: &helmChartListAdapter{&sourcev1.HelmChartList{}},
|
||||
funcMap: make(typeMap),
|
||||
}
|
||||
|
||||
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
|
||||
o, ok := obj.(*sourcev1.HelmChart)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Impossible to cast type %#v chart", obj)
|
||||
}
|
||||
|
||||
sink := &helmChartListAdapter{&sourcev1.HelmChartList{
|
||||
Items: []sourcev1.HelmChart{
|
||||
*o,
|
||||
}}}
|
||||
return sink, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := get.run(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
getSourceCmd.AddCommand(getSourceHelmChartCmd)
|
||||
}
|
||||
|
||||
func (a *helmChartListAdapter) summariseItem(i int, includeNamespace bool) []string {
|
||||
func (a *helmChartListAdapter) summariseItem(i int, includeNamespace bool, includeKind bool) []string {
|
||||
item := a.Items[i]
|
||||
var revision string
|
||||
if item.GetArtifact() != nil {
|
||||
revision = item.GetArtifact().Revision
|
||||
}
|
||||
status, msg := statusAndMessage(item.Status.Conditions)
|
||||
return append(nameColumns(&item, includeNamespace),
|
||||
return append(nameColumns(&item, includeNamespace, includeKind),
|
||||
status, msg, revision, strings.Title(strconv.FormatBool(item.Spec.Suspend)))
|
||||
}
|
||||
|
||||
@@ -62,3 +90,8 @@ func (a helmChartListAdapter) headers(includeNamespace bool) []string {
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
func (a helmChartListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
|
||||
item := a.Items[i]
|
||||
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
|
||||
}
|
||||
|
||||
@@ -17,11 +17,14 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var getSourceGitCmd = &cobra.Command{
|
||||
@@ -32,26 +35,51 @@ var getSourceGitCmd = &cobra.Command{
|
||||
flux get sources git
|
||||
|
||||
# List Git repositories from all namespaces
|
||||
flux get sources git --all-namespaces
|
||||
`,
|
||||
RunE: getCommand{
|
||||
apiType: gitRepositoryType,
|
||||
list: &gitRepositoryListAdapter{&sourcev1.GitRepositoryList{}},
|
||||
}.run,
|
||||
flux get sources git --all-namespaces`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
get := getCommand{
|
||||
apiType: gitRepositoryType,
|
||||
list: &gitRepositoryListAdapter{&sourcev1.GitRepositoryList{}},
|
||||
funcMap: make(typeMap),
|
||||
}
|
||||
|
||||
err := get.funcMap.registerCommand(get.apiType.kind, func(obj runtime.Object) (summarisable, error) {
|
||||
o, ok := obj.(*sourcev1.GitRepository)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Impossible to cast type %#v git", obj)
|
||||
}
|
||||
|
||||
sink := &gitRepositoryListAdapter{&sourcev1.GitRepositoryList{
|
||||
Items: []sourcev1.GitRepository{
|
||||
*o,
|
||||
}}}
|
||||
return sink, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := get.run(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
getSourceCmd.AddCommand(getSourceGitCmd)
|
||||
}
|
||||
|
||||
func (a *gitRepositoryListAdapter) summariseItem(i int, includeNamespace bool) []string {
|
||||
func (a *gitRepositoryListAdapter) summariseItem(i int, includeNamespace bool, includeKind bool) []string {
|
||||
item := a.Items[i]
|
||||
var revision string
|
||||
if item.GetArtifact() != nil {
|
||||
revision = item.GetArtifact().Revision
|
||||
}
|
||||
status, msg := statusAndMessage(item.Status.Conditions)
|
||||
return append(nameColumns(&item, includeNamespace),
|
||||
return append(nameColumns(&item, includeNamespace, includeKind),
|
||||
status, msg, revision, strings.Title(strconv.FormatBool(item.Spec.Suspend)))
|
||||
}
|
||||
|
||||
@@ -62,3 +90,8 @@ func (a gitRepositoryListAdapter) headers(includeNamespace bool) []string {
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
func (a gitRepositoryListAdapter) statusSelectorMatches(i int, conditionType, conditionStatus string) bool {
|
||||
item := a.Items[i]
|
||||
return statusMatches(conditionType, conditionStatus, item.Status.Conditions)
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user