Compare commits
459 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d500cc0bd1 | ||
|
|
71995b4f83 | ||
|
|
932c91d022 | ||
|
|
107e7424d1 | ||
|
|
c93181c0ad | ||
|
|
050fca6767 | ||
|
|
71827b4a1a | ||
|
|
1d0315bf5e | ||
|
|
b2b64e7283 | ||
|
|
fe0e2edd37 | ||
|
|
e5bb3d5645 | ||
|
|
b88a99347b | ||
|
|
344a909d19 | ||
|
|
3cbe3aab25 | ||
|
|
9e3a4b1810 | ||
|
|
e855bbaa29 | ||
|
|
78d7dca985 | ||
|
|
9da7ded976 | ||
|
|
427b107d0e | ||
|
|
1cab68e385 | ||
|
|
07e4fa8abd | ||
|
|
77b86c78a4 | ||
|
|
e4c701864a | ||
|
|
0275f28490 | ||
|
|
300c3dd578 | ||
|
|
fb81870803 | ||
|
|
bb6a61a313 | ||
|
|
976d917a57 | ||
|
|
7e13cc2ca8 | ||
|
|
704296df4e | ||
|
|
65244e3b8d | ||
|
|
3cf54a4cce | ||
|
|
031c09d8dc | ||
|
|
5209d9cf75 | ||
|
|
815dad18f4 | ||
|
|
4319382da3 | ||
|
|
5e96cec95b | ||
|
|
071982097a | ||
|
|
56024de6cc | ||
|
|
845d4acd8e | ||
|
|
b0029e9255 | ||
|
|
23bc44a350 | ||
|
|
0bf52f4746 | ||
|
|
345707e6cc | ||
|
|
e2752e4508 | ||
|
|
9916a53761 | ||
|
|
4581c99a81 | ||
|
|
c3fdc41a91 | ||
|
|
edf2f51aa1 | ||
|
|
de944d0095 | ||
|
|
49ffc972f8 | ||
|
|
2d8e5b2420 | ||
|
|
7c48975198 | ||
|
|
9bc250d027 | ||
|
|
41d4e7e15b | ||
|
|
b0d2a38ff6 | ||
|
|
bd4d4d927e | ||
|
|
db17cacbf4 | ||
|
|
0c5961df98 | ||
|
|
0e67b76b57 | ||
|
|
f72b323ab5 | ||
|
|
927c21a60f | ||
|
|
624a9ba8eb | ||
|
|
8509283ac2 | ||
|
|
aa9ba27f40 | ||
|
|
06434464bb | ||
|
|
3e7bfc72a2 | ||
|
|
8dfbc35e60 | ||
|
|
503e5ec950 | ||
|
|
414aeb0ac3 | ||
|
|
55b8544d32 | ||
|
|
2d67ea5f7f | ||
|
|
4eaf72fa3e | ||
|
|
95ef3c1782 | ||
|
|
b3ef410fb7 | ||
|
|
0c55bca218 | ||
|
|
5fd28439dc | ||
|
|
a58c18e992 | ||
|
|
058dfdfcd6 | ||
|
|
637fdac28a | ||
|
|
a8b667780a | ||
|
|
b4f13e10d3 | ||
|
|
d0eb55fb86 | ||
|
|
b041dbd14f | ||
|
|
0ab814fbc4 | ||
|
|
a2144b1759 | ||
|
|
82eb3b5ccf | ||
|
|
7515080c63 | ||
|
|
07015c5172 | ||
|
|
19918cd342 | ||
|
|
16f0ed548e | ||
|
|
0d1600275d | ||
|
|
768f32bd2d | ||
|
|
d86798a7c6 | ||
|
|
7718c6a2a5 | ||
|
|
a0616ac2cb | ||
|
|
23bbe0d52b | ||
|
|
6d9e7758a2 | ||
|
|
f81a80c2da | ||
|
|
ab64619a41 | ||
|
|
18bdd26be8 | ||
|
|
c5f3a674d6 | ||
|
|
f95e17b144 | ||
|
|
4989826124 | ||
|
|
f23a551ae3 | ||
|
|
bd2df01b12 | ||
|
|
880ef303e8 | ||
|
|
b4ed1a0bdc | ||
|
|
7a2eae0699 | ||
|
|
4464252cae | ||
|
|
ca8cf44200 | ||
|
|
4565165579 | ||
|
|
a37be432a9 | ||
|
|
90591e852d | ||
|
|
13f7d44a06 | ||
|
|
7dc8aa66a6 | ||
|
|
6cf28ab718 | ||
|
|
f461c5e8b7 | ||
|
|
9433bdf4ad | ||
|
|
d2d494e079 | ||
|
|
e64b35cde8 | ||
|
|
d32e8c6e98 | ||
|
|
55cee488bc | ||
|
|
65b8942416 | ||
|
|
94cf7c329c | ||
|
|
8eac7d6b4d | ||
|
|
7ebb34de80 | ||
|
|
6ea84906ac | ||
|
|
f7971a871a | ||
|
|
54b35b7c2b | ||
|
|
ca970b4ffb | ||
|
|
8a96e32679 | ||
|
|
fc4d01b3e5 | ||
|
|
b6afc8f6ce | ||
|
|
c481a431be | ||
|
|
0a7b82793e | ||
|
|
3653236bcb | ||
|
|
a2eee72015 | ||
|
|
5672646278 | ||
|
|
c4d3fa7a48 | ||
|
|
32b0267b9f | ||
|
|
a7b41a4b8c | ||
|
|
bfd6d14bf3 | ||
|
|
469de31218 | ||
|
|
2ce9823b3a | ||
|
|
e8b3d09ddf | ||
|
|
f613c01803 | ||
|
|
a5a5908fb5 | ||
|
|
5313a0ed47 | ||
|
|
1c15eebd7c | ||
|
|
f3cab6e177 | ||
|
|
c0623334ee | ||
|
|
d41bd6b6b1 | ||
|
|
c9b4a8eef5 | ||
|
|
3619cb8bd1 | ||
|
|
8e2316ba62 | ||
|
|
495abf42ef | ||
|
|
5372dd633e | ||
|
|
5efa1ebe88 | ||
|
|
07677ed4a7 | ||
|
|
73e5640109 | ||
|
|
bdbded8588 | ||
|
|
e0fbf8920d | ||
|
|
7b2227bfac | ||
|
|
12866ca7ba | ||
|
|
1427b1537e | ||
|
|
6ceb133bb5 | ||
|
|
4ab67aaf90 | ||
|
|
6cce0a3901 | ||
|
|
fa67789350 | ||
|
|
16adeb1373 | ||
|
|
29c1cf1237 | ||
|
|
0e52065893 | ||
|
|
3972c08efc | ||
|
|
1a679ee05d | ||
|
|
b2286055b0 | ||
|
|
249d0d43de | ||
|
|
536630cbcd | ||
|
|
70d0bfce15 | ||
|
|
84e36ed847 | ||
|
|
3d4ff687b5 | ||
|
|
edddf65d0e | ||
|
|
f216273008 | ||
|
|
3295ef4fcf | ||
|
|
4ea0e04852 | ||
|
|
414c0b3a8d | ||
|
|
ff6a1c14be | ||
|
|
0e1a862e34 | ||
|
|
d902c71a6f | ||
|
|
b3f6d5206a | ||
|
|
ff0d80e84f | ||
|
|
cf080330ba | ||
|
|
2373bacb0c | ||
|
|
938edefea1 | ||
|
|
393be92632 | ||
|
|
267440142e | ||
|
|
d11fa476e1 | ||
|
|
bd2994f9ab | ||
|
|
2806feb468 | ||
|
|
8e40069e67 | ||
|
|
24d7d8dcc4 | ||
|
|
34147d7694 | ||
|
|
83bd245bfd | ||
|
|
a02452ccb9 | ||
|
|
a8f72564f4 | ||
|
|
6e7b311696 | ||
|
|
2bda0eb761 | ||
|
|
c2661fb79e | ||
|
|
4e70fd704b | ||
|
|
85d03a9946 | ||
|
|
1c7994a353 | ||
|
|
347c2b6bcc | ||
|
|
19d9953a48 | ||
|
|
7b4e815a8d | ||
|
|
59011c9517 | ||
|
|
39d5c9e525 | ||
|
|
e6d553c8ff | ||
|
|
fecd777d30 | ||
|
|
ce64b1fc09 | ||
|
|
857e442376 | ||
|
|
b0e407bf30 | ||
|
|
cad64ba044 | ||
|
|
85801f18ae | ||
|
|
f93a40a18b | ||
|
|
9b0c44162a | ||
|
|
a66ac1594b | ||
|
|
101e7bbce0 | ||
|
|
0e969bbaad | ||
|
|
621b4c8213 | ||
|
|
8ca6e44de7 | ||
|
|
8ee2c972d3 | ||
|
|
fafcf09570 | ||
|
|
0b14328024 | ||
|
|
2d2b24f589 | ||
|
|
346d8f7583 | ||
|
|
2096532f5d | ||
|
|
4136eb1444 | ||
|
|
67e0acd044 | ||
|
|
cbcdfc5f6c | ||
|
|
288d952686 | ||
|
|
c36e02bba9 | ||
|
|
c121a4c0f5 | ||
|
|
2bac5aabee | ||
|
|
97ff225bc0 | ||
|
|
d5e78b9f80 | ||
|
|
3f98affd5a | ||
|
|
531c2bcf00 | ||
|
|
dd5505918a | ||
|
|
4a30a69eb4 | ||
|
|
38b302e5a5 | ||
|
|
ea010895a0 | ||
|
|
7b88512698 | ||
|
|
1ff24d9285 | ||
|
|
ebf742d272 | ||
|
|
a7b1b04920 | ||
|
|
1218d6abe8 | ||
|
|
f9d546676b | ||
|
|
afef6960b9 | ||
|
|
f6626b8975 | ||
|
|
b1e66f81ab | ||
|
|
9cc018e618 | ||
|
|
797cd9bea2 | ||
|
|
9dbfca3d7a | ||
|
|
f18d1efdcb | ||
|
|
29a9b89224 | ||
|
|
11b5b9808b | ||
|
|
ca1f84d22b | ||
|
|
d6c6c88e6e | ||
|
|
ee33702463 | ||
|
|
8b6995e9ec | ||
|
|
36ba8f0fcb | ||
|
|
bfb560ec50 | ||
|
|
78bb11dcbf | ||
|
|
5c8d00665f | ||
|
|
f4d78cc08e | ||
|
|
2aa395ba12 | ||
|
|
ac862e6822 | ||
|
|
1b55ead16e | ||
|
|
b24727ec22 | ||
|
|
2768926683 | ||
|
|
3f07bd6471 | ||
|
|
2f861f19c0 | ||
|
|
6b397cff73 | ||
|
|
44a3cf86d3 | ||
|
|
dfb0a40293 | ||
|
|
7719dd378b | ||
|
|
c9f8e43681 | ||
|
|
4a7538041d | ||
|
|
dd3b2288e2 | ||
|
|
496abc3a98 | ||
|
|
8b9abfb26e | ||
|
|
330e21e2ba | ||
|
|
e53d0dadbf | ||
|
|
fa56685767 | ||
|
|
2727f4b92d | ||
|
|
0f74f65af8 | ||
|
|
8e03968370 | ||
|
|
969f181f3e | ||
|
|
cc18077192 | ||
|
|
47d07b2326 | ||
|
|
a96bb72fb8 | ||
|
|
75364dd5b4 | ||
|
|
22624ae4d5 | ||
|
|
cb23d3ff3c | ||
|
|
e751bdc8a9 | ||
|
|
2078d048a1 | ||
|
|
22ff25269d | ||
|
|
1ee9a6a39d | ||
|
|
50efd865d9 | ||
|
|
d688d3837f | ||
|
|
6cb438440d | ||
|
|
2c5771d9e8 | ||
|
|
0ce06116e6 | ||
|
|
706bc0fdfe | ||
|
|
0b5b1ba11a | ||
|
|
0ed8ca961e | ||
|
|
31d4b62bf3 | ||
|
|
35d6172d06 | ||
|
|
b5ed8f0183 | ||
|
|
7cb3bb0d4e | ||
|
|
d27d42d9ca | ||
|
|
e2fd6e8f86 | ||
|
|
a8e534a8a4 | ||
|
|
479d7575fa | ||
|
|
4707a3075e | ||
|
|
21a189e0b7 | ||
|
|
ab7ff6551f | ||
|
|
248961d58c | ||
|
|
473e226883 | ||
|
|
2ebb06d330 | ||
|
|
cc88e68c4e | ||
|
|
f8704747d9 | ||
|
|
0c33df883c | ||
|
|
3fbc396bc8 | ||
|
|
17df7a46e2 | ||
|
|
925c1d3d8e | ||
|
|
1976d4cc1b | ||
|
|
d98578f260 | ||
|
|
8d1dddf205 | ||
|
|
2584b6ca5b | ||
|
|
70897cebfe | ||
|
|
0e80cd5c44 | ||
|
|
b979e313b2 | ||
|
|
533cb42d29 | ||
|
|
35a209903e | ||
|
|
824de61579 | ||
|
|
17ca3f8ac2 | ||
|
|
87a299736e | ||
|
|
e86286722a | ||
|
|
c4a0724c8d | ||
|
|
17139f34dd | ||
|
|
1779714b0d | ||
|
|
1ff4495737 | ||
|
|
02c0dc1217 | ||
|
|
fb43c194b9 | ||
|
|
ae94bb56d9 | ||
|
|
123433c4ea | ||
|
|
58619076ea | ||
|
|
a50d1c5784 | ||
|
|
91c8cb197f | ||
|
|
427c60618f | ||
|
|
2d417f200d | ||
|
|
54b11e7b25 | ||
|
|
50d2eb7d57 | ||
|
|
dfb20dd1ca | ||
|
|
4f22016f13 | ||
|
|
430a2d0454 | ||
|
|
db23c8ce9f | ||
|
|
ffd4784916 | ||
|
|
750830c302 | ||
|
|
d245ef9b39 | ||
|
|
c8586d1ef4 | ||
|
|
316cba1cb8 | ||
|
|
13dba62b8d | ||
|
|
c2ff169c08 | ||
|
|
57a1dbfc6d | ||
|
|
efb39d6fc6 | ||
|
|
b784234430 | ||
|
|
aebad92426 | ||
|
|
8e67cfd5c9 | ||
|
|
10cc6d7e08 | ||
|
|
83c236c829 | ||
|
|
b6ab37691f | ||
|
|
c85af78025 | ||
|
|
2c2fc6dd97 | ||
|
|
3620b76139 | ||
|
|
ca5732e586 | ||
|
|
2463d72f3b | ||
|
|
d6f7474200 | ||
|
|
0b2bc7ab3f | ||
|
|
0a4fac61d4 | ||
|
|
797aec5528 | ||
|
|
5f0b95dc59 | ||
|
|
b384c5f14c | ||
|
|
5254dca9d9 | ||
|
|
8534ccbf37 | ||
|
|
9af874d810 | ||
|
|
4e3dee15ce | ||
|
|
aaad618e20 | ||
|
|
10bb50bd82 | ||
|
|
6d2ff6e019 | ||
|
|
670070a879 | ||
|
|
dcec8007d4 | ||
|
|
3abf4a49cd | ||
|
|
38825bf96a | ||
|
|
faa69da28d | ||
|
|
5cf524e2fd | ||
|
|
88802a44e7 | ||
|
|
94498d862d | ||
|
|
9418b24e8f | ||
|
|
b92cbcd7e7 | ||
|
|
9ef2ff92df | ||
|
|
422724bd2d | ||
|
|
6cb7897f25 | ||
|
|
499ba15004 | ||
|
|
b04abe989e | ||
|
|
ea576179f9 | ||
|
|
116d53a978 | ||
|
|
32adbf2ec8 | ||
|
|
c664484fda | ||
|
|
06906eba4c | ||
|
|
d387ebf32d | ||
|
|
f75556f33c | ||
|
|
2cf09e4de6 | ||
|
|
a5a3a9c586 | ||
|
|
746dfbd955 | ||
|
|
b1993d2fb7 | ||
|
|
e8096dec88 | ||
|
|
39eee51ec8 | ||
|
|
7bb3a10795 | ||
|
|
a8cbe4b05f | ||
|
|
fe86da0cde | ||
|
|
4c86a2c191 | ||
|
|
8dc5db17ac | ||
|
|
549c3a190e | ||
|
|
7a68c4ccf3 | ||
|
|
4c684df653 | ||
|
|
bf8831b833 | ||
|
|
394227571f | ||
|
|
bf67577073 | ||
|
|
e180611024 | ||
|
|
43cfc55368 | ||
|
|
c03b7ea15d | ||
|
|
ddfedfb590 | ||
|
|
24418370f1 | ||
|
|
02521b6964 | ||
|
|
16f693148b | ||
|
|
0bf46cb63f | ||
|
|
2e38855396 | ||
|
|
97592a1387 | ||
|
|
c61bf76c80 | ||
|
|
e95b137011 | ||
|
|
ad655183e0 | ||
|
|
789fd34c4a | ||
|
|
87bbbaa475 | ||
|
|
a4ca813cf5 | ||
|
|
e8eef73212 | ||
|
|
512d4a43cb | ||
|
|
b9f7b1d175 |
6
.github/actions/kustomize/Dockerfile
vendored
6
.github/actions/kustomize/Dockerfile
vendored
@@ -1,6 +0,0 @@
|
||||
FROM giantswarm/tiny-tools
|
||||
|
||||
COPY entrypoint.sh /entrypoint.sh
|
||||
RUN chmod +x /entrypoint.sh
|
||||
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
9
.github/actions/kustomize/action.yml
vendored
9
.github/actions/kustomize/action.yml
vendored
@@ -1,9 +0,0 @@
|
||||
name: 'kustomize'
|
||||
description: 'A GitHub Action to run kustomize commands'
|
||||
author: 'Stefan Prodan'
|
||||
branding:
|
||||
icon: 'command'
|
||||
color: 'blue'
|
||||
runs:
|
||||
using: 'docker'
|
||||
image: 'Dockerfile'
|
||||
12
.github/actions/kustomize/entrypoint.sh
vendored
12
.github/actions/kustomize/entrypoint.sh
vendored
@@ -1,12 +0,0 @@
|
||||
#!/bin/sh -l
|
||||
|
||||
VERSION=3.5.4
|
||||
curl -sL https://github.com/kubernetes-sigs/kustomize/releases/download/kustomize%2Fv${VERSION}/kustomize_v${VERSION}_linux_amd64.tar.gz | tar xz
|
||||
|
||||
mkdir -p $GITHUB_WORKSPACE/bin
|
||||
cp ./kustomize $GITHUB_WORKSPACE/bin
|
||||
chmod +x $GITHUB_WORKSPACE/bin/kustomize
|
||||
ls -lh $GITHUB_WORKSPACE/bin
|
||||
|
||||
echo "::add-path::$GITHUB_WORKSPACE/bin"
|
||||
echo "::add-path::$RUNNER_WORKSPACE/$(basename $GITHUB_REPOSITORY)/bin"
|
||||
78
.github/workflows/bootstrap.yaml
vendored
Normal file
78
.github/workflows/bootstrap.yaml
vendored
Normal file
@@ -0,0 +1,78 @@
|
||||
name: bootstrap
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
github:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: Restore Go cache
|
||||
uses: actions/cache@v1
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-go-
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.14.x
|
||||
- name: Setup Kubernetes
|
||||
uses: engineerd/setup-kind@v0.4.0
|
||||
- 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
|
||||
- name: bootstrap init
|
||||
run: |
|
||||
./bin/flux bootstrap github --manifests ./manifests/install/ \
|
||||
--owner=fluxcd-testing \
|
||||
--repository=flux-test-${{ steps.vars.outputs.sha_short }} \
|
||||
--branch=main \
|
||||
--path=test-cluster
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITPROVIDER_BOT_TOKEN }}
|
||||
- name: bootstrap no-op
|
||||
run: |
|
||||
./bin/flux bootstrap github --manifests ./manifests/install/ \
|
||||
--owner=fluxcd-testing \
|
||||
--repository=flux-test-${{ steps.vars.outputs.sha_short }} \
|
||||
--branch=main \
|
||||
--path=test-cluster
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITPROVIDER_BOT_TOKEN }}
|
||||
- name: uninstall
|
||||
run: |
|
||||
./bin/flux suspend kustomization flux-system
|
||||
./bin/flux uninstall --resources --crds -s
|
||||
- name: bootstrap reinstall
|
||||
run: |
|
||||
./bin/flux bootstrap github --manifests ./manifests/install/ \
|
||||
--owner=fluxcd-testing \
|
||||
--repository=flux-test-${{ steps.vars.outputs.sha_short }} \
|
||||
--branch=main \
|
||||
--path=test-cluster
|
||||
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
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITPROVIDER_BOT_TOKEN }}
|
||||
- name: Debug failure
|
||||
if: failure()
|
||||
run: |
|
||||
kubectl -n flux-system get all
|
||||
kubectl -n flux-system logs deploy/source-controller
|
||||
kubectl -n flux-system logs deploy/kustomize-controller
|
||||
56
.github/workflows/docs.yaml
vendored
56
.github/workflows/docs.yaml
vendored
@@ -3,7 +3,7 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- docs*
|
||||
- master
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -13,17 +13,51 @@ jobs:
|
||||
- name: Checkout master
|
||||
uses: actions/checkout@v1
|
||||
- name: Copy assets
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
cp install/tk.sh docs/install.sh
|
||||
curl https://raw.githubusercontent.com/fluxcd/source-controller/master/docs/api/source.md > docs/components/source/api.md
|
||||
curl https://raw.githubusercontent.com/fluxcd/source-controller/master/docs/spec/v1alpha1/gitrepositories.md > docs/components/source/gitrepositories.md
|
||||
curl https://raw.githubusercontent.com/fluxcd/source-controller/master/docs/spec/v1alpha1/helmrepositories.md > docs/components/source/helmrepositories.md
|
||||
curl https://raw.githubusercontent.com/fluxcd/kustomize-controller/master/docs/api/kustomize.md > docs/components/kustomize/api.md
|
||||
curl https://raw.githubusercontent.com/fluxcd/kustomize-controller/master/docs/spec/v1alpha1/kustomization.md > docs/components/kustomize/kustomization.md
|
||||
curl https://raw.githubusercontent.com/fluxcd/notification-controller/master/docs/api/notification.md > docs/components/notification/api.md
|
||||
curl https://raw.githubusercontent.com/fluxcd/notification-controller/master/docs/spec/v1alpha1/event.md > docs/components/notification/event.md
|
||||
curl https://raw.githubusercontent.com/fluxcd/notification-controller/master/docs/spec/v1alpha1/alert.md > docs/components/notification/alert.md
|
||||
curl https://raw.githubusercontent.com/fluxcd/notification-controller/master/docs/spec/v1alpha1/provider.md > docs/components/notification/provider.md
|
||||
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
|
||||
}
|
||||
|
||||
{
|
||||
# install script
|
||||
cp install/flux.sh docs/install.sh
|
||||
}
|
||||
- name: Deploy docs
|
||||
uses: mhausenblas/mkdocs-deploy-gh-pages@master
|
||||
env:
|
||||
|
||||
136
.github/workflows/e2e.yaml
vendored
136
.github/workflows/e2e.yaml
vendored
@@ -4,7 +4,7 @@ on:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- main
|
||||
|
||||
jobs:
|
||||
kind:
|
||||
@@ -20,11 +20,13 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-go-
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v2-beta
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.14.x
|
||||
go-version: 1.15.x
|
||||
- name: Setup Kubernetes
|
||||
uses: engineerd/setup-kind@v0.3.0
|
||||
uses: engineerd/setup-kind@v0.4.0
|
||||
with:
|
||||
image: kindest/node:v1.16.9
|
||||
- name: Run test
|
||||
run: make test
|
||||
- name: Check if working tree is dirty
|
||||
@@ -35,68 +37,116 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
- name: Build
|
||||
run: sudo go build -o ./bin/tk ./cmd/tk
|
||||
- name: tk check --pre
|
||||
run: sudo go build -o ./bin/flux ./cmd/flux
|
||||
- name: flux check --pre
|
||||
run: |
|
||||
./bin/tk check --pre
|
||||
- name: tk install --version
|
||||
./bin/flux check --pre
|
||||
- name: flux install --manifests
|
||||
run: |
|
||||
./bin/tk install --version=master --namespace=test --verbose --components="source-controller,kustomize-controller"
|
||||
- name: tk uninstall
|
||||
./bin/flux install --manifests ./manifests/install/
|
||||
- name: flux create source git
|
||||
run: |
|
||||
./bin/tk uninstall --namespace=test --crds --silent
|
||||
- name: tk install --manifests
|
||||
run: |
|
||||
./bin/tk install --manifests ./manifests/install/ --version=""
|
||||
- name: tk create source git
|
||||
run: |
|
||||
./bin/tk create source git podinfo \
|
||||
./bin/flux create source git podinfo \
|
||||
--url https://github.com/stefanprodan/podinfo \
|
||||
--tag-semver=">=3.2.3"
|
||||
- name: tk get sources git
|
||||
- name: flux create source git export apply
|
||||
run: |
|
||||
./bin/tk get sources git
|
||||
- name: tk create kustomization
|
||||
./bin/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
|
||||
- name: flux get sources git
|
||||
run: |
|
||||
./bin/tk create kustomization podinfo \
|
||||
./bin/flux get sources git
|
||||
- name: flux get sources git --all-namespaces
|
||||
run: |
|
||||
./bin/flux get sources git --all-namespaces
|
||||
- name: flux create kustomization
|
||||
run: |
|
||||
./bin/flux create kustomization podinfo \
|
||||
--source=podinfo \
|
||||
--path="./deploy/overlays/dev" \
|
||||
--prune=true \
|
||||
--interval=5m \
|
||||
--validate=client \
|
||||
--validation=client \
|
||||
--health-check="Deployment/frontend.dev" \
|
||||
--health-check="Deployment/backend.dev" \
|
||||
--health-check-timeout=3m
|
||||
- name: tk sync kustomization --with-source
|
||||
- name: flux reconcile kustomization --with-source
|
||||
run: |
|
||||
./bin/tk sync kustomization podinfo --with-source
|
||||
- name: tk get kustomizations
|
||||
./bin/flux reconcile kustomization podinfo --with-source
|
||||
- name: flux get kustomizations
|
||||
run: |
|
||||
./bin/tk get kustomizations
|
||||
- name: tk suspend kustomization
|
||||
./bin/flux get kustomizations
|
||||
- name: flux get kustomizations --all-namespaces
|
||||
run: |
|
||||
./bin/tk suspend kustomization podinfo
|
||||
- name: tk resume kustomization
|
||||
./bin/flux get kustomizations --all-namespaces
|
||||
- name: flux suspend kustomization
|
||||
run: |
|
||||
./bin/tk resume kustomization podinfo
|
||||
- name: tk export
|
||||
./bin/flux suspend kustomization podinfo
|
||||
- name: flux resume kustomization
|
||||
run: |
|
||||
./bin/tk export source git --all
|
||||
./bin/tk export kustomization --all
|
||||
- name: tk delete kustomization
|
||||
./bin/flux resume kustomization podinfo
|
||||
- name: flux export
|
||||
run: |
|
||||
./bin/tk delete kustomization podinfo --silent
|
||||
- name: tk delete source git
|
||||
./bin/flux export source git --all
|
||||
./bin/flux export kustomization --all
|
||||
- name: flux delete kustomization
|
||||
run: |
|
||||
./bin/tk delete source git podinfo --silent
|
||||
- name: tk check
|
||||
./bin/flux delete kustomization podinfo --silent
|
||||
- name: flux create source helm
|
||||
run: |
|
||||
./bin/tk check
|
||||
./bin/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 \
|
||||
--target-namespace=default \
|
||||
--source=HelmRepository/podinfo \
|
||||
--chart=podinfo \
|
||||
--chart-version=">4.0.0 <5.0.0"
|
||||
- name: flux create helmrelease --source=GitRepository/podinfo
|
||||
run: |
|
||||
./bin/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
|
||||
- name: flux get helmreleases
|
||||
run: |
|
||||
./bin/flux get helmreleases
|
||||
- name: flux get helmreleases --all-namespaces
|
||||
run: |
|
||||
./bin/flux get helmreleases --all-namespaces
|
||||
- name: flux export helmrelease
|
||||
run: |
|
||||
./bin/flux export hr --all
|
||||
- name: flux delete helmrelease podinfo-helm
|
||||
run: |
|
||||
./bin/flux delete hr podinfo-helm --silent
|
||||
- name: flux delete helmrelease podinfo-git
|
||||
run: |
|
||||
./bin/flux delete hr podinfo-git --silent
|
||||
- name: flux delete source helm
|
||||
run: |
|
||||
./bin/flux delete source helm podinfo --silent
|
||||
- name: flux delete source git
|
||||
run: |
|
||||
./bin/flux delete source git podinfo --silent
|
||||
- name: flux check
|
||||
run: |
|
||||
./bin/flux check
|
||||
- name: flux uninstall
|
||||
run: |
|
||||
./bin/flux uninstall --crds --silent
|
||||
- name: Debug failure
|
||||
if: failure()
|
||||
run: |
|
||||
kubectl version --client --short
|
||||
kubectl -n gitops-system get all
|
||||
kubectl -n gitops-system get kustomizations -oyaml
|
||||
kubectl -n gitops-system logs deploy/source-controller
|
||||
kubectl -n gitops-system logs deploy/kustomize-controller
|
||||
kubectl -n flux-system get all
|
||||
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
Normal file
25
.github/workflows/fossa.yml
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
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 }}
|
||||
21
.github/workflows/rebase.yml
vendored
Normal file
21
.github/workflows/rebase.yml
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
name: rebase
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
jobs:
|
||||
rebase:
|
||||
if: github.event.issue.pull_request != '' && contains(github.event.comment.body, '/rebase') && (github.event.comment.author_association == 'CONTRIBUTOR' || github.event.comment.author_association == 'MEMBER' || github.event.comment.author_association == 'OWNER')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout the latest code
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Automatic Rebase
|
||||
uses: cirrus-actions/rebase@1.3.1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.BOT_GITHUB_TOKEN }}
|
||||
61
.github/workflows/release.yaml
vendored
61
.github/workflows/release.yaml
vendored
@@ -14,9 +14,9 @@ jobs:
|
||||
- name: Unshallow
|
||||
run: git fetch --prune --unshallow
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v2-beta
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.14.x
|
||||
go-version: 1.15.x
|
||||
- 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
|
||||
@@ -24,11 +24,64 @@ jobs:
|
||||
- name: Generate release notes
|
||||
run: |
|
||||
echo 'CHANGELOG' > /tmp/release.txt
|
||||
github-release-notes -org fluxcd -repo toolkit -since-latest-release >> /tmp/release.txt
|
||||
github-release-notes -org fluxcd -repo toolkit -since-latest-release -include-author >> /tmp/release.txt
|
||||
env:
|
||||
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: Create release
|
||||
id: create_release
|
||||
uses: actions/create-release@latest
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tag_name: ${{ github.ref }}
|
||||
release_name: ${{ github.ref }}
|
||||
- name: Upload artifacts
|
||||
id: upload-release-asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: ./output/manifests.tar.gz
|
||||
asset_name: manifests.tar.gz
|
||||
asset_content_type: application/gzip
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v1
|
||||
with:
|
||||
version: latest
|
||||
args: release --release-notes=/tmp/release.txt
|
||||
args: release --release-notes=/tmp/release.txt --skip-validate
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
HOMEBREW_TAP_GITHUB_TOKEN: ${{ secrets.BOT_GITHUB_TOKEN }}
|
||||
|
||||
74
.github/workflows/update.yml
vendored
Normal file
74
.github/workflows/update.yml
vendored
Normal file
@@ -0,0 +1,74 @@
|
||||
name: Update Components
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "0 * * * *"
|
||||
|
||||
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
|
||||
|
||||
# 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 }}"
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -13,4 +13,5 @@
|
||||
|
||||
# Dependency directories (remove the comment below to include it)
|
||||
# vendor/
|
||||
bin/
|
||||
bin/
|
||||
output/
|
||||
@@ -1,16 +1,52 @@
|
||||
builds:
|
||||
- main: ./cmd/tk
|
||||
ldflags:
|
||||
- -s -w -X main.VERSION={{ .Version }}
|
||||
binary: tk
|
||||
- <<: &build_defaults
|
||||
binary: flux
|
||||
main: ./cmd/flux
|
||||
ldflags:
|
||||
- -s -w -X main.VERSION={{ .Version }}
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
id: linux
|
||||
goos:
|
||||
- darwin
|
||||
- linux
|
||||
goarch:
|
||||
- amd64
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
- arm64
|
||||
- arm
|
||||
goarm:
|
||||
- 7
|
||||
- <<: *build_defaults
|
||||
id: darwin
|
||||
goos:
|
||||
- darwin
|
||||
- <<: *build_defaults
|
||||
id: windows
|
||||
goos:
|
||||
- windows
|
||||
archives:
|
||||
- name_template: "{{ .Binary }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}"
|
||||
id: nix
|
||||
builds: [linux, darwin]
|
||||
format: tar.gz
|
||||
files:
|
||||
- none*
|
||||
- name_template: "{{ .Binary }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}"
|
||||
id: windows
|
||||
builds: [windows]
|
||||
format: zip
|
||||
files:
|
||||
- none*
|
||||
brews:
|
||||
- name: flux
|
||||
tap:
|
||||
owner: fluxcd
|
||||
name: homebrew-tap
|
||||
token: "{{ .Env.HOMEBREW_TAP_GITHUB_TOKEN }}"
|
||||
folder: Formula
|
||||
homepage: "https://toolkit.fluxcd.io/"
|
||||
description: "Flux CLI"
|
||||
dependencies:
|
||||
- name: kubectl
|
||||
type: optional
|
||||
test: |
|
||||
system "#{bin}/flux --version"
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
# Contributing
|
||||
|
||||
FluxCD toolkit is [Apache 2.0 licensed](LICENSE) and accepts contributions
|
||||
via GitHub pull requests. This document outlines some of the conventions on
|
||||
to make it easier to get your contribution accepted.
|
||||
Flux is [Apache 2.0
|
||||
licensed](https://github.com/fluxcd/flux2/blob/main/LICENSE) and
|
||||
accepts contributions via GitHub pull requests. This document outlines
|
||||
some of the conventions on to make it easier to get your contribution
|
||||
accepted.
|
||||
|
||||
We gratefully welcome improvements to issues and documentation as well as to
|
||||
code.
|
||||
@@ -14,19 +16,42 @@ Origin (DCO). This document was created by the Linux Kernel community and is a
|
||||
simple statement that you, as a contributor, have the legal right to make the
|
||||
contribution. No action from you is required, but it's a good idea to see the
|
||||
[DCO](DCO) file for details before you start contributing code to FluxCD
|
||||
toolkit.
|
||||
organization.
|
||||
|
||||
## Communications
|
||||
|
||||
The project uses Slack: To join the conversation, simply join the
|
||||
[CNCF](https://slack.cncf.io/) Slack workspace and use the
|
||||
[#flux](https://cloud-native.slack.com/messages/flux/) channel.
|
||||
For realtime communications we use Slack: To join the conversation, simply
|
||||
join the [CNCF](https://slack.cncf.io/) Slack workspace and use the
|
||||
[#flux-dev](https://cloud-native.slack.com/messages/flux-dev/) channel.
|
||||
|
||||
The developers use a mailing list to discuss development as well.
|
||||
Simply subscribe to [flux-dev on cncf.io](https://lists.cncf.io/g/cncf-flux-dev)
|
||||
to join the conversation (this will also add an invitation to your
|
||||
Google calendar for our [Flux
|
||||
meeting](https://docs.google.com/document/d/1l_M0om0qUEN_NNiGgpqJ2tvsF2iioHkaARDeh6b70B0/edit#)).
|
||||
To discuss ideas and specifications we use [Github
|
||||
Discussions](https://github.com/fluxcd/flux2/discussions).
|
||||
|
||||
For announcements we use a mailing list as well. Simply subscribe to
|
||||
[flux-dev on cncf.io](https://lists.cncf.io/g/cncf-flux-dev)
|
||||
to join the conversation (there you can also add calendar invites
|
||||
to your Google calendar for our [Flux
|
||||
meeting](https://docs.google.com/document/d/1l_M0om0qUEN_NNiGgpqJ2tvsF2iioHkaARDeh6b70B0/view)).
|
||||
|
||||
## Understanding Flux and the GitOps Toolkit
|
||||
|
||||
If you are entirely new to Flux and the GitOps Toolkit,
|
||||
you might want to take a look at the [introductory talk and demo](https://www.youtube.com/watch?v=qQBtSkgl7tI).
|
||||
|
||||
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
|
||||
|
||||
### 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
|
||||
walks you through writing a short and concise controller that watches out
|
||||
for source changes.
|
||||
|
||||
### How to run the test suite
|
||||
|
||||
@@ -57,7 +82,7 @@ get asked to resubmit the PR or divide the changes into more than one PR.
|
||||
|
||||
### Format of the Commit Message
|
||||
|
||||
For Source Controller we prefer the following rules for good commit messages:
|
||||
For the GitOps Toolkit controllers we prefer the following rules for good commit messages:
|
||||
|
||||
- Limit the subject to 50 characters and write as the continuation
|
||||
of the sentence "If applied, this commit will ..."
|
||||
|
||||
11
Makefile
11
Makefile
@@ -1,4 +1,4 @@
|
||||
VERSION?=$(shell grep 'VERSION' cmd/tk/main.go | awk '{ print $$4 }' | tr -d '"')
|
||||
VERSION?=$(shell grep 'VERSION' cmd/flux/main.go | awk '{ print $$4 }' | tr -d '"')
|
||||
|
||||
all: test build
|
||||
|
||||
@@ -15,14 +15,15 @@ test: tidy fmt vet docs
|
||||
go test ./... -coverprofile cover.out
|
||||
|
||||
build:
|
||||
CGO_ENABLED=0 go build -o ./bin/tk ./cmd/tk
|
||||
CGO_ENABLED=0 go build -o ./bin/flux ./cmd/flux
|
||||
|
||||
install:
|
||||
go install cmd/tk
|
||||
go install cmd/flux
|
||||
|
||||
.PHONY: docs
|
||||
docs:
|
||||
mkdir -p ./docs/cmd && go run ./cmd/tk/ docgen
|
||||
rm docs/cmd/*
|
||||
mkdir -p ./docs/cmd && go run ./cmd/flux/ docgen
|
||||
|
||||
install-dev:
|
||||
CGO_ENABLED=0 go build -o /usr/local/bin ./cmd/tk
|
||||
CGO_ENABLED=0 go build -o /usr/local/bin ./cmd/flux
|
||||
|
||||
120
README.md
120
README.md
@@ -1,12 +1,116 @@
|
||||
# toolkit
|
||||
# Flux version 2
|
||||
|
||||
[](https://github.com/fluxcd/toolkit/actions)
|
||||
[](https://goreportcard.com/report/github.com/fluxcd/toolkit)
|
||||
[](https://github.com/fluxcd/toolkit/blob/master/LICENSE)
|
||||
[](https://github.com/fluxcd/toolkit/releases)
|
||||
[](https://github.com/fluxcd/flux2/actions)
|
||||
[](https://goreportcard.com/report/github.com/fluxcd/flux2)
|
||||
[](https://github.com/fluxcd/flux2/blob/main/LICENSE)
|
||||
[](https://github.com/fluxcd/flux2/releases)
|
||||
|
||||
Experimental toolkit for assembling CD pipelines the GitOps way.
|
||||
Flux is a tool for keeping Kubernetes clusters in sync with sources of
|
||||
configuration (like Git repositories), and automating updates to
|
||||
configuration when there is new code to deploy.
|
||||
|
||||

|
||||
Flux version 2 ("v2") is built from the ground up to use Kubernetes'
|
||||
API extension system, and to integrate with Prometheus and other core
|
||||
components of the Kubernetes ecosystem. In version 2, Flux supports
|
||||
multi-tenancy and support for syncing an arbitrary number of Git
|
||||
repositories, among other long-requested features.
|
||||
|
||||
To get started with the toolkit please read the [docs](https://toolkit.fluxcd.io/).
|
||||
Flux v2 is constructed with the [GitOps Toolkit](#gitops-toolkit), a
|
||||
set of composable APIs and specialized tools for building Continuous
|
||||
Delivery on top of Kubernetes.
|
||||
|
||||
## Flux installation
|
||||
|
||||
With Homebrew:
|
||||
|
||||
```sh
|
||||
brew install fluxcd/tap/flux
|
||||
```
|
||||
|
||||
With Bash:
|
||||
|
||||
```sh
|
||||
curl -s https://toolkit.fluxcd.io/install.sh | sudo bash
|
||||
|
||||
# enable completions in ~/.bash_profile
|
||||
. <(flux completion bash)
|
||||
```
|
||||
|
||||
Binaries for macOS, Windows and Linux AMD64/ARM are available to download on the
|
||||
[release page](https://github.com/fluxcd/flux2/releases).
|
||||
|
||||
Verify that your cluster satisfies the prerequisites with:
|
||||
|
||||
```sh
|
||||
flux check --pre
|
||||
```
|
||||
|
||||
## Get started
|
||||
|
||||
To get started with Flux, start [browsing the
|
||||
documentation](https://toolkit.fluxcd.io) 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/)
|
||||
|
||||
## GitOps Toolkit
|
||||
|
||||
The GitOps Toolkit is the set of APIs and controllers that make up the
|
||||
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/).
|
||||
|
||||
### 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/)
|
||||
|
||||
## Community
|
||||
|
||||
The Flux project is always looking for new contributors and there are a multitude of ways to get involved.
|
||||
Depending on what you want to do, some of the following bits might be your first steps:
|
||||
|
||||
- Join our upcoming dev meetings ([meeting access and agenda](https://docs.google.com/document/d/1l_M0om0qUEN_NNiGgpqJ2tvsF2iioHkaARDeh6b70B0/view))
|
||||
- Talk to us in the #flux channel on [CNCF Slack](https://slack.cncf.io/)
|
||||
- Join the [planning discussions](https://github.com/fluxcd/flux2/discussions)
|
||||
- And if you are completely new to Flux and the GitOps Toolkit, take a look at our [Get Started guide](https://toolkit.fluxcd.io/get-started/) and give us feedback
|
||||
- To be part of the conversation about Flux's development, [join the flux-dev mailing list](https://lists.cncf.io/g/cncf-flux-dev).
|
||||
- Check out [how to contribute](CONTRIBUTING.md) to the project
|
||||
|
||||
### Featured Talks
|
||||
|
||||
- 28 Oct 2020 - [The Kubelist Podcast: Flux with Michael Bridgen](https://www.heavybit.com/library/podcasts/the-kubelist-podcast/ep-5-flux-with-michael-bridgen-of-weaveworks/)
|
||||
- 19 Oct 2020 - [The Power of GitOps with Flux & GitOps Toolkit - Part 1 with Leigh Capili](https://youtu.be/0v5bjysXTL8)
|
||||
- 12 Oct 2020 - [Rawkode Live: Introduction to GitOps Toolkit with Stefan Prodan](https://youtu.be/HqTzuOBP0eY)
|
||||
- 4 Sep 2020 - [KubeCon Europe: The road to Flux v2 and Progressive Delivery with Stefan Prodan & Hidde Beydals](https://youtu.be/8v94nUkXsxU)
|
||||
- 25 June 2020 - [Cloud Native Nordics: Introduction to GitOps & GitOps Toolkit with Alexis Richardson & Stefan Prodan](https://youtu.be/qQBtSkgl7tI)
|
||||
- 7 May 2020 - [GitOps Days - Community Special: GitOps Toolkit Experimentation with Stefan Prodan](https://youtu.be/WHzxunv4DKk?t=6521)
|
||||
|
||||
### Upcoming Events
|
||||
|
||||
- 2 Nov 2020 - [The Power of GitOps with Flux & GitOps Toolkit - Part 2 with Leigh Capili](https://www.meetup.com/GitOps-Community/events/273934676/)
|
||||
- 12-13 Nov 2020 - [GitOps Days EMEA](https://www.gitopsdays.com/) with talks and workshops on migrating to Flux v2 and Helm Controller
|
||||
- 19 Nov 2020 - [KubeCon NA: Progressive Delivery Techniques with Flagger and Flux v2 with Stefan Prodan](https://kccncna20.sched.com/event/1b04f8408b49976b843a5d0019cb8112)
|
||||
|
||||
We are looking forward to seeing you with us!
|
||||
|
||||
251
cmd/flux/bootstrap.go
Normal file
251
cmd/flux/bootstrap.go
Normal file
@@ -0,0 +1,251 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
var bootstrapCmd = &cobra.Command{
|
||||
Use: "bootstrap",
|
||||
Short: "Bootstrap toolkit components",
|
||||
Long: "The bootstrap sub-commands bootstrap the toolkit components on the targeted Git provider.",
|
||||
}
|
||||
|
||||
var (
|
||||
bootstrapVersion string
|
||||
bootstrapComponents []string
|
||||
bootstrapRegistry string
|
||||
bootstrapImagePullSecret string
|
||||
bootstrapBranch string
|
||||
bootstrapWatchAllNamespaces bool
|
||||
bootstrapNetworkPolicy bool
|
||||
bootstrapManifestsPath string
|
||||
bootstrapArch = flags.Arch(defaults.Arch)
|
||||
bootstrapLogLevel = flags.LogLevel(defaults.LogLevel)
|
||||
bootstrapRequiredComponents = []string{"source-controller", "kustomize-controller"}
|
||||
)
|
||||
|
||||
const (
|
||||
bootstrapDefaultBranch = "main"
|
||||
)
|
||||
|
||||
func init() {
|
||||
bootstrapCmd.PersistentFlags().StringVarP(&bootstrapVersion, "version", "v", defaults.Version,
|
||||
"toolkit version")
|
||||
bootstrapCmd.PersistentFlags().StringSliceVar(&bootstrapComponents, "components", defaults.Components,
|
||||
"list of components, accepts comma-separated values")
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapRegistry, "registry", "ghcr.io/fluxcd",
|
||||
"container registry where the toolkit images are published")
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapImagePullSecret, "image-pull-secret", "",
|
||||
"Kubernetes secret name used for pulling the toolkit images from a private registry")
|
||||
bootstrapCmd.PersistentFlags().Var(&bootstrapArch, "arch", bootstrapArch.Description())
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapBranch, "branch", bootstrapDefaultBranch,
|
||||
"default branch (for GitHub this must match the default branch setting for the organization)")
|
||||
rootCmd.AddCommand(bootstrapCmd)
|
||||
bootstrapCmd.PersistentFlags().BoolVar(&bootstrapWatchAllNamespaces, "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(&bootstrapNetworkPolicy, "network-policy", true,
|
||||
"deny ingress access to the toolkit controllers from other namespaces using network policies")
|
||||
bootstrapCmd.PersistentFlags().Var(&bootstrapLogLevel, "log-level", bootstrapLogLevel.Description())
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapManifestsPath, "manifests", "", "path to the manifest directory")
|
||||
bootstrapCmd.PersistentFlags().MarkHidden("manifests")
|
||||
}
|
||||
|
||||
func bootstrapValidate() error {
|
||||
for _, component := range bootstrapRequiredComponents {
|
||||
if !utils.ContainsItemString(bootstrapComponents, component) {
|
||||
return fmt.Errorf("component %s is required", component)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateInstallManifests(targetPath, namespace, tmpDir string, localManifests string) (string, error) {
|
||||
opts := install.Options{
|
||||
BaseURL: localManifests,
|
||||
Version: bootstrapVersion,
|
||||
Namespace: namespace,
|
||||
Components: bootstrapComponents,
|
||||
Registry: bootstrapRegistry,
|
||||
ImagePullSecret: bootstrapImagePullSecret,
|
||||
Arch: bootstrapArch.String(),
|
||||
WatchAllNamespaces: bootstrapWatchAllNamespaces,
|
||||
NetworkPolicy: bootstrapNetworkPolicy,
|
||||
LogLevel: bootstrapLogLevel.String(),
|
||||
NotificationController: defaults.NotificationController,
|
||||
ManifestFile: defaults.ManifestFile,
|
||||
Timeout: timeout,
|
||||
TargetPath: targetPath,
|
||||
}
|
||||
|
||||
if localManifests == "" {
|
||||
opts.BaseURL = defaults.BaseURL
|
||||
}
|
||||
|
||||
output, err := install.Generate(opts)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("generating install manifests failed: %w", err)
|
||||
}
|
||||
|
||||
if filePath, err := output.WriteFile(tmpDir); err != nil {
|
||||
return "", fmt.Errorf("generating install manifests failed: %w", err)
|
||||
} else {
|
||||
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, kubectlArgs...); err != nil {
|
||||
return fmt.Errorf("install failed")
|
||||
}
|
||||
|
||||
for _, deployment := range components {
|
||||
kubectlArgs = []string{"-n", namespace, "rollout", "status", "deployment", deployment, "--timeout", timeout.String()}
|
||||
if _, err := utils.ExecKubectlCommand(ctx, utils.ModeOS, kubectlArgs...); err != nil {
|
||||
return fmt.Errorf("install failed")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateSyncManifests(url, branch, name, namespace, targetPath, tmpDir string, interval time.Duration) 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)
|
||||
}
|
||||
|
||||
if _, err := manifest.WriteFile(tmpDir); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := utils.GenerateKustomizationYaml(filepath.Join(tmpDir, targetPath, namespace)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func applySyncManifests(ctx context.Context, kubeClient client.Client, name, namespace, targetPath, tmpDir string) error {
|
||||
kubectlArgs := []string{"apply", "-k", filepath.Join(tmpDir, targetPath, namespace)}
|
||||
if _, err := utils.ExecKubectlCommand(ctx, utils.ModeStderrOS, kubectlArgs...); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Waitingf("waiting for cluster sync")
|
||||
|
||||
var gitRepository sourcev1.GitRepository
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isGitRepositoryReady(ctx, kubeClient, types.NamespacedName{Name: name, Namespace: namespace}, &gitRepository)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var kustomization kustomizev1.Kustomization
|
||||
if err := wait.PollImmediate(pollInterval, 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)
|
||||
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
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/git"
|
||||
)
|
||||
|
||||
@@ -42,19 +43,22 @@ the bootstrap command will perform an upgrade if needed.`,
|
||||
export GITHUB_TOKEN=<my-token>
|
||||
|
||||
# Run bootstrap for a private repo owned by a GitHub organization
|
||||
bootstrap github --owner=<organization> --repository=<repo name>
|
||||
flux bootstrap github --owner=<organization> --repository=<repo name>
|
||||
|
||||
# Run bootstrap for a private repo and assign organization teams to it
|
||||
bootstrap github --owner=<organization> --repository=<repo name> --team=<team1 slug> --team=<team2 slug>
|
||||
flux bootstrap github --owner=<organization> --repository=<repo name> --team=<team1 slug> --team=<team2 slug>
|
||||
|
||||
# Run bootstrap for a repository path
|
||||
bootstrap github --owner=<organization> --repository=<repo name> --path=dev-cluster
|
||||
flux bootstrap github --owner=<organization> --repository=<repo name> --path=dev-cluster
|
||||
|
||||
# Run bootstrap for a public repository on a personal account
|
||||
bootstrap github --owner=<user> --repository=<repo name> --private=false --personal=true
|
||||
flux bootstrap github --owner=<user> --repository=<repo name> --private=false --personal=true
|
||||
|
||||
# Run bootstrap for a private repo hosted on GitHub Enterprise
|
||||
bootstrap github --owner=<organization> --repository=<repo name> --hostname=<domain>
|
||||
flux bootstrap github --owner=<organization> --repository=<repo name> --hostname=<domain>
|
||||
|
||||
# Run bootstrap for a an existing repository with a branch named main
|
||||
flux bootstrap github --owner=<organization> --repository=<repo name> --branch=main
|
||||
`,
|
||||
RunE: bootstrapGitHubCmdRun,
|
||||
}
|
||||
@@ -68,6 +72,7 @@ var (
|
||||
ghHostname string
|
||||
ghPath string
|
||||
ghTeams []string
|
||||
ghDelete bool
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -84,6 +89,9 @@ func init() {
|
||||
bootstrapGitHubCmd.Flags().StringVar(&ghHostname, "hostname", git.GitHubDefaultHostname, "GitHub hostname")
|
||||
bootstrapGitHubCmd.Flags().StringVar(&ghPath, "path", "", "repository path, when specified the cluster sync will be scoped to this path")
|
||||
|
||||
bootstrapGitHubCmd.Flags().BoolVar(&ghDelete, "delete", false, "delete repository (used for testing only)")
|
||||
bootstrapGitHubCmd.Flags().MarkHidden("delete")
|
||||
|
||||
bootstrapCmd.AddCommand(bootstrapGitHubCmd)
|
||||
}
|
||||
|
||||
@@ -93,7 +101,11 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return fmt.Errorf("%s environment variable not found", git.GitHubTokenName)
|
||||
}
|
||||
|
||||
repository, err := git.NewRepository(ghRepository, ghOwner, ghHostname, ghToken, "tk", ghOwner+"@users.noreply.github.com")
|
||||
if err := bootstrapValidate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
repository, err := git.NewRepository(ghRepository, ghOwner, ghHostname, ghToken, "flux", ghOwner+"@users.noreply.github.com")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -103,11 +115,6 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
|
||||
IsPersonal: ghPersonal,
|
||||
}
|
||||
|
||||
kubeClient, err := utils.kubeClient(kubeconfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tmpDir, err := ioutil.TempDir("", namespace)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -117,6 +124,14 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
if ghDelete {
|
||||
if err := provider.DeleteRepository(ctx, repository); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("repository deleted")
|
||||
return nil
|
||||
}
|
||||
|
||||
// create GitHub repository if doesn't exists
|
||||
logger.Actionf("connecting to %s", ghHostname)
|
||||
changed, err := provider.CreateRepository(ctx, repository)
|
||||
@@ -148,7 +163,7 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
|
||||
|
||||
// generate install manifests
|
||||
logger.Generatef("generating manifests")
|
||||
manifest, err := generateInstallManifests(ghPath, namespace, tmpDir)
|
||||
manifest, err := generateInstallManifests(ghPath, namespace, tmpDir, bootstrapManifestsPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -169,13 +184,18 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
|
||||
logger.Successf("components are up to date")
|
||||
}
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// determine if repo synchronization is working
|
||||
isInstall := shouldInstallManifests(ctx, kubeClient, namespace)
|
||||
|
||||
if isInstall {
|
||||
// apply install manifests
|
||||
logger.Actionf("installing components in %s namespace", namespace)
|
||||
if err := applyInstallManifests(ctx, manifest, components); err != nil {
|
||||
if err := applyInstallManifests(ctx, manifest, bootstrapComponents); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("install completed")
|
||||
@@ -194,9 +214,9 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return fmt.Errorf("generating deploy key failed: %w", err)
|
||||
}
|
||||
|
||||
keyName := "tk"
|
||||
keyName := "flux"
|
||||
if ghPath != "" {
|
||||
keyName = fmt.Sprintf("tk-%s", ghPath)
|
||||
keyName = fmt.Sprintf("flux-%s", ghPath)
|
||||
}
|
||||
|
||||
if changed, err := provider.AddDeployKey(ctx, repository, key, keyName); err != nil {
|
||||
@@ -207,28 +227,25 @@ func bootstrapGitHubCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
// configure repo synchronization
|
||||
if isInstall {
|
||||
// generate source and kustomization manifests
|
||||
logger.Actionf("generating sync manifests")
|
||||
if err := generateSyncManifests(repository.GetSSH(), namespace, namespace, ghPath, tmpDir, ghInterval); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Actionf("generating sync manifests")
|
||||
if err := generateSyncManifests(repository.GetSSH(), bootstrapBranch, namespace, namespace, ghPath, tmpDir, ghInterval); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// commit and push manifests
|
||||
if changed, err = repository.Commit(ctx, path.Join(ghPath, namespace), "Add manifests"); err != nil {
|
||||
// commit and push manifests
|
||||
if changed, err = repository.Commit(ctx, path.Join(ghPath, namespace), "Add manifests"); err != nil {
|
||||
return err
|
||||
} else if changed {
|
||||
if err := repository.Push(ctx); err != nil {
|
||||
return err
|
||||
} else if changed {
|
||||
if err := repository.Push(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("sync manifests pushed")
|
||||
}
|
||||
logger.Successf("sync manifests pushed")
|
||||
}
|
||||
|
||||
// apply manifests and waiting for sync
|
||||
logger.Actionf("applying sync manifests")
|
||||
if err := applySyncManifests(ctx, kubeClient, namespace, namespace, ghPath, tmpDir); err != nil {
|
||||
return err
|
||||
}
|
||||
// apply manifests and waiting for sync
|
||||
logger.Actionf("applying sync manifests")
|
||||
if err := applySyncManifests(ctx, kubeClient, namespace, namespace, ghPath, tmpDir); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if withErrors {
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -26,7 +26,10 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/git"
|
||||
)
|
||||
|
||||
@@ -41,29 +44,36 @@ 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 owned by a GitLab group
|
||||
bootstrap gitlab --owner=<group> --repository=<repo name>
|
||||
# Run bootstrap for a private repo using HTTPS token authentication
|
||||
flux bootstrap gitlab --owner=<group> --repository=<repo name>
|
||||
|
||||
# Run bootstrap for a private repo using SSH authentication
|
||||
flux bootstrap gitlab --owner=<group> --repository=<repo name> --ssh-hostname=gitlab.com
|
||||
|
||||
# Run bootstrap for a repository path
|
||||
bootstrap gitlab --owner=<group> --repository=<repo name> --path=dev-cluster
|
||||
flux bootstrap gitlab --owner=<group> --repository=<repo name> --path=dev-cluster
|
||||
|
||||
# Run bootstrap for a public repository on a personal account
|
||||
bootstrap gitlab --owner=<user> --repository=<repo name> --private=false --personal=true
|
||||
flux bootstrap gitlab --owner=<user> --repository=<repo name> --private=false --personal=true
|
||||
|
||||
# Run bootstrap for a private repo hosted on a GitLab server
|
||||
bootstrap gitlab --owner=<group> --repository=<repo name> --hostname=<domain>
|
||||
flux bootstrap gitlab --owner=<group> --repository=<repo name> --hostname=<domain>
|
||||
|
||||
# Run bootstrap for a an existing repository with a branch named main
|
||||
flux bootstrap gitlab --owner=<organization> --repository=<repo name> --branch=main
|
||||
`,
|
||||
RunE: bootstrapGitLabCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
glOwner string
|
||||
glRepository string
|
||||
glInterval time.Duration
|
||||
glPersonal bool
|
||||
glPrivate bool
|
||||
glHostname string
|
||||
glPath string
|
||||
glOwner string
|
||||
glRepository string
|
||||
glInterval time.Duration
|
||||
glPersonal bool
|
||||
glPrivate bool
|
||||
glHostname string
|
||||
glSSHHostname string
|
||||
glPath string
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -73,6 +83,7 @@ func init() {
|
||||
bootstrapGitLabCmd.Flags().BoolVar(&glPrivate, "private", true, "is private repository")
|
||||
bootstrapGitLabCmd.Flags().DurationVar(&glInterval, "interval", time.Minute, "sync interval")
|
||||
bootstrapGitLabCmd.Flags().StringVar(&glHostname, "hostname", git.GitLabDefaultHostname, "GitLab hostname")
|
||||
bootstrapGitLabCmd.Flags().StringVar(&glSSHHostname, "ssh-hostname", "", "GitLab SSH hostname, when specified a deploy key will be added to the repository")
|
||||
bootstrapGitLabCmd.Flags().StringVar(&glPath, "path", "", "repository path, when specified the cluster sync will be scoped to this path")
|
||||
|
||||
bootstrapCmd.AddCommand(bootstrapGitLabCmd)
|
||||
@@ -84,17 +95,25 @@ func bootstrapGitLabCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return fmt.Errorf("%s environment variable not found", git.GitLabTokenName)
|
||||
}
|
||||
|
||||
repository, err := git.NewRepository(glRepository, glOwner, glHostname, glToken, "tk", glOwner+"@users.noreply.gitlab.com")
|
||||
if err := bootstrapValidate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
repository, err := git.NewRepository(glRepository, glOwner, glHostname, glToken, "flux", glOwner+"@users.noreply.gitlab.com")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if glSSHHostname != "" {
|
||||
repository.SSHHost = glSSHHostname
|
||||
}
|
||||
|
||||
provider := &git.GitLabProvider{
|
||||
IsPrivate: glPrivate,
|
||||
IsPersonal: glPersonal,
|
||||
}
|
||||
|
||||
kubeClient, err := utils.kubeClient(kubeconfig)
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -126,7 +145,7 @@ func bootstrapGitLabCmdRun(cmd *cobra.Command, args []string) error {
|
||||
|
||||
// generate install manifests
|
||||
logger.Generatef("generating manifests")
|
||||
manifest, err := generateInstallManifests(glPath, namespace, tmpDir)
|
||||
manifest, err := generateInstallManifests(glPath, namespace, tmpDir, bootstrapManifestsPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -153,60 +172,77 @@ func bootstrapGitLabCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if isInstall {
|
||||
// apply install manifests
|
||||
logger.Actionf("installing components in %s namespace", namespace)
|
||||
if err := applyInstallManifests(ctx, manifest, components); err != nil {
|
||||
if err := applyInstallManifests(ctx, manifest, bootstrapComponents); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("install completed")
|
||||
}
|
||||
|
||||
// setup SSH deploy key
|
||||
if shouldCreateDeployKey(ctx, kubeClient, namespace) {
|
||||
logger.Actionf("configuring deploy key")
|
||||
u, err := url.Parse(repository.GetSSH())
|
||||
if err != nil {
|
||||
return fmt.Errorf("git URL parse failed: %w", err)
|
||||
}
|
||||
repoURL := repository.GetURL()
|
||||
|
||||
key, err := generateDeployKey(ctx, kubeClient, u, namespace)
|
||||
if err != nil {
|
||||
return fmt.Errorf("generating deploy key failed: %w", err)
|
||||
}
|
||||
if glSSHHostname != "" {
|
||||
// setup SSH deploy key
|
||||
repoURL = repository.GetSSH()
|
||||
if shouldCreateDeployKey(ctx, kubeClient, namespace) {
|
||||
logger.Actionf("configuring deploy key")
|
||||
u, err := url.Parse(repoURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("git URL parse failed: %w", err)
|
||||
}
|
||||
|
||||
keyName := "tk"
|
||||
if glPath != "" {
|
||||
keyName = fmt.Sprintf("tk-%s", glPath)
|
||||
}
|
||||
key, err := generateDeployKey(ctx, kubeClient, u, namespace)
|
||||
if err != nil {
|
||||
return fmt.Errorf("generating deploy key failed: %w", err)
|
||||
}
|
||||
|
||||
if changed, err := provider.AddDeployKey(ctx, repository, key, keyName); err != nil {
|
||||
keyName := "flux"
|
||||
if glPath != "" {
|
||||
keyName = fmt.Sprintf("flux-%s", glPath)
|
||||
}
|
||||
|
||||
if changed, err := provider.AddDeployKey(ctx, repository, key, keyName); err != nil {
|
||||
return err
|
||||
} else if changed {
|
||||
logger.Successf("deploy key configured")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// setup HTTPS token auth
|
||||
secret := corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: namespace,
|
||||
Namespace: namespace,
|
||||
},
|
||||
StringData: map[string]string{
|
||||
"username": "git",
|
||||
"password": glToken,
|
||||
},
|
||||
}
|
||||
if err := upsertSecret(ctx, kubeClient, secret); err != nil {
|
||||
return err
|
||||
} else if changed {
|
||||
logger.Successf("deploy key configured")
|
||||
}
|
||||
}
|
||||
|
||||
// configure repo synchronization
|
||||
if isInstall {
|
||||
// generate source and kustomization manifests
|
||||
logger.Actionf("generating sync manifests")
|
||||
if err := generateSyncManifests(repository.GetSSH(), namespace, namespace, glPath, tmpDir, glInterval); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Actionf("generating sync manifests")
|
||||
if err := generateSyncManifests(repoURL, bootstrapBranch, namespace, namespace, glPath, tmpDir, glInterval); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// commit and push manifests
|
||||
if changed, err = repository.Commit(ctx, path.Join(glPath, namespace), "Add manifests"); err != nil {
|
||||
// commit and push manifests
|
||||
if changed, err = repository.Commit(ctx, path.Join(glPath, namespace), "Add manifests"); err != nil {
|
||||
return err
|
||||
} else if changed {
|
||||
if err := repository.Push(ctx); err != nil {
|
||||
return err
|
||||
} else if changed {
|
||||
if err := repository.Push(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("sync manifests pushed")
|
||||
}
|
||||
logger.Successf("sync manifests pushed")
|
||||
}
|
||||
|
||||
// apply manifests and waiting for sync
|
||||
logger.Actionf("applying sync manifests")
|
||||
if err := applySyncManifests(ctx, kubeClient, namespace, namespace, glPath, tmpDir); err != nil {
|
||||
return err
|
||||
}
|
||||
// apply manifests and waiting for sync
|
||||
logger.Actionf("applying sync manifests")
|
||||
if err := applySyncManifests(ctx, kubeClient, namespace, namespace, glPath, tmpDir); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Successf("bootstrap finished")
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -18,13 +18,15 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"github.com/blang/semver"
|
||||
"github.com/blang/semver/v4"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/spf13/cobra"
|
||||
apimachineryversion "k8s.io/apimachinery/pkg/version"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
"k8s.io/client-go/tools/clientcmd"
|
||||
)
|
||||
@@ -35,22 +37,28 @@ var checkCmd = &cobra.Command{
|
||||
Long: `The check command will perform a series of checks to validate that
|
||||
the local environment is configured correctly and if the installed components are healthy.`,
|
||||
Example: ` # Run pre-installation checks
|
||||
check --pre
|
||||
flux check --pre
|
||||
|
||||
# Run installation checks
|
||||
check
|
||||
flux check
|
||||
`,
|
||||
RunE: runCheckCmd,
|
||||
}
|
||||
|
||||
var (
|
||||
checkPre bool
|
||||
checkPre bool
|
||||
checkComponents []string
|
||||
)
|
||||
|
||||
type kubectlVersion struct {
|
||||
ClientVersion *apimachineryversion.Info `json:"clientVersion"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
checkCmd.Flags().BoolVarP(&checkPre, "pre", "", false,
|
||||
"only run pre-installation checks")
|
||||
|
||||
checkCmd.Flags().StringSliceVar(&checkComponents, "components", defaults.Components,
|
||||
"list of components, accepts comma-separated values")
|
||||
rootCmd.AddCommand(checkCmd)
|
||||
}
|
||||
|
||||
@@ -65,7 +73,7 @@ func runCheckCmd(cmd *cobra.Command, args []string) error {
|
||||
checkFailed = true
|
||||
}
|
||||
|
||||
if !kubernetesCheck(">=1.14.0") {
|
||||
if !kubernetesCheck(">=1.16.0") {
|
||||
checkFailed = true
|
||||
}
|
||||
|
||||
@@ -95,14 +103,20 @@ func kubectlCheck(ctx context.Context, version string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
command := "kubectl version --client --short | awk '{ print $3 }'"
|
||||
output, err := utils.execCommand(ctx, ModeCapture, command)
|
||||
kubectlArgs := []string{"version", "--client", "--output", "json"}
|
||||
output, err := utils.ExecKubectlCommand(ctx, utils.ModeCapture, kubectlArgs...)
|
||||
if err != nil {
|
||||
logger.Failuref("kubectl version can't be determined")
|
||||
return false
|
||||
}
|
||||
|
||||
v, err := semver.ParseTolerant(output)
|
||||
kv := &kubectlVersion{}
|
||||
if err = json.Unmarshal([]byte(output), kv); err != nil {
|
||||
logger.Failuref("kubectl version output can't be unmarshaled")
|
||||
return false
|
||||
}
|
||||
|
||||
v, err := semver.ParseTolerant(kv.ClientVersion.GitVersion)
|
||||
if err != nil {
|
||||
logger.Failuref("kubectl version can't be parsed")
|
||||
return false
|
||||
@@ -158,10 +172,9 @@ func componentsCheck() bool {
|
||||
defer cancel()
|
||||
|
||||
ok := true
|
||||
for _, deployment := range components {
|
||||
command := fmt.Sprintf("kubectl -n %s rollout status deployment %s --timeout=%s",
|
||||
namespace, deployment, timeout.String())
|
||||
if output, err := utils.execCommand(ctx, ModeCapture, command); err != nil {
|
||||
for _, deployment := range checkComponents {
|
||||
kubectlArgs := []string{"-n", namespace, "rollout", "status", "deployment", deployment, "--timeout", timeout.String()}
|
||||
if output, err := utils.ExecKubectlCommand(ctx, utils.ModeCapture, kubectlArgs...); err != nil {
|
||||
logger.Failuref("%s: %s", deployment, strings.TrimSuffix(output, "\n"))
|
||||
ok = false
|
||||
} else {
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -17,24 +17,15 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var createCmd = &cobra.Command{
|
||||
Use: "create",
|
||||
Short: "Create or update sources and resources",
|
||||
Long: "The create sub-commands generate sources and resources.",
|
||||
var completionCmd = &cobra.Command{
|
||||
Use: "completion",
|
||||
Short: "Generates completion scripts for various shells",
|
||||
Long: "The completion sub-command generates completion scripts for various shells",
|
||||
}
|
||||
|
||||
var (
|
||||
interval time.Duration
|
||||
export bool
|
||||
)
|
||||
|
||||
func init() {
|
||||
createCmd.PersistentFlags().DurationVarP(&interval, "interval", "", time.Minute, "source sync interval")
|
||||
createCmd.PersistentFlags().BoolVar(&export, "export", false, "export in YAML format to stdout")
|
||||
rootCmd.AddCommand(createCmd)
|
||||
rootCmd.AddCommand(completionCmd)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -22,17 +22,17 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var completionCmd = &cobra.Command{
|
||||
Use: "completion",
|
||||
var completionBashCmd = &cobra.Command{
|
||||
Use: "bash",
|
||||
Short: "Generates bash completion scripts",
|
||||
Example: `To load completion run
|
||||
|
||||
. <(tk completion)
|
||||
. <(flux completion bash)
|
||||
|
||||
To configure your bash shell to load completions for each session add to your bashrc
|
||||
|
||||
# ~/.bashrc or ~/.profile
|
||||
. <(tk completion)
|
||||
command -v flux >/dev/null && . <(flux completion bash)
|
||||
`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
rootCmd.GenBashCompletion(os.Stdout)
|
||||
@@ -40,5 +40,5 @@ To configure your bash shell to load completions for each session add to your ba
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(completionCmd)
|
||||
completionCmd.AddCommand(completionBashCmd)
|
||||
}
|
||||
45
cmd/flux/completion_fish.go
Normal file
45
cmd/flux/completion_fish.go
Normal file
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
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 (
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var completionFishCmd = &cobra.Command{
|
||||
Use: "fish",
|
||||
Short: "Generates fish completion scripts",
|
||||
Example: `To load completion run
|
||||
|
||||
. <(flux completion 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
|
||||
`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
rootCmd.GenFishCompletion(os.Stdout, true)
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
completionCmd.AddCommand(completionFishCmd)
|
||||
}
|
||||
51
cmd/flux/completion_powershell.go
Normal file
51
cmd/flux/completion_powershell.go
Normal file
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
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 (
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var completionPowerShellCmd = &cobra.Command{
|
||||
Use: "powershell",
|
||||
Short: "Generates powershell completion scripts",
|
||||
Example: `To load completion run
|
||||
|
||||
. <(flux completion powershell)
|
||||
|
||||
To configure your powershell shell to load completions for each session add to your powershell profile
|
||||
|
||||
Windows:
|
||||
|
||||
cd "$env:USERPROFILE\Documents\WindowsPowerShell\Modules"
|
||||
flux completion >> flux-completion.ps1
|
||||
|
||||
Linux:
|
||||
|
||||
cd "${XDG_CONFIG_HOME:-"$HOME/.config/"}/powershell/modules"
|
||||
flux completion >> flux-completions.ps1
|
||||
`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
rootCmd.GenPowerShellCompletion(os.Stdout)
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
completionCmd.AddCommand(completionPowerShellCmd)
|
||||
}
|
||||
52
cmd/flux/completion_zsh.go
Normal file
52
cmd/flux/completion_zsh.go
Normal file
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
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 (
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var completionZshCmd = &cobra.Command{
|
||||
Use: "zsh",
|
||||
Short: "Generates zsh completion scripts",
|
||||
Example: `To load completion run
|
||||
|
||||
. <(flux completion zsh) && compdef _flux flux
|
||||
|
||||
To configure your zsh shell to load completions for each session add to your zshrc
|
||||
|
||||
# ~/.zshrc or ~/.profile
|
||||
command -v flux >/dev/null && . <(flux completion zsh) && compdef _flux flux
|
||||
|
||||
or write a cached file in one of the completion directories in your ${fpath}:
|
||||
|
||||
echo "${fpath// /\n}" | grep -i completion
|
||||
flux completions zsh > _flux
|
||||
|
||||
mv _flux ~/.oh-my-zsh/completions # oh-my-zsh
|
||||
mv _flux ~/.zprezto/modules/completion/external/src/ # zprezto
|
||||
`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
rootCmd.GenZshCompletion(os.Stdout)
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
completionCmd.AddCommand(completionZshCmd)
|
||||
}
|
||||
72
cmd/flux/create.go
Normal file
72
cmd/flux/create.go
Normal file
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
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"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"k8s.io/apimachinery/pkg/util/validation"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var createCmd = &cobra.Command{
|
||||
Use: "create",
|
||||
Short: "Create or update sources and resources",
|
||||
Long: "The create sub-commands generate sources and resources.",
|
||||
}
|
||||
|
||||
var (
|
||||
interval time.Duration
|
||||
export bool
|
||||
labels []string
|
||||
)
|
||||
|
||||
func init() {
|
||||
createCmd.PersistentFlags().DurationVarP(&interval, "interval", "", time.Minute, "source sync interval")
|
||||
createCmd.PersistentFlags().BoolVar(&export, "export", false, "export in YAML format to stdout")
|
||||
createCmd.PersistentFlags().StringSliceVar(&labels, "label", nil,
|
||||
"set labels on the resource (can specify multiple labels with commas: label1=value1,label2=value2)")
|
||||
rootCmd.AddCommand(createCmd)
|
||||
}
|
||||
|
||||
func parseLabels() (map[string]string, error) {
|
||||
result := make(map[string]string)
|
||||
for _, label := range labels {
|
||||
// validate key value pair
|
||||
parts := strings.Split(label, "=")
|
||||
if len(parts) != 2 {
|
||||
return nil, fmt.Errorf("invalid label format '%s', must be key=value", label)
|
||||
}
|
||||
|
||||
// validate label name
|
||||
if errors := validation.IsQualifiedName(parts[0]); len(errors) > 0 {
|
||||
return nil, fmt.Errorf("invalid label '%s': %v", parts[0], errors)
|
||||
}
|
||||
|
||||
// validate label value
|
||||
if errors := validation.IsValidLabelValue(parts[1]); len(errors) > 0 {
|
||||
return nil, fmt.Errorf("invalid label value '%s': %v", parts[1], errors)
|
||||
}
|
||||
|
||||
result[parts[0]] = parts[1]
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
192
cmd/flux/create_alert.go
Normal file
192
cmd/flux/create_alert.go
Normal file
@@ -0,0 +1,192 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"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"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var createAlertCmd = &cobra.Command{
|
||||
Use: "alert [name]",
|
||||
Short: "Create or update a Alert resource",
|
||||
Long: "The create alert command generates a Alert resource.",
|
||||
Example: ` # Create an Alert for kustomization events
|
||||
flux create alert \
|
||||
--event-severity info \
|
||||
--event-source Kustomization/flux-system \
|
||||
--provider-ref slack \
|
||||
flux-system
|
||||
`,
|
||||
RunE: createAlertCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
aProviderRef string
|
||||
aEventSeverity string
|
||||
aEventSources []string
|
||||
)
|
||||
|
||||
func init() {
|
||||
createAlertCmd.Flags().StringVar(&aProviderRef, "provider-ref", "", "reference to provider")
|
||||
createAlertCmd.Flags().StringVar(&aEventSeverity, "event-severity", "", "severity of events to send alerts for")
|
||||
createAlertCmd.Flags().StringArrayVar(&aEventSources, "event-source", []string{}, "sources that should generate alerts (<kind>/<name>)")
|
||||
createCmd.AddCommand(createAlertCmd)
|
||||
}
|
||||
|
||||
func createAlertCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("Alert name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
if aProviderRef == "" {
|
||||
return fmt.Errorf("provider ref is required")
|
||||
}
|
||||
|
||||
eventSources := []notificationv1.CrossNamespaceObjectReference{}
|
||||
for _, eventSource := range aEventSources {
|
||||
kind, name := utils.ParseObjectKindName(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,
|
||||
})
|
||||
}
|
||||
|
||||
if len(eventSources) == 0 {
|
||||
return fmt.Errorf("at least one event source is required")
|
||||
}
|
||||
|
||||
sourceLabels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !export {
|
||||
logger.Generatef("generating Alert")
|
||||
}
|
||||
|
||||
alert := notificationv1.Alert{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
Labels: sourceLabels,
|
||||
},
|
||||
Spec: notificationv1.AlertSpec{
|
||||
ProviderRef: corev1.LocalObjectReference{
|
||||
Name: aProviderRef,
|
||||
},
|
||||
EventSeverity: aEventSeverity,
|
||||
EventSources: eventSources,
|
||||
Suspend: false,
|
||||
},
|
||||
}
|
||||
|
||||
if export {
|
||||
return exportAlert(alert)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("applying Alert")
|
||||
namespacedName, err := upsertAlert(ctx, kubeClient, &alert)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Waitingf("waiting for Alert reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isAlertReady(ctx, kubeClient, namespacedName, &alert)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Alert %s is ready", name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertAlert(ctx context.Context, kubeClient client.Client,
|
||||
alert *notificationv1.Alert) (types.NamespacedName, error) {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: alert.GetNamespace(),
|
||||
Name: alert.GetName(),
|
||||
}
|
||||
|
||||
var existing notificationv1.Alert
|
||||
err := kubeClient.Get(ctx, namespacedName, &existing)
|
||||
if err != nil {
|
||||
if errors.IsNotFound(err) {
|
||||
if err := kubeClient.Create(ctx, alert); err != nil {
|
||||
return namespacedName, err
|
||||
} else {
|
||||
logger.Successf("Alert created")
|
||||
return namespacedName, nil
|
||||
}
|
||||
}
|
||||
return namespacedName, err
|
||||
}
|
||||
|
||||
existing.Labels = alert.Labels
|
||||
existing.Spec = alert.Spec
|
||||
if err := kubeClient.Update(ctx, &existing); err != nil {
|
||||
return namespacedName, err
|
||||
}
|
||||
alert = &existing
|
||||
logger.Successf("Alert updated")
|
||||
return namespacedName, nil
|
||||
}
|
||||
|
||||
func isAlertReady(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, alert *notificationv1.Alert) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, alert)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(alert.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
190
cmd/flux/create_alertprovider.go
Normal file
190
cmd/flux/create_alertprovider.go
Normal file
@@ -0,0 +1,190 @@
|
||||
/*
|
||||
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 (
|
||||
"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"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
)
|
||||
|
||||
var createAlertProviderCmd = &cobra.Command{
|
||||
Use: "alert-provider [name]",
|
||||
Short: "Create or update a Provider resource",
|
||||
Long: "The create alert-provider command generates a Provider resource.",
|
||||
Example: ` # Create a Provider for a Slack channel
|
||||
flux create alert-provider slack \
|
||||
--type slack \
|
||||
--channel general \
|
||||
--address https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK \
|
||||
--secret-ref webhook-url
|
||||
|
||||
# Create a Provider for a Github repository
|
||||
flux create alert-provider github-podinfo \
|
||||
--type github \
|
||||
--address https://github.com/stefanprodan/podinfo \
|
||||
--secret-ref github-token
|
||||
`,
|
||||
RunE: createAlertProviderCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
apType string
|
||||
apChannel string
|
||||
apUsername string
|
||||
apAddress string
|
||||
apSecretRef string
|
||||
)
|
||||
|
||||
func init() {
|
||||
createAlertProviderCmd.Flags().StringVar(&apType, "type", "", "type of provider")
|
||||
createAlertProviderCmd.Flags().StringVar(&apChannel, "channel", "", "channel to send messages to in the case of a chat provider")
|
||||
createAlertProviderCmd.Flags().StringVar(&apUsername, "username", "", "bot username used by the provider")
|
||||
createAlertProviderCmd.Flags().StringVar(&apAddress, "address", "", "path to either the git repository, chat provider or webhook")
|
||||
createAlertProviderCmd.Flags().StringVar(&apSecretRef, "secret-ref", "", "name of secret containing authentication token")
|
||||
createCmd.AddCommand(createAlertProviderCmd)
|
||||
}
|
||||
|
||||
func createAlertProviderCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("Provider name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
if apType == "" {
|
||||
return fmt.Errorf("Provider type is required")
|
||||
}
|
||||
|
||||
sourceLabels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !export {
|
||||
logger.Generatef("generating Provider")
|
||||
}
|
||||
|
||||
provider := notificationv1.Provider{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
Labels: sourceLabels,
|
||||
},
|
||||
Spec: notificationv1.ProviderSpec{
|
||||
Type: apType,
|
||||
Channel: apChannel,
|
||||
Username: apUsername,
|
||||
Address: apAddress,
|
||||
},
|
||||
}
|
||||
|
||||
if apSecretRef != "" {
|
||||
provider.Spec.SecretRef = &corev1.LocalObjectReference{
|
||||
Name: apSecretRef,
|
||||
}
|
||||
}
|
||||
|
||||
if export {
|
||||
return exportAlertProvider(provider)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("applying Provider")
|
||||
namespacedName, err := upsertAlertProvider(ctx, kubeClient, &provider)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Waitingf("waiting for Provider reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isAlertProviderReady(ctx, kubeClient, namespacedName, &provider)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Successf("Provider %s is ready", name)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertAlertProvider(ctx context.Context, kubeClient client.Client,
|
||||
provider *notificationv1.Provider) (types.NamespacedName, error) {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: provider.GetNamespace(),
|
||||
Name: provider.GetName(),
|
||||
}
|
||||
|
||||
var existing notificationv1.Provider
|
||||
err := kubeClient.Get(ctx, namespacedName, &existing)
|
||||
if err != nil {
|
||||
if errors.IsNotFound(err) {
|
||||
if err := kubeClient.Create(ctx, provider); err != nil {
|
||||
return namespacedName, err
|
||||
} else {
|
||||
logger.Successf("Provider created")
|
||||
return namespacedName, nil
|
||||
}
|
||||
}
|
||||
return namespacedName, err
|
||||
}
|
||||
|
||||
existing.Labels = provider.Labels
|
||||
existing.Spec = provider.Spec
|
||||
if err := kubeClient.Update(ctx, &existing); err != nil {
|
||||
return namespacedName, err
|
||||
}
|
||||
provider = &existing
|
||||
logger.Successf("Provider updated")
|
||||
return namespacedName, nil
|
||||
}
|
||||
|
||||
func isAlertProviderReady(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, provider *notificationv1.Provider) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, provider)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(provider.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
248
cmd/flux/create_helmrelease.go
Normal file
248
cmd/flux/create_helmrelease.go
Normal file
@@ -0,0 +1,248 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
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"
|
||||
"sigs.k8s.io/yaml"
|
||||
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
|
||||
)
|
||||
|
||||
var createHelmReleaseCmd = &cobra.Command{
|
||||
Use: "helmrelease [name]",
|
||||
Aliases: []string{"hr"},
|
||||
Short: "Create or update a HelmRelease resource",
|
||||
Long: "The helmrelease create command generates a HelmRelease resource for a given HelmRepository source.",
|
||||
Example: ` # Create a HelmRelease with a chart from a HelmRepository source
|
||||
flux create hr podinfo \
|
||||
--interval=10m \
|
||||
--source=HelmRepository/podinfo \
|
||||
--chart=podinfo \
|
||||
--chart-version=">4.0.0"
|
||||
|
||||
# Create a HelmRelease with a chart from a GitRepository source
|
||||
flux create hr podinfo \
|
||||
--interval=10m \
|
||||
--source=GitRepository/podinfo \
|
||||
--chart=./charts/podinfo
|
||||
|
||||
# Create a HelmRelease with a chart from a Bucket source
|
||||
flux create hr podinfo \
|
||||
--interval=10m \
|
||||
--source=Bucket/podinfo \
|
||||
--chart=./charts/podinfo
|
||||
|
||||
# Create a HelmRelease with values from a local YAML file
|
||||
flux create hr podinfo \
|
||||
--source=HelmRepository/podinfo \
|
||||
--chart=podinfo \
|
||||
--values=./my-values.yaml
|
||||
|
||||
# Create a HelmRelease with a custom release name
|
||||
flux create hr podinfo \
|
||||
--release-name=podinfo-dev
|
||||
--source=HelmRepository/podinfo \
|
||||
--chart=podinfo \
|
||||
|
||||
# Create a HelmRelease targeting another namespace than the resource
|
||||
flux create hr podinfo \
|
||||
--target-namespace=default \
|
||||
--source=HelmRepository/podinfo \
|
||||
--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
|
||||
`,
|
||||
RunE: createHelmReleaseCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
hrName string
|
||||
hrSource flags.HelmChartSource
|
||||
hrDependsOn []string
|
||||
hrChart string
|
||||
hrChartVersion string
|
||||
hrTargetNamespace string
|
||||
hrValuesFile string
|
||||
)
|
||||
|
||||
func init() {
|
||||
createHelmReleaseCmd.Flags().StringVar(&hrName, "release-name", "", "name used for the Helm release, defaults to a composition of '[<target-namespace>-]<HelmRelease-name>'")
|
||||
createHelmReleaseCmd.Flags().Var(&hrSource, "source", hrSource.Description())
|
||||
createHelmReleaseCmd.Flags().StringVar(&hrChart, "chart", "", "Helm chart name or path")
|
||||
createHelmReleaseCmd.Flags().StringVar(&hrChartVersion, "chart-version", "", "Helm chart version, accepts a semver range (ignored for charts from GitRepository sources)")
|
||||
createHelmReleaseCmd.Flags().StringArrayVar(&hrDependsOn, "depends-on", nil, "HelmReleases that must be ready before this release can be installed, supported formats '<name>' and '<namespace>/<name>'")
|
||||
createHelmReleaseCmd.Flags().StringVar(&hrTargetNamespace, "target-namespace", "", "namespace to install this release, defaults to the HelmRelease namespace")
|
||||
createHelmReleaseCmd.Flags().StringVar(&hrValuesFile, "values", "", "local path to the values.yaml file")
|
||||
createCmd.AddCommand(createHelmReleaseCmd)
|
||||
}
|
||||
|
||||
func createHelmReleaseCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("HelmRelease name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
if hrChart == "" {
|
||||
return fmt.Errorf("chart name or path is required")
|
||||
}
|
||||
|
||||
sourceLabels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !export {
|
||||
logger.Generatef("generating HelmRelease")
|
||||
}
|
||||
|
||||
helmRelease := helmv2.HelmRelease{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
Labels: sourceLabels,
|
||||
},
|
||||
Spec: helmv2.HelmReleaseSpec{
|
||||
ReleaseName: hrName,
|
||||
DependsOn: utils.MakeDependsOn(hrDependsOn),
|
||||
Interval: metav1.Duration{
|
||||
Duration: interval,
|
||||
},
|
||||
TargetNamespace: hrTargetNamespace,
|
||||
Chart: helmv2.HelmChartTemplate{
|
||||
Spec: helmv2.HelmChartTemplateSpec{
|
||||
Chart: hrChart,
|
||||
Version: hrChartVersion,
|
||||
SourceRef: helmv2.CrossNamespaceObjectReference{
|
||||
Kind: hrSource.Kind,
|
||||
Name: hrSource.Name,
|
||||
},
|
||||
},
|
||||
},
|
||||
Suspend: false,
|
||||
},
|
||||
}
|
||||
|
||||
if hrValuesFile != "" {
|
||||
data, err := ioutil.ReadFile(hrValuesFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading values from %s failed: %w", hrValuesFile, err)
|
||||
}
|
||||
|
||||
json, err := yaml.YAMLToJSON(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("converting values to JSON from %s failed: %w", hrValuesFile, err)
|
||||
}
|
||||
|
||||
helmRelease.Spec.Values = &apiextensionsv1.JSON{Raw: json}
|
||||
}
|
||||
|
||||
if export {
|
||||
return exportHelmRelease(helmRelease)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("applying HelmRelease")
|
||||
namespacedName, err := upsertHelmRelease(ctx, kubeClient, &helmRelease)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Waitingf("waiting for HelmRelease reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isHelmReleaseReady(ctx, kubeClient, namespacedName, &helmRelease)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("HelmRelease %s is ready", name)
|
||||
|
||||
logger.Successf("applied revision %s", helmRelease.Status.LastAppliedRevision)
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertHelmRelease(ctx context.Context, kubeClient client.Client,
|
||||
helmRelease *helmv2.HelmRelease) (types.NamespacedName, error) {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: helmRelease.GetNamespace(),
|
||||
Name: helmRelease.GetName(),
|
||||
}
|
||||
|
||||
var existing helmv2.HelmRelease
|
||||
err := kubeClient.Get(ctx, namespacedName, &existing)
|
||||
if err != nil {
|
||||
if errors.IsNotFound(err) {
|
||||
if err := kubeClient.Create(ctx, helmRelease); err != nil {
|
||||
return namespacedName, err
|
||||
} else {
|
||||
logger.Successf("HelmRelease created")
|
||||
return namespacedName, nil
|
||||
}
|
||||
}
|
||||
return namespacedName, err
|
||||
}
|
||||
|
||||
existing.Labels = helmRelease.Labels
|
||||
existing.Spec = helmRelease.Spec
|
||||
if err := kubeClient.Update(ctx, &existing); err != nil {
|
||||
return namespacedName, err
|
||||
}
|
||||
helmRelease = &existing
|
||||
logger.Successf("HelmRelease updated")
|
||||
return namespacedName, nil
|
||||
}
|
||||
|
||||
func isHelmReleaseReady(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, helmRelease *helmv2.HelmRelease) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, helmRelease)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Confirm the state we are observing is for the current generation
|
||||
if helmRelease.Generation != helmRelease.Status.ObservedGeneration {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return meta.HasReadyCondition(helmRelease.Status.Conditions), nil
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -30,82 +30,82 @@ import (
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1alpha1"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1alpha1"
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
)
|
||||
|
||||
var createKsCmd = &cobra.Command{
|
||||
Use: "kustomization [name]",
|
||||
Aliases: []string{"ks"},
|
||||
Short: "Create or update a Kustomization resource",
|
||||
Long: "The kustomization source create command generates a Kustomize resource for a given GitRepository source.",
|
||||
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
|
||||
create kustomization contour \
|
||||
flux create kustomization contour \
|
||||
--source=contour \
|
||||
--path="./examples/contour/" \
|
||||
--prune=true \
|
||||
--interval=10m \
|
||||
--validate=client \
|
||||
--validation=client \
|
||||
--health-check="Deployment/contour.projectcontour" \
|
||||
--health-check="DaemonSet/envoy.projectcontour" \
|
||||
--health-check-timeout=3m
|
||||
|
||||
# Create a Kustomization resource that depends on the previous one
|
||||
create kustomization webapp \
|
||||
flux create kustomization webapp \
|
||||
--depends-on=contour \
|
||||
--source=webapp \
|
||||
--path="./deploy/overlays/dev" \
|
||||
--prune=true \
|
||||
--interval=5m \
|
||||
--validate=client
|
||||
--validation=client
|
||||
|
||||
# Create a Kustomization resource that runs under a service account
|
||||
create kustomization webapp \
|
||||
--source=webapp \
|
||||
--path="./deploy/overlays/staging" \
|
||||
# Create a Kustomization resource that references a Bucket
|
||||
flux create kustomization secrets \
|
||||
--source=Bucket/secrets \
|
||||
--prune=true \
|
||||
--interval=5m \
|
||||
--validate=client \
|
||||
--sa-name=reconclier \
|
||||
--sa-namespace=staging
|
||||
--interval=5m
|
||||
`,
|
||||
RunE: createKsCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
ksSource string
|
||||
ksPath string
|
||||
ksPrune bool
|
||||
ksDependsOn []string
|
||||
ksValidate string
|
||||
ksHealthCheck []string
|
||||
ksHealthTimeout time.Duration
|
||||
ksSAName string
|
||||
ksSANamespace string
|
||||
ksSource flags.KustomizationSource
|
||||
ksPath string
|
||||
ksPrune bool
|
||||
ksDependsOn []string
|
||||
ksValidation string
|
||||
ksHealthCheck []string
|
||||
ksHealthTimeout time.Duration
|
||||
ksSAName string
|
||||
ksSANamespace string
|
||||
ksDecryptionProvider flags.DecryptionProvider
|
||||
ksDecryptionSecret string
|
||||
)
|
||||
|
||||
func init() {
|
||||
createKsCmd.Flags().StringVar(&ksSource, "source", "", "GitRepository name")
|
||||
createKsCmd.Flags().Var(&ksSource, "source", ksSource.Description())
|
||||
createKsCmd.Flags().StringVar(&ksPath, "path", "./", "path to the directory containing the Kustomization file")
|
||||
createKsCmd.Flags().BoolVar(&ksPrune, "prune", false, "enable garbage collection")
|
||||
createKsCmd.Flags().StringArrayVar(&ksHealthCheck, "health-check", nil, "workload to be included in the health assessment, in the format '<kind>/<name>.<namespace>'")
|
||||
createKsCmd.Flags().DurationVar(&ksHealthTimeout, "health-check-timeout", 2*time.Minute, "timeout of health checking operations")
|
||||
createKsCmd.Flags().StringVar(&ksValidate, "validate", "", "validate the manifests before applying them on the cluster, can be 'client' or 'server'")
|
||||
createKsCmd.Flags().StringArrayVar(&ksDependsOn, "depends-on", nil, "Kustomization that must be ready before this Kustomization can be applied")
|
||||
createKsCmd.Flags().StringVar(&ksValidation, "validation", "", "validate the manifests before applying them on the cluster, can be 'client' or 'server'")
|
||||
createKsCmd.Flags().StringArrayVar(&ksDependsOn, "depends-on", nil, "Kustomization that must be ready before this Kustomization can be applied, supported formats '<name>' and '<namespace>/<name>'")
|
||||
createKsCmd.Flags().StringVar(&ksSAName, "sa-name", "", "service account name")
|
||||
createKsCmd.Flags().StringVar(&ksSANamespace, "sa-namespace", "", "service account namespace")
|
||||
createKsCmd.Flags().Var(&ksDecryptionProvider, "decryption-provider", ksDecryptionProvider.Description())
|
||||
createKsCmd.Flags().StringVar(&ksDecryptionSecret, "decryption-secret", "", "set the Kubernetes secret name that contains the OpenPGP private keys used for sops decryption")
|
||||
createCmd.AddCommand(createKsCmd)
|
||||
}
|
||||
|
||||
func createKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("kustomization name is required")
|
||||
return fmt.Errorf("Kustomization name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
if ksSource == "" {
|
||||
return fmt.Errorf("source is required")
|
||||
}
|
||||
if ksPath == "" {
|
||||
return fmt.Errorf("path is required")
|
||||
}
|
||||
@@ -113,67 +113,71 @@ func createKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return fmt.Errorf("path must begin with ./")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
if !export {
|
||||
logger.Generatef("generating Kustomization")
|
||||
}
|
||||
|
||||
kubeClient, err := utils.kubeClient(kubeconfig)
|
||||
ksLabels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !export {
|
||||
logger.Generatef("generating kustomization")
|
||||
}
|
||||
|
||||
emptyAPIGroup := ""
|
||||
kustomization := kustomizev1.Kustomization{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
Labels: ksLabels,
|
||||
},
|
||||
Spec: kustomizev1.KustomizationSpec{
|
||||
DependsOn: ksDependsOn,
|
||||
DependsOn: utils.MakeDependsOn(ksDependsOn),
|
||||
Interval: metav1.Duration{
|
||||
Duration: interval,
|
||||
},
|
||||
Path: ksPath,
|
||||
Prune: ksPrune,
|
||||
SourceRef: corev1.TypedLocalObjectReference{
|
||||
APIGroup: &emptyAPIGroup,
|
||||
Kind: "GitRepository",
|
||||
Name: ksSource,
|
||||
SourceRef: kustomizev1.CrossNamespaceSourceReference{
|
||||
Kind: ksSource.Kind,
|
||||
Name: ksSource.Name,
|
||||
},
|
||||
Suspend: false,
|
||||
Validation: ksValidate,
|
||||
Validation: ksValidation,
|
||||
},
|
||||
}
|
||||
|
||||
if len(ksHealthCheck) > 0 {
|
||||
healthChecks := make([]kustomizev1.WorkloadReference, 0)
|
||||
healthChecks := make([]kustomizev1.CrossNamespaceObjectReference, 0)
|
||||
for _, w := range ksHealthCheck {
|
||||
kindObj := strings.Split(w, "/")
|
||||
if len(kindObj) != 2 {
|
||||
return fmt.Errorf("invalid health check '%s' must be in the format 'kind/name.namespace' %v", w, kindObj)
|
||||
}
|
||||
kind := kindObj[0]
|
||||
|
||||
//TODO: (stefan) extend this list with all the kstatus builtin kinds
|
||||
kinds := map[string]bool{
|
||||
"Deployment": true,
|
||||
"DaemonSet": true,
|
||||
"StatefulSet": true,
|
||||
"Deployment": true,
|
||||
"DaemonSet": true,
|
||||
"StatefulSet": true,
|
||||
helmv2.HelmReleaseKind: true,
|
||||
}
|
||||
if !kinds[kind] {
|
||||
return fmt.Errorf("invalid health check kind '%s' can be Deployment, DaemonSet or StatefulSet", kind)
|
||||
return fmt.Errorf("invalid health check kind '%s' can be HelmRelease, Deployment, DaemonSet or StatefulSet", kind)
|
||||
}
|
||||
nameNs := strings.Split(kindObj[1], ".")
|
||||
if len(nameNs) != 2 {
|
||||
return fmt.Errorf("invalid health check '%s' must be in the format 'kind/name.namespace'", w)
|
||||
}
|
||||
|
||||
healthChecks = append(healthChecks, kustomizev1.WorkloadReference{
|
||||
check := kustomizev1.CrossNamespaceObjectReference{
|
||||
Kind: kind,
|
||||
Name: nameNs[0],
|
||||
Namespace: nameNs[1],
|
||||
})
|
||||
}
|
||||
|
||||
if kind == helmv2.HelmReleaseKind {
|
||||
check.APIVersion = helmv2.GroupVersion.String()
|
||||
}
|
||||
healthChecks = append(healthChecks, check)
|
||||
}
|
||||
kustomization.Spec.HealthChecks = healthChecks
|
||||
kustomization.Spec.Timeout = &metav1.Duration{
|
||||
@@ -188,42 +192,47 @@ func createKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
}
|
||||
|
||||
if ksDecryptionProvider != "" {
|
||||
kustomization.Spec.Decryption = &kustomizev1.Decryption{
|
||||
Provider: ksDecryptionProvider.String(),
|
||||
}
|
||||
|
||||
if ksDecryptionSecret != "" {
|
||||
kustomization.Spec.Decryption.SecretRef = &corev1.LocalObjectReference{Name: ksDecryptionSecret}
|
||||
}
|
||||
}
|
||||
|
||||
if export {
|
||||
return exportKs(kustomization)
|
||||
}
|
||||
|
||||
logger.Actionf("applying kustomization")
|
||||
if err := upsertKustomization(ctx, kubeClient, kustomization); err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
logger.Waitingf("waiting for kustomization sync")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isKustomizationReady(ctx, kubeClient, name, namespace)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Successf("kustomization %s is ready", name)
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
err = kubeClient.Get(ctx, namespacedName, &kustomization)
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return fmt.Errorf("kustomization sync failed: %w", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if kustomization.Status.LastAppliedRevision != "" {
|
||||
logger.Successf("applied revision %s", kustomization.Status.LastAppliedRevision)
|
||||
} else {
|
||||
return fmt.Errorf("kustomization sync failed")
|
||||
logger.Actionf("applying Kustomization")
|
||||
namespacedName, err := upsertKustomization(ctx, kubeClient, &kustomization)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Waitingf("waiting for Kustomization reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isKustomizationReady(ctx, kubeClient, namespacedName, &kustomization)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Kustomization %s is ready", name)
|
||||
|
||||
logger.Successf("applied revision %s", kustomization.Status.LastAppliedRevision)
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertKustomization(ctx context.Context, kubeClient client.Client, kustomization kustomizev1.Kustomization) error {
|
||||
func upsertKustomization(ctx context.Context, kubeClient client.Client,
|
||||
kustomization *kustomizev1.Kustomization) (types.NamespacedName, error) {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: kustomization.GetNamespace(),
|
||||
Name: kustomization.GetName(),
|
||||
@@ -233,45 +242,45 @@ func upsertKustomization(ctx context.Context, kubeClient client.Client, kustomiz
|
||||
err := kubeClient.Get(ctx, namespacedName, &existing)
|
||||
if err != nil {
|
||||
if errors.IsNotFound(err) {
|
||||
if err := kubeClient.Create(ctx, &kustomization); err != nil {
|
||||
return err
|
||||
if err := kubeClient.Create(ctx, kustomization); err != nil {
|
||||
return namespacedName, err
|
||||
} else {
|
||||
logger.Successf("kustomization created")
|
||||
return nil
|
||||
logger.Successf("Kustomization created")
|
||||
return namespacedName, nil
|
||||
}
|
||||
}
|
||||
return err
|
||||
return namespacedName, err
|
||||
}
|
||||
|
||||
existing.Labels = kustomization.Labels
|
||||
existing.Spec = kustomization.Spec
|
||||
if err := kubeClient.Update(ctx, &existing); err != nil {
|
||||
return err
|
||||
return namespacedName, err
|
||||
}
|
||||
|
||||
logger.Successf("kustomization updated")
|
||||
return nil
|
||||
kustomization = &existing
|
||||
logger.Successf("Kustomization updated")
|
||||
return namespacedName, nil
|
||||
}
|
||||
|
||||
func isKustomizationReady(ctx context.Context, kubeClient client.Client, name, namespace string) wait.ConditionFunc {
|
||||
func isKustomizationReady(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, kustomization *kustomizev1.Kustomization) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
var kustomization kustomizev1.Kustomization
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
err := kubeClient.Get(ctx, namespacedName, &kustomization)
|
||||
err := kubeClient.Get(ctx, namespacedName, kustomization)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
for _, condition := range kustomization.Status.Conditions {
|
||||
if condition.Type == sourcev1.ReadyCondition {
|
||||
if condition.Status == corev1.ConditionTrue {
|
||||
return true, nil
|
||||
} else if condition.Status == corev1.ConditionFalse {
|
||||
return false, fmt.Errorf(condition.Message)
|
||||
}
|
||||
// Confirm the state we are observing is for the current generation
|
||||
if kustomization.Generation != kustomization.Status.ObservedGeneration {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(kustomization.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
202
cmd/flux/create_receiver.go
Normal file
202
cmd/flux/create_receiver.go
Normal file
@@ -0,0 +1,202 @@
|
||||
/*
|
||||
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 (
|
||||
"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"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
)
|
||||
|
||||
var createReceiverCmd = &cobra.Command{
|
||||
Use: "receiver [name]",
|
||||
Short: "Create or update a Receiver resource",
|
||||
Long: "The create receiver command generates a Receiver resource.",
|
||||
Example: ` # Create a Receiver
|
||||
flux create receiver github-receiver \
|
||||
--type github \
|
||||
--event ping \
|
||||
--event push \
|
||||
--secret-ref webhook-token \
|
||||
--resource GitRepository/webapp \
|
||||
--resource HelmRepository/webapp
|
||||
`,
|
||||
RunE: createReceiverCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
rcvType string
|
||||
rcvSecretRef string
|
||||
rcvEvents []string
|
||||
rcvResources []string
|
||||
)
|
||||
|
||||
func init() {
|
||||
createReceiverCmd.Flags().StringVar(&rcvType, "type", "", "")
|
||||
createReceiverCmd.Flags().StringVar(&rcvSecretRef, "secret-ref", "", "")
|
||||
createReceiverCmd.Flags().StringArrayVar(&rcvEvents, "event", []string{}, "")
|
||||
createReceiverCmd.Flags().StringArrayVar(&rcvResources, "resource", []string{}, "")
|
||||
createCmd.AddCommand(createReceiverCmd)
|
||||
}
|
||||
|
||||
func createReceiverCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("Receiver name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
if rcvType == "" {
|
||||
return fmt.Errorf("Receiver type is required")
|
||||
}
|
||||
|
||||
if rcvSecretRef == "" {
|
||||
return fmt.Errorf("secret ref is required")
|
||||
}
|
||||
|
||||
resources := []notificationv1.CrossNamespaceObjectReference{}
|
||||
for _, resource := range rcvResources {
|
||||
kind, name := utils.ParseObjectKindName(resource)
|
||||
if kind == "" {
|
||||
return fmt.Errorf("invalid event source '%s', must be in format <kind>/<name>", resource)
|
||||
}
|
||||
|
||||
resources = append(resources, notificationv1.CrossNamespaceObjectReference{
|
||||
Kind: kind,
|
||||
Name: name,
|
||||
})
|
||||
}
|
||||
|
||||
if len(resources) == 0 {
|
||||
return fmt.Errorf("atleast one resource is required")
|
||||
}
|
||||
|
||||
sourceLabels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !export {
|
||||
logger.Generatef("generating Receiver")
|
||||
}
|
||||
|
||||
receiver := notificationv1.Receiver{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
Labels: sourceLabels,
|
||||
},
|
||||
Spec: notificationv1.ReceiverSpec{
|
||||
Type: rcvType,
|
||||
Events: rcvEvents,
|
||||
Resources: resources,
|
||||
SecretRef: corev1.LocalObjectReference{
|
||||
Name: rcvSecretRef,
|
||||
},
|
||||
Suspend: false,
|
||||
},
|
||||
}
|
||||
|
||||
if export {
|
||||
return exportReceiver(receiver)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("applying Receiver")
|
||||
namespacedName, err := upsertReceiver(ctx, kubeClient, &receiver)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Waitingf("waiting for Receiver reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isReceiverReady(ctx, kubeClient, namespacedName, &receiver)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Receiver %s is ready", name)
|
||||
|
||||
logger.Successf("generated webhook URL %s", receiver.Status.URL)
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertReceiver(ctx context.Context, kubeClient client.Client,
|
||||
receiver *notificationv1.Receiver) (types.NamespacedName, error) {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: receiver.GetNamespace(),
|
||||
Name: receiver.GetName(),
|
||||
}
|
||||
|
||||
var existing notificationv1.Receiver
|
||||
err := kubeClient.Get(ctx, namespacedName, &existing)
|
||||
if err != nil {
|
||||
if errors.IsNotFound(err) {
|
||||
if err := kubeClient.Create(ctx, receiver); err != nil {
|
||||
return namespacedName, err
|
||||
} else {
|
||||
logger.Successf("Receiver created")
|
||||
return namespacedName, nil
|
||||
}
|
||||
}
|
||||
return namespacedName, err
|
||||
}
|
||||
|
||||
existing.Labels = receiver.Labels
|
||||
existing.Spec = receiver.Spec
|
||||
if err := kubeClient.Update(ctx, &existing); err != nil {
|
||||
return namespacedName, err
|
||||
}
|
||||
receiver = &existing
|
||||
logger.Successf("Receiver updated")
|
||||
return namespacedName, nil
|
||||
}
|
||||
|
||||
func isReceiverReady(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, receiver *notificationv1.Receiver) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, receiver)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(receiver.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
227
cmd/flux/create_source_bucket.go
Normal file
227
cmd/flux/create_source_bucket.go
Normal file
@@ -0,0 +1,227 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"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"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
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.
|
||||
For Buckets with static authentication, the credentials are stored in a Kubernetes secret.`,
|
||||
Example: ` # Create a source from a Buckets using static authentication
|
||||
flux create source bucket podinfo \
|
||||
--bucket-name=podinfo \
|
||||
--endpoint=minio.minio.svc.cluster.local:9000 \
|
||||
--insecure=true \
|
||||
--access-key=myaccesskey \
|
||||
--secret-key=mysecretkey \
|
||||
--interval=10m
|
||||
|
||||
# Create a source from 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
|
||||
`,
|
||||
RunE: createSourceBucketCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
sourceBucketName string
|
||||
sourceBucketProvider = flags.SourceBucketProvider(sourcev1.GenericBucketProvider)
|
||||
sourceBucketEndpoint string
|
||||
sourceBucketAccessKey string
|
||||
sourceBucketSecretKey string
|
||||
sourceBucketRegion string
|
||||
sourceBucketInsecure bool
|
||||
sourceBucketSecretRef string
|
||||
)
|
||||
|
||||
func init() {
|
||||
createSourceBucketCmd.Flags().Var(&sourceBucketProvider, "provider", sourceBucketProvider.Description())
|
||||
createSourceBucketCmd.Flags().StringVar(&sourceBucketName, "bucket-name", "", "the bucket name")
|
||||
createSourceBucketCmd.Flags().StringVar(&sourceBucketEndpoint, "endpoint", "", "the bucket endpoint address")
|
||||
createSourceBucketCmd.Flags().StringVar(&sourceBucketAccessKey, "access-key", "", "the bucket access key")
|
||||
createSourceBucketCmd.Flags().StringVar(&sourceBucketSecretKey, "secret-key", "", "the bucket secret key")
|
||||
createSourceBucketCmd.Flags().StringVar(&sourceBucketRegion, "region", "", "the bucket region")
|
||||
createSourceBucketCmd.Flags().BoolVar(&sourceBucketInsecure, "insecure", false, "for when connecting to a non-TLS S3 HTTP endpoint")
|
||||
createSourceBucketCmd.Flags().StringVar(&sourceBucketSecretRef, "secret-ref", "", "the name of an existing secret containing credentials")
|
||||
|
||||
createSourceCmd.AddCommand(createSourceBucketCmd)
|
||||
}
|
||||
|
||||
func createSourceBucketCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("Bucket source name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
if sourceBucketName == "" {
|
||||
return fmt.Errorf("bucket-name is required")
|
||||
}
|
||||
|
||||
if sourceBucketEndpoint == "" {
|
||||
return fmt.Errorf("endpoint is required")
|
||||
}
|
||||
|
||||
sourceLabels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tmpDir, err := ioutil.TempDir("", name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
bucket := &sourcev1.Bucket{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
Labels: sourceLabels,
|
||||
},
|
||||
Spec: sourcev1.BucketSpec{
|
||||
BucketName: sourceBucketName,
|
||||
Provider: sourceBucketProvider.String(),
|
||||
Insecure: sourceBucketInsecure,
|
||||
Endpoint: sourceBucketEndpoint,
|
||||
Region: sourceBucketRegion,
|
||||
Interval: metav1.Duration{
|
||||
Duration: interval,
|
||||
},
|
||||
},
|
||||
}
|
||||
if sourceHelmSecretRef != "" {
|
||||
bucket.Spec.SecretRef = &corev1.LocalObjectReference{
|
||||
Name: sourceBucketSecretRef,
|
||||
}
|
||||
}
|
||||
|
||||
if export {
|
||||
return exportBucket(*bucket)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Generatef("generating Bucket source")
|
||||
|
||||
if sourceBucketSecretRef == "" {
|
||||
secretName := fmt.Sprintf("bucket-%s", name)
|
||||
|
||||
secret := corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: secretName,
|
||||
Namespace: namespace,
|
||||
},
|
||||
StringData: map[string]string{},
|
||||
}
|
||||
|
||||
if sourceBucketAccessKey != "" && sourceBucketSecretKey != "" {
|
||||
secret.StringData["accesskey"] = sourceBucketAccessKey
|
||||
secret.StringData["secretkey"] = sourceBucketSecretKey
|
||||
}
|
||||
|
||||
if len(secret.StringData) > 0 {
|
||||
logger.Actionf("applying secret with the bucket credentials")
|
||||
if err := upsertSecret(ctx, kubeClient, secret); err != nil {
|
||||
return err
|
||||
}
|
||||
bucket.Spec.SecretRef = &corev1.LocalObjectReference{
|
||||
Name: secretName,
|
||||
}
|
||||
logger.Successf("authentication configured")
|
||||
}
|
||||
}
|
||||
|
||||
logger.Actionf("applying Bucket source")
|
||||
namespacedName, err := upsertBucket(ctx, kubeClient, bucket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Waitingf("waiting for Bucket source reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isBucketReady(ctx, kubeClient, namespacedName, bucket)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Bucket source reconciliation completed")
|
||||
|
||||
if bucket.Status.Artifact == nil {
|
||||
return fmt.Errorf("Bucket source reconciliation but no artifact was found")
|
||||
}
|
||||
logger.Successf("fetched revision: %s", bucket.Status.Artifact.Revision)
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertBucket(ctx context.Context, kubeClient client.Client,
|
||||
bucket *sourcev1.Bucket) (types.NamespacedName, error) {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: bucket.GetNamespace(),
|
||||
Name: bucket.GetName(),
|
||||
}
|
||||
|
||||
var existing sourcev1.Bucket
|
||||
err := kubeClient.Get(ctx, namespacedName, &existing)
|
||||
if err != nil {
|
||||
if errors.IsNotFound(err) {
|
||||
if err := kubeClient.Create(ctx, bucket); err != nil {
|
||||
return namespacedName, err
|
||||
} else {
|
||||
logger.Successf("Bucket source created")
|
||||
return namespacedName, nil
|
||||
}
|
||||
}
|
||||
return namespacedName, err
|
||||
}
|
||||
|
||||
existing.Labels = bucket.Labels
|
||||
existing.Spec = bucket.Spec
|
||||
if err := kubeClient.Update(ctx, &existing); err != nil {
|
||||
return namespacedName, err
|
||||
}
|
||||
bucket = &existing
|
||||
logger.Successf("Bucket source updated")
|
||||
return namespacedName, nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -25,7 +25,11 @@ import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1alpha1"
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"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"
|
||||
@@ -46,35 +50,35 @@ The create source git command generates a GitRepository resource and waits for i
|
||||
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
|
||||
create source git podinfo \
|
||||
flux create source git podinfo \
|
||||
--url=https://github.com/stefanprodan/podinfo \
|
||||
--branch=master
|
||||
|
||||
# Create a source from a Git repository pinned to specific git tag
|
||||
create source git podinfo \
|
||||
flux create source git podinfo \
|
||||
--url=https://github.com/stefanprodan/podinfo \
|
||||
--tag="3.2.3"
|
||||
|
||||
# Create a source from a public Git repository tag that matches a semver range
|
||||
create source git podinfo \
|
||||
flux create source git podinfo \
|
||||
--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 source git podinfo \
|
||||
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
|
||||
# ECDSA P-521 curve public key
|
||||
create source git podinfo \
|
||||
flux create source git podinfo \
|
||||
--url=ssh://git@github.com/stefanprodan/podinfo \
|
||||
--branch=master \
|
||||
--ssh-key-algorithm=ecdsa \
|
||||
--ssh-ecdsa-curve=p521
|
||||
|
||||
# Create a source from a Git repository using basic authentication
|
||||
create source git podinfo \
|
||||
flux create source git podinfo \
|
||||
--url=https://github.com/stefanprodan/podinfo \
|
||||
--username=username \
|
||||
--password=password
|
||||
@@ -83,15 +87,17 @@ For private Git repositories, the basic authentication credentials are stored in
|
||||
}
|
||||
|
||||
var (
|
||||
sourceGitURL string
|
||||
sourceGitBranch string
|
||||
sourceGitTag string
|
||||
sourceGitSemver string
|
||||
sourceGitUsername string
|
||||
sourceGitPassword string
|
||||
sourceGitKeyAlgorithm PublicKeyAlgorithm = "rsa"
|
||||
sourceGitRSABits RSAKeyBits = 2048
|
||||
sourceGitECDSACurve = ECDSACurve{elliptic.P384()}
|
||||
sourceGitURL string
|
||||
sourceGitBranch string
|
||||
sourceGitTag string
|
||||
sourceGitSemver string
|
||||
sourceGitUsername string
|
||||
sourceGitPassword string
|
||||
|
||||
sourceGitKeyAlgorithm flags.PublicKeyAlgorithm = "rsa"
|
||||
sourceGitRSABits flags.RSAKeyBits = 2048
|
||||
sourceGitECDSACurve = flags.ECDSACurve{Curve: elliptic.P384()}
|
||||
sourceGitSecretRef string
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -104,18 +110,19 @@ func init() {
|
||||
createSourceGitCmd.Flags().Var(&sourceGitKeyAlgorithm, "ssh-key-algorithm", sourceGitKeyAlgorithm.Description())
|
||||
createSourceGitCmd.Flags().Var(&sourceGitRSABits, "ssh-rsa-bits", sourceGitRSABits.Description())
|
||||
createSourceGitCmd.Flags().Var(&sourceGitECDSACurve, "ssh-ecdsa-curve", sourceGitECDSACurve.Description())
|
||||
createSourceGitCmd.Flags().StringVarP(&sourceGitSecretRef, "secret-ref", "", "", "the name of an existing secret containing SSH or basic credentials")
|
||||
|
||||
createSourceCmd.AddCommand(createSourceGitCmd)
|
||||
}
|
||||
|
||||
func createSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("source name is required")
|
||||
return fmt.Errorf("GitRepository source name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
if sourceGitURL == "" {
|
||||
return fmt.Errorf("git-url is required")
|
||||
return fmt.Errorf("url is required")
|
||||
}
|
||||
|
||||
tmpDir, err := ioutil.TempDir("", name)
|
||||
@@ -129,10 +136,7 @@ func createSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return fmt.Errorf("git URL parse failed: %w", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.kubeClient(kubeconfig)
|
||||
sourceLabels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -141,6 +145,7 @@ func createSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
Labels: sourceLabels,
|
||||
},
|
||||
Spec: sourcev1.GitRepositorySpec{
|
||||
URL: sourceGitURL,
|
||||
@@ -160,12 +165,27 @@ func createSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
if export {
|
||||
if sourceGitSecretRef != "" {
|
||||
gitRepository.Spec.SecretRef = &corev1.LocalObjectReference{
|
||||
Name: sourceGitSecretRef,
|
||||
}
|
||||
}
|
||||
return exportGit(gitRepository)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
withAuth := false
|
||||
// TODO(hidde): move all auth prep to separate func?
|
||||
if u.Scheme == "ssh" {
|
||||
if sourceGitSecretRef != "" {
|
||||
withAuth = true
|
||||
} else if u.Scheme == "ssh" {
|
||||
logger.Actionf("generating deploy key pair")
|
||||
pair, err := generateKeyPair(ctx)
|
||||
if err != nil {
|
||||
@@ -227,42 +247,35 @@ func createSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
logger.Successf("authentication configured")
|
||||
}
|
||||
|
||||
logger.Generatef("generating source")
|
||||
logger.Generatef("generating GitRepository source")
|
||||
|
||||
if withAuth {
|
||||
secretName := name
|
||||
if sourceGitSecretRef != "" {
|
||||
secretName = sourceGitSecretRef
|
||||
}
|
||||
gitRepository.Spec.SecretRef = &corev1.LocalObjectReference{
|
||||
Name: name,
|
||||
Name: secretName,
|
||||
}
|
||||
}
|
||||
|
||||
logger.Actionf("applying source")
|
||||
if err := upsertGitRepository(ctx, kubeClient, gitRepository); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Waitingf("waiting for git sync")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isGitRepositoryReady(ctx, kubeClient, name, namespace)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Successf("git sync completed")
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
err = kubeClient.Get(ctx, namespacedName, &gitRepository)
|
||||
logger.Actionf("applying GitRepository source")
|
||||
namespacedName, err := upsertGitRepository(ctx, kubeClient, &gitRepository)
|
||||
if err != nil {
|
||||
return fmt.Errorf("git sync failed: %w", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if gitRepository.Status.Artifact != nil {
|
||||
logger.Successf("fetched revision: %s", gitRepository.Status.Artifact.Revision)
|
||||
} else {
|
||||
return fmt.Errorf("git sync failed, artifact not found")
|
||||
logger.Waitingf("waiting for GitRepository source reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isGitRepositoryReady(ctx, kubeClient, namespacedName, &gitRepository)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("GitRepository source reconciliation completed")
|
||||
|
||||
if gitRepository.Status.Artifact == nil {
|
||||
return fmt.Errorf("GitRepository source reconciliation completed but no artifact was found")
|
||||
}
|
||||
logger.Successf("fetched revision: %s", gitRepository.Status.Artifact.Revision)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -323,7 +336,8 @@ func upsertSecret(ctx context.Context, kubeClient client.Client, secret corev1.S
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertGitRepository(ctx context.Context, kubeClient client.Client, gitRepository sourcev1.GitRepository) error {
|
||||
func upsertGitRepository(ctx context.Context, kubeClient client.Client,
|
||||
gitRepository *sourcev1.GitRepository) (types.NamespacedName, error) {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: gitRepository.GetNamespace(),
|
||||
Name: gitRepository.GetName(),
|
||||
@@ -333,45 +347,40 @@ func upsertGitRepository(ctx context.Context, kubeClient client.Client, gitRepos
|
||||
err := kubeClient.Get(ctx, namespacedName, &existing)
|
||||
if err != nil {
|
||||
if errors.IsNotFound(err) {
|
||||
if err := kubeClient.Create(ctx, &gitRepository); err != nil {
|
||||
return err
|
||||
if err := kubeClient.Create(ctx, gitRepository); err != nil {
|
||||
return namespacedName, err
|
||||
} else {
|
||||
logger.Successf("source created")
|
||||
return nil
|
||||
logger.Successf("GitRepository source created")
|
||||
return namespacedName, nil
|
||||
}
|
||||
}
|
||||
return err
|
||||
return namespacedName, err
|
||||
}
|
||||
|
||||
existing.Labels = gitRepository.Labels
|
||||
existing.Spec = gitRepository.Spec
|
||||
if err := kubeClient.Update(ctx, &existing); err != nil {
|
||||
return err
|
||||
return namespacedName, err
|
||||
}
|
||||
|
||||
logger.Successf("source updated")
|
||||
return nil
|
||||
gitRepository = &existing
|
||||
logger.Successf("GitRepository source updated")
|
||||
return namespacedName, nil
|
||||
}
|
||||
|
||||
func isGitRepositoryReady(ctx context.Context, kubeClient client.Client, name, namespace string) wait.ConditionFunc {
|
||||
func isGitRepositoryReady(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, gitRepository *sourcev1.GitRepository) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
var gitRepository sourcev1.GitRepository
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
err := kubeClient.Get(ctx, namespacedName, &gitRepository)
|
||||
err := kubeClient.Get(ctx, namespacedName, gitRepository)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
for _, condition := range gitRepository.Status.Conditions {
|
||||
if condition.Type == sourcev1.ReadyCondition {
|
||||
if condition.Status == corev1.ConditionTrue {
|
||||
return true, nil
|
||||
} else if condition.Status == corev1.ConditionFalse {
|
||||
return false, fmt.Errorf(condition.Message)
|
||||
}
|
||||
if c := meta.GetCondition(gitRepository.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
244
cmd/flux/create_source_helm.go
Normal file
244
cmd/flux/create_source_helm.go
Normal file
@@ -0,0 +1,244 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"os"
|
||||
|
||||
"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"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
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.
|
||||
For private Helm repositories, the basic authentication credentials are stored in a Kubernetes secret.`,
|
||||
Example: ` # Create a source from 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
|
||||
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
|
||||
flux create source helm podinfo \
|
||||
--url=https://stefanprodan.github.io/podinfo \
|
||||
--cert-file=./cert.crt \
|
||||
--key-file=./key.crt \
|
||||
--ca-file=./ca.crt
|
||||
`,
|
||||
RunE: createSourceHelmCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
sourceHelmURL string
|
||||
sourceHelmUsername string
|
||||
sourceHelmPassword string
|
||||
sourceHelmCertFile string
|
||||
sourceHelmKeyFile string
|
||||
sourceHelmCAFile string
|
||||
sourceHelmSecretRef string
|
||||
)
|
||||
|
||||
func init() {
|
||||
createSourceHelmCmd.Flags().StringVar(&sourceHelmURL, "url", "", "Helm repository address")
|
||||
createSourceHelmCmd.Flags().StringVarP(&sourceHelmUsername, "username", "u", "", "basic authentication username")
|
||||
createSourceHelmCmd.Flags().StringVarP(&sourceHelmPassword, "password", "p", "", "basic authentication password")
|
||||
createSourceHelmCmd.Flags().StringVar(&sourceHelmCertFile, "cert-file", "", "TLS authentication cert file path")
|
||||
createSourceHelmCmd.Flags().StringVar(&sourceHelmKeyFile, "key-file", "", "TLS authentication key file path")
|
||||
createSourceHelmCmd.Flags().StringVar(&sourceHelmCAFile, "ca-file", "", "TLS authentication CA file path")
|
||||
createSourceHelmCmd.Flags().StringVarP(&sourceHelmSecretRef, "secret-ref", "", "", "the name of an existing secret containing TLS or basic auth credentials")
|
||||
|
||||
createSourceCmd.AddCommand(createSourceHelmCmd)
|
||||
}
|
||||
|
||||
func createSourceHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("HelmRepository source name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
if sourceHelmURL == "" {
|
||||
return fmt.Errorf("url is required")
|
||||
}
|
||||
|
||||
sourceLabels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tmpDir, err := ioutil.TempDir("", name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
if _, err := url.Parse(sourceHelmURL); err != nil {
|
||||
return fmt.Errorf("url parse failed: %w", err)
|
||||
}
|
||||
|
||||
helmRepository := &sourcev1.HelmRepository{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
Labels: sourceLabels,
|
||||
},
|
||||
Spec: sourcev1.HelmRepositorySpec{
|
||||
URL: sourceHelmURL,
|
||||
Interval: metav1.Duration{
|
||||
Duration: interval,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if sourceHelmSecretRef != "" {
|
||||
helmRepository.Spec.SecretRef = &corev1.LocalObjectReference{
|
||||
Name: sourceHelmSecretRef,
|
||||
}
|
||||
}
|
||||
|
||||
if export {
|
||||
return exportHelmRepository(*helmRepository)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Generatef("generating HelmRepository source")
|
||||
if sourceHelmSecretRef == "" {
|
||||
secretName := fmt.Sprintf("helm-%s", name)
|
||||
|
||||
secret := corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: secretName,
|
||||
Namespace: namespace,
|
||||
},
|
||||
StringData: map[string]string{},
|
||||
}
|
||||
|
||||
if sourceHelmUsername != "" && sourceHelmPassword != "" {
|
||||
secret.StringData["username"] = sourceHelmUsername
|
||||
secret.StringData["password"] = sourceHelmPassword
|
||||
}
|
||||
|
||||
if sourceHelmCertFile != "" && sourceHelmKeyFile != "" {
|
||||
cert, err := ioutil.ReadFile(sourceHelmCertFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read repository cert file '%s': %w", sourceHelmCertFile, err)
|
||||
}
|
||||
secret.StringData["certFile"] = string(cert)
|
||||
|
||||
key, err := ioutil.ReadFile(sourceHelmKeyFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read repository key file '%s': %w", sourceHelmKeyFile, err)
|
||||
}
|
||||
secret.StringData["keyFile"] = string(key)
|
||||
}
|
||||
|
||||
if sourceHelmCAFile != "" {
|
||||
ca, err := ioutil.ReadFile(sourceHelmCAFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read repository CA file '%s': %w", sourceHelmCAFile, err)
|
||||
}
|
||||
secret.StringData["caFile"] = string(ca)
|
||||
}
|
||||
|
||||
if len(secret.StringData) > 0 {
|
||||
logger.Actionf("applying secret with repository credentials")
|
||||
if err := upsertSecret(ctx, kubeClient, secret); err != nil {
|
||||
return err
|
||||
}
|
||||
helmRepository.Spec.SecretRef = &corev1.LocalObjectReference{
|
||||
Name: secretName,
|
||||
}
|
||||
logger.Successf("authentication configured")
|
||||
}
|
||||
}
|
||||
|
||||
logger.Actionf("applying HelmRepository source")
|
||||
namespacedName, err := upsertHelmRepository(ctx, kubeClient, helmRepository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Waitingf("waiting for HelmRepository source reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isHelmRepositoryReady(ctx, kubeClient, namespacedName, helmRepository)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("HelmRepository source reconciliation completed")
|
||||
|
||||
if helmRepository.Status.Artifact == nil {
|
||||
return fmt.Errorf("HelmRepository source reconciliation completed but no artifact was found")
|
||||
}
|
||||
logger.Successf("fetched revision: %s", helmRepository.Status.Artifact.Revision)
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertHelmRepository(ctx context.Context, kubeClient client.Client,
|
||||
helmRepository *sourcev1.HelmRepository) (types.NamespacedName, error) {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: helmRepository.GetNamespace(),
|
||||
Name: helmRepository.GetName(),
|
||||
}
|
||||
|
||||
var existing sourcev1.HelmRepository
|
||||
err := kubeClient.Get(ctx, namespacedName, &existing)
|
||||
if err != nil {
|
||||
if errors.IsNotFound(err) {
|
||||
if err := kubeClient.Create(ctx, helmRepository); err != nil {
|
||||
return namespacedName, err
|
||||
} else {
|
||||
logger.Successf("source created")
|
||||
return namespacedName, nil
|
||||
}
|
||||
}
|
||||
return namespacedName, err
|
||||
}
|
||||
|
||||
existing.Labels = helmRepository.Labels
|
||||
existing.Spec = helmRepository.Spec
|
||||
if err := kubeClient.Update(ctx, &existing); err != nil {
|
||||
return namespacedName, err
|
||||
}
|
||||
helmRepository = &existing
|
||||
logger.Successf("source updated")
|
||||
return namespacedName, nil
|
||||
}
|
||||
258
cmd/flux/create_tenant.go
Normal file
258
cmd/flux/create_tenant.go
Normal file
@@ -0,0 +1,258 @@
|
||||
/*
|
||||
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 (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
rbacv1 "k8s.io/api/rbac/v1"
|
||||
"k8s.io/apimachinery/pkg/api/equality"
|
||||
"k8s.io/apimachinery/pkg/api/errors"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/validation"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
var createTenantCmd = &cobra.Command{
|
||||
Use: "tenant",
|
||||
Short: "Create or update a tenant",
|
||||
Long: `
|
||||
The create tenant command generates namespaces 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 \
|
||||
--with-namespace=frontend \
|
||||
--label=environment=dev
|
||||
|
||||
# Generate tenant namespaces and role bindings in YAML format
|
||||
flux create tenant dev-team \
|
||||
--with-namespace=frontend \
|
||||
--with-namespace=backend \
|
||||
--export > dev-team.yaml
|
||||
`,
|
||||
RunE: createTenantCmdRun,
|
||||
}
|
||||
|
||||
const (
|
||||
tenantLabel = "toolkit.fluxcd.io/tenant"
|
||||
tenantRoleBinding = "gotk-reconciler"
|
||||
)
|
||||
|
||||
var (
|
||||
tenantNamespaces []string
|
||||
tenantClusterRole string
|
||||
)
|
||||
|
||||
func init() {
|
||||
createTenantCmd.Hidden = true
|
||||
createTenantCmd.Flags().StringSliceVar(&tenantNamespaces, "with-namespace", nil, "namespace belonging to this tenant")
|
||||
createTenantCmd.Flags().StringVar(&tenantClusterRole, "cluster-role", "cluster-admin", "cluster role of the tenant role binding")
|
||||
createCmd.AddCommand(createTenantCmd)
|
||||
}
|
||||
|
||||
func createTenantCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("tenant name is required")
|
||||
}
|
||||
tenant := args[0]
|
||||
if err := validation.IsQualifiedName(tenant); len(err) > 0 {
|
||||
return fmt.Errorf("invalid tenant name '%s': %v", tenant, err)
|
||||
}
|
||||
|
||||
if tenantClusterRole == "" {
|
||||
return fmt.Errorf("cluster-role is required")
|
||||
}
|
||||
|
||||
if tenantNamespaces == nil {
|
||||
return fmt.Errorf("with-namespace is required")
|
||||
}
|
||||
|
||||
var namespaces []corev1.Namespace
|
||||
var roleBindings []rbacv1.RoleBinding
|
||||
|
||||
for _, ns := range tenantNamespaces {
|
||||
if err := validation.IsQualifiedName(ns); len(err) > 0 {
|
||||
return fmt.Errorf("invalid namespace '%s': %v", ns, err)
|
||||
}
|
||||
|
||||
objLabels, err := parseLabels()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
objLabels[tenantLabel] = tenant
|
||||
|
||||
namespace := corev1.Namespace{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: ns,
|
||||
Labels: objLabels,
|
||||
},
|
||||
}
|
||||
namespaces = append(namespaces, namespace)
|
||||
|
||||
roleBinding := rbacv1.RoleBinding{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: tenantRoleBinding,
|
||||
Namespace: ns,
|
||||
Labels: objLabels,
|
||||
},
|
||||
Subjects: []rbacv1.Subject{
|
||||
{
|
||||
APIGroup: "rbac.authorization.k8s.io",
|
||||
Kind: "User",
|
||||
Name: fmt.Sprintf("gotk:%s:reconciler", ns),
|
||||
},
|
||||
},
|
||||
RoleRef: rbacv1.RoleRef{
|
||||
APIGroup: "rbac.authorization.k8s.io",
|
||||
Kind: "ClusterRole",
|
||||
Name: tenantClusterRole,
|
||||
},
|
||||
}
|
||||
roleBindings = append(roleBindings, roleBinding)
|
||||
}
|
||||
|
||||
if export {
|
||||
for i, _ := range tenantNamespaces {
|
||||
if err := exportTenant(namespaces[i], roleBindings[1]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for i, _ := range tenantNamespaces {
|
||||
logger.Actionf("applying namespace %s", namespaces[i].Name)
|
||||
if err := upsertNamespace(ctx, kubeClient, namespaces[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("applying role binding %s", roleBindings[i].Name)
|
||||
if err := upsertRoleBinding(ctx, kubeClient, roleBindings[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
logger.Successf("tenant setup completed")
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertNamespace(ctx context.Context, kubeClient client.Client, namespace corev1.Namespace) error {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace.GetNamespace(),
|
||||
Name: namespace.GetName(),
|
||||
}
|
||||
|
||||
var existing corev1.Namespace
|
||||
err := kubeClient.Get(ctx, namespacedName, &existing)
|
||||
if err != nil {
|
||||
if errors.IsNotFound(err) {
|
||||
if err := kubeClient.Create(ctx, &namespace); err != nil {
|
||||
return err
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if !equality.Semantic.DeepDerivative(namespace.Labels, existing.Labels) {
|
||||
existing.Labels = namespace.Labels
|
||||
if err := kubeClient.Update(ctx, &existing); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func upsertRoleBinding(ctx context.Context, kubeClient client.Client, roleBinding rbacv1.RoleBinding) error {
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: roleBinding.GetNamespace(),
|
||||
Name: roleBinding.GetName(),
|
||||
}
|
||||
|
||||
var existing rbacv1.RoleBinding
|
||||
err := kubeClient.Get(ctx, namespacedName, &existing)
|
||||
if err != nil {
|
||||
if errors.IsNotFound(err) {
|
||||
if err := kubeClient.Create(ctx, &roleBinding); err != nil {
|
||||
return err
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if !equality.Semantic.DeepDerivative(roleBinding.Subjects, existing.Subjects) ||
|
||||
!equality.Semantic.DeepDerivative(roleBinding.RoleRef, existing.RoleRef) ||
|
||||
!equality.Semantic.DeepDerivative(roleBinding.Labels, existing.Labels) {
|
||||
if err := kubeClient.Delete(ctx, &existing); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := kubeClient.Create(ctx, &roleBinding); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportTenant(namespace corev1.Namespace, roleBinding rbacv1.RoleBinding) error {
|
||||
namespace.TypeMeta = metav1.TypeMeta{
|
||||
APIVersion: "v1",
|
||||
Kind: "Namespace",
|
||||
}
|
||||
data, err := yaml.Marshal(namespace)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
data = bytes.Replace(data, []byte("spec: {}\n"), []byte(""), 1)
|
||||
fmt.Println(resourceToString(data))
|
||||
|
||||
roleBinding.TypeMeta = metav1.TypeMeta{
|
||||
APIVersion: "rbac.authorization.k8s.io/v1",
|
||||
Kind: "RoleBinding",
|
||||
}
|
||||
data, err = yaml.Marshal(roleBinding)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
88
cmd/flux/delete_alert.go
Normal file
88
cmd/flux/delete_alert.go
Normal file
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
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 (
|
||||
"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"
|
||||
)
|
||||
|
||||
var deleteAlertCmd = &cobra.Command{
|
||||
Use: "alert [name]",
|
||||
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,
|
||||
}
|
||||
|
||||
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(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
var alert notificationv1.Alert
|
||||
err = kubeClient.Get(ctx, namespacedName, &alert)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !deleteSilent {
|
||||
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, namespace)
|
||||
err = kubeClient.Delete(ctx, &alert)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("alert deleted")
|
||||
|
||||
return nil
|
||||
}
|
||||
88
cmd/flux/delete_alertprovider.go
Normal file
88
cmd/flux/delete_alertprovider.go
Normal file
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
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 (
|
||||
"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"
|
||||
)
|
||||
|
||||
var deleteAlertProviderCmd = &cobra.Command{
|
||||
Use: "alert-provider [name]",
|
||||
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,
|
||||
}
|
||||
|
||||
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(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
var alertProvider notificationv1.Provider
|
||||
err = kubeClient.Get(ctx, namespacedName, &alertProvider)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !deleteSilent {
|
||||
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, namespace)
|
||||
err = kubeClient.Delete(ctx, &alertProvider)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("provider deleted")
|
||||
|
||||
return nil
|
||||
}
|
||||
92
cmd/flux/delete_helmrelease.go
Normal file
92
cmd/flux/delete_helmrelease.go
Normal file
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/manifoldco/promptui"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
|
||||
)
|
||||
|
||||
var deleteHelmReleaseCmd = &cobra.Command{
|
||||
Use: "helmrelease [name]",
|
||||
Aliases: []string{"hr"},
|
||||
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
|
||||
`,
|
||||
RunE: deleteHelmReleaseCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
deleteCmd.AddCommand(deleteHelmReleaseCmd)
|
||||
}
|
||||
|
||||
func deleteHelmReleaseCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("release name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
var helmRelease helmv2.HelmRelease
|
||||
err = kubeClient.Get(ctx, namespacedName, &helmRelease)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !deleteSilent {
|
||||
if !helmRelease.Spec.Suspend {
|
||||
logger.Waitingf("This action will remove the Kubernetes objects previously applied by the %s Helm release!", name)
|
||||
}
|
||||
prompt := promptui.Prompt{
|
||||
Label: "Are you sure you want to delete this Helm release",
|
||||
IsConfirm: true,
|
||||
}
|
||||
if _, err := prompt.Run(); err != nil {
|
||||
return fmt.Errorf("aborting")
|
||||
}
|
||||
}
|
||||
|
||||
logger.Actionf("deleting release %s in %s namespace", name, namespace)
|
||||
err = kubeClient.Delete(ctx, &helmRelease)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("release deleted")
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -20,7 +20,8 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1alpha1"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
"github.com/manifoldco/promptui"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
@@ -31,7 +32,10 @@ var deleteKsCmd = &cobra.Command{
|
||||
Aliases: []string{"ks"},
|
||||
Short: "Delete a Kustomization resource",
|
||||
Long: "The delete kustomization command deletes the given Kustomization from the cluster.",
|
||||
RunE: deleteKsCmdRun,
|
||||
Example: ` # Delete a kustomization and the Kubernetes resources created by it
|
||||
flux delete kustomization podinfo
|
||||
`,
|
||||
RunE: deleteKsCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -47,7 +51,7 @@ func deleteKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.kubeClient(kubeconfig)
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
88
cmd/flux/delete_receiver.go
Normal file
88
cmd/flux/delete_receiver.go
Normal file
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
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 (
|
||||
"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"
|
||||
)
|
||||
|
||||
var deleteReceiverCmd = &cobra.Command{
|
||||
Use: "receiver [name]",
|
||||
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,
|
||||
}
|
||||
|
||||
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(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
var receiver notificationv1.Receiver
|
||||
err = kubeClient.Get(ctx, namespacedName, &receiver)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !deleteSilent {
|
||||
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, namespace)
|
||||
err = kubeClient.Delete(ctx, &receiver)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("receiver deleted")
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
87
cmd/flux/delete_source_bucket.go
Normal file
87
cmd/flux/delete_source_bucket.go
Normal file
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
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 (
|
||||
"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"
|
||||
)
|
||||
|
||||
var deleteSourceBucketCmd = &cobra.Command{
|
||||
Use: "bucket [name]",
|
||||
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
|
||||
`,
|
||||
RunE: deleteSourceBucketCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
deleteSourceCmd.AddCommand(deleteSourceBucketCmd)
|
||||
}
|
||||
|
||||
func deleteSourceBucketCmdRun(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(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
var bucket sourcev1.Bucket
|
||||
err = kubeClient.Get(ctx, namespacedName, &bucket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !deleteSilent {
|
||||
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, namespace)
|
||||
err = kubeClient.Delete(ctx, &bucket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("source deleted")
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -20,7 +20,8 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1alpha1"
|
||||
"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"
|
||||
@@ -30,7 +31,10 @@ var deleteSourceGitCmd = &cobra.Command{
|
||||
Use: "git [name]",
|
||||
Short: "Delete a GitRepository source",
|
||||
Long: "The delete source git command deletes the given GitRepository from the cluster.",
|
||||
RunE: deleteSourceGitCmdRun,
|
||||
Example: ` # Delete a Git repository
|
||||
flux delete source git podinfo
|
||||
`,
|
||||
RunE: deleteSourceGitCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -46,7 +50,7 @@ func deleteSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.kubeClient(kubeconfig)
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
87
cmd/flux/delete_source_helm.go
Normal file
87
cmd/flux/delete_source_helm.go
Normal file
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
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 (
|
||||
"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"
|
||||
)
|
||||
|
||||
var deleteSourceHelmCmd = &cobra.Command{
|
||||
Use: "helm [name]",
|
||||
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
|
||||
`,
|
||||
RunE: deleteSourceHelmCmdRun,
|
||||
}
|
||||
|
||||
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(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
var helmRepository sourcev1.HelmRepository
|
||||
err = kubeClient.Get(ctx, namespacedName, &helmRepository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !deleteSilent {
|
||||
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, namespace)
|
||||
err = kubeClient.Delete(ctx, &helmRepository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("source deleted")
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -17,6 +17,8 @@ limitations under the License.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
@@ -35,3 +37,9 @@ func init() {
|
||||
|
||||
rootCmd.AddCommand(exportCmd)
|
||||
}
|
||||
|
||||
func resourceToString(data []byte) string {
|
||||
data = bytes.Replace(data, []byte(" creationTimestamp: null\n"), []byte(""), 1)
|
||||
data = bytes.Replace(data, []byte("status: {}\n"), []byte(""), 1)
|
||||
return string(data)
|
||||
}
|
||||
120
cmd/flux/export_alert.go
Normal file
120
cmd/flux/export_alert.go
Normal file
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
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 (
|
||||
"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"
|
||||
)
|
||||
|
||||
var exportAlertCmd = &cobra.Command{
|
||||
Use: "alert [name]",
|
||||
Short: "Export Alert resources in YAML format",
|
||||
Long: "The export alert command exports one or all Alert resources in YAML format.",
|
||||
Example: ` # Export all Alert resources
|
||||
flux export alert --all > alerts.yaml
|
||||
|
||||
# Export a Alert
|
||||
flux export alert main > main.yaml
|
||||
`,
|
||||
RunE: exportAlertCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportCmd.AddCommand(exportAlertCmd)
|
||||
}
|
||||
|
||||
func exportAlertCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if !exportAll && len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportAll {
|
||||
var list notificationv1.AlertList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no alerts found in %s namespace", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, alert := range list.Items {
|
||||
if err := exportAlert(alert); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
name := args[0]
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: 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 {
|
||||
gvk := notificationv1.GroupVersion.WithKind("Alert")
|
||||
export := notificationv1.Alert{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
Kind: gvk.Kind,
|
||||
APIVersion: gvk.GroupVersion().String(),
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: alert.Name,
|
||||
Namespace: alert.Namespace,
|
||||
Labels: alert.Labels,
|
||||
Annotations: alert.Annotations,
|
||||
},
|
||||
Spec: alert.Spec,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(export)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
}
|
||||
120
cmd/flux/export_alertprovider.go
Normal file
120
cmd/flux/export_alertprovider.go
Normal file
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
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 (
|
||||
"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"
|
||||
)
|
||||
|
||||
var exportAlertProviderCmd = &cobra.Command{
|
||||
Use: "alert-provider [name]",
|
||||
Short: "Export Provider resources in YAML format",
|
||||
Long: "The export alert-provider command exports one or all Provider resources in YAML format.",
|
||||
Example: ` # Export all Provider resources
|
||||
flux export alert-provider --all > alert-providers.yaml
|
||||
|
||||
# Export a Provider
|
||||
flux export alert-provider slack > slack.yaml
|
||||
`,
|
||||
RunE: exportAlertProviderCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportCmd.AddCommand(exportAlertProviderCmd)
|
||||
}
|
||||
|
||||
func exportAlertProviderCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if !exportAll && len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportAll {
|
||||
var list notificationv1.ProviderList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no alertproviders found in %s namespace", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, alertProvider := range list.Items {
|
||||
if err := exportAlertProvider(alertProvider); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
name := args[0]
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: 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 {
|
||||
gvk := notificationv1.GroupVersion.WithKind("Provider")
|
||||
export := notificationv1.Provider{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
Kind: gvk.Kind,
|
||||
APIVersion: gvk.GroupVersion().String(),
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: alertProvider.Name,
|
||||
Namespace: alertProvider.Namespace,
|
||||
Labels: alertProvider.Labels,
|
||||
Annotations: alertProvider.Annotations,
|
||||
},
|
||||
Spec: alertProvider.Spec,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(export)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
}
|
||||
121
cmd/flux/export_helmrelease.go
Normal file
121
cmd/flux/export_helmrelease.go
Normal file
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
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 (
|
||||
"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"
|
||||
)
|
||||
|
||||
var exportHelmReleaseCmd = &cobra.Command{
|
||||
Use: "helmrelease [name]",
|
||||
Aliases: []string{"hr"},
|
||||
Short: "Export HelmRelease resources in YAML format",
|
||||
Long: "The export helmrelease command exports one or all HelmRelease resources in YAML format.",
|
||||
Example: ` # Export all HelmRelease resources
|
||||
flux export helmrelease --all > kustomizations.yaml
|
||||
|
||||
# Export a HelmRelease
|
||||
flux export hr my-app > app-release.yaml
|
||||
`,
|
||||
RunE: exportHelmReleaseCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportCmd.AddCommand(exportHelmReleaseCmd)
|
||||
}
|
||||
|
||||
func exportHelmReleaseCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if !exportAll && len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportAll {
|
||||
var list helmv2.HelmReleaseList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no helmrelease found in %s namespace", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, helmRelease := range list.Items {
|
||||
if err := exportHelmRelease(helmRelease); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
name := args[0]
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: 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 {
|
||||
gvk := helmv2.GroupVersion.WithKind(helmv2.HelmReleaseKind)
|
||||
export := helmv2.HelmRelease{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
Kind: gvk.Kind,
|
||||
APIVersion: gvk.GroupVersion().String(),
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: helmRelease.Name,
|
||||
Namespace: helmRelease.Namespace,
|
||||
Labels: helmRelease.Labels,
|
||||
Annotations: helmRelease.Annotations,
|
||||
},
|
||||
Spec: helmRelease.Spec,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(export)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -20,12 +20,14 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1alpha1"
|
||||
"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"
|
||||
)
|
||||
|
||||
var exportKsCmd = &cobra.Command{
|
||||
@@ -34,10 +36,10 @@ var exportKsCmd = &cobra.Command{
|
||||
Short: "Export Kustomization resources in YAML format",
|
||||
Long: "The export kustomization command exports one or all Kustomization resources in YAML format.",
|
||||
Example: ` # Export all Kustomization resources
|
||||
export kustomization --all > kustomizations.yaml
|
||||
flux export kustomization --all > kustomizations.yaml
|
||||
|
||||
# Export a Kustomization
|
||||
export kustomization my-app > kustomization.yaml
|
||||
flux export kustomization my-app > kustomization.yaml
|
||||
`,
|
||||
RunE: exportKsCmdRun,
|
||||
}
|
||||
@@ -54,7 +56,7 @@ func exportKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.kubeClient(kubeconfig)
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -100,8 +102,10 @@ func exportKs(kustomization kustomizev1.Kustomization) error {
|
||||
APIVersion: gvk.GroupVersion().String(),
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: kustomization.Name,
|
||||
Namespace: kustomization.Namespace,
|
||||
Name: kustomization.Name,
|
||||
Namespace: kustomization.Namespace,
|
||||
Labels: kustomization.Labels,
|
||||
Annotations: kustomization.Annotations,
|
||||
},
|
||||
Spec: kustomization.Spec,
|
||||
}
|
||||
@@ -112,6 +116,6 @@ func exportKs(kustomization kustomizev1.Kustomization) error {
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(string(data))
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
}
|
||||
120
cmd/flux/export_receiver.go
Normal file
120
cmd/flux/export_receiver.go
Normal file
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
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 (
|
||||
"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"
|
||||
)
|
||||
|
||||
var exportReceiverCmd = &cobra.Command{
|
||||
Use: "receiver [name]",
|
||||
Short: "Export Receiver resources in YAML format",
|
||||
Long: "The export receiver command exports one or all Receiver resources in YAML format.",
|
||||
Example: ` # Export all Receiver resources
|
||||
flux export receiver --all > receivers.yaml
|
||||
|
||||
# Export a Receiver
|
||||
flux export receiver main > main.yaml
|
||||
`,
|
||||
RunE: exportReceiverCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportCmd.AddCommand(exportReceiverCmd)
|
||||
}
|
||||
|
||||
func exportReceiverCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if !exportAll && len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportAll {
|
||||
var list notificationv1.ReceiverList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no receivers found in %s namespace", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, receiver := range list.Items {
|
||||
if err := exportReceiver(receiver); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
name := args[0]
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: 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 {
|
||||
gvk := notificationv1.GroupVersion.WithKind("Receiver")
|
||||
export := notificationv1.Receiver{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
Kind: gvk.Kind,
|
||||
APIVersion: gvk.GroupVersion().String(),
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: receiver.Name,
|
||||
Namespace: receiver.Namespace,
|
||||
Labels: receiver.Labels,
|
||||
Annotations: receiver.Annotations,
|
||||
},
|
||||
Spec: receiver.Spec,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(export)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
167
cmd/flux/export_source_bucket.go
Normal file
167
cmd/flux/export_source_bucket.go
Normal file
@@ -0,0 +1,167 @@
|
||||
/*
|
||||
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 (
|
||||
"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.",
|
||||
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,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportSourceCmd.AddCommand(exportSourceBucketCmd)
|
||||
}
|
||||
|
||||
func exportSourceBucketCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if !exportAll && len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportAll {
|
||||
var list sourcev1.BucketList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no source found in %s namespace", 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: 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 {
|
||||
gvk := sourcev1.GroupVersion.WithKind(sourcev1.BucketKind)
|
||||
export := sourcev1.Bucket{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
Kind: gvk.Kind,
|
||||
APIVersion: gvk.GroupVersion().String(),
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: source.Name,
|
||||
Namespace: source.Namespace,
|
||||
Labels: source.Labels,
|
||||
Annotations: source.Annotations,
|
||||
},
|
||||
Spec: source.Spec,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(export)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportBucketCredentials(ctx context.Context, kubeClient client.Client, source sourcev1.Bucket) error {
|
||||
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 nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -20,13 +20,15 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1alpha1"
|
||||
"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{
|
||||
@@ -34,10 +36,10 @@ var exportSourceGitCmd = &cobra.Command{
|
||||
Short: "Export GitRepository sources in YAML format",
|
||||
Long: "The export source git command exports on or all GitRepository sources in YAML format.",
|
||||
Example: ` # Export all GitRepository sources
|
||||
export source git --all > sources.yaml
|
||||
flux export source git --all > sources.yaml
|
||||
|
||||
# Export a GitRepository source including the SSH key pair or basic auth credentials
|
||||
export source git my-private-repo --with-credentials > source.yaml
|
||||
flux export source git my-private-repo --with-credentials > source.yaml
|
||||
`,
|
||||
RunE: exportSourceGitCmdRun,
|
||||
}
|
||||
@@ -48,13 +50,13 @@ func init() {
|
||||
|
||||
func exportSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if !exportAll && len(args) < 1 {
|
||||
return fmt.Errorf("kustomization name is required")
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.kubeClient(kubeconfig)
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -103,15 +105,17 @@ func exportSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
func exportGit(source sourcev1.GitRepository) error {
|
||||
gvk := sourcev1.GroupVersion.WithKind("GitRepository")
|
||||
gvk := sourcev1.GroupVersion.WithKind(sourcev1.GitRepositoryKind)
|
||||
export := sourcev1.GitRepository{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
Kind: gvk.Kind,
|
||||
APIVersion: gvk.GroupVersion().String(),
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: source.Name,
|
||||
Namespace: source.Namespace,
|
||||
Name: source.Name,
|
||||
Namespace: source.Namespace,
|
||||
Labels: source.Labels,
|
||||
Annotations: source.Annotations,
|
||||
},
|
||||
Spec: source.Spec,
|
||||
}
|
||||
@@ -122,7 +126,7 @@ func exportGit(source sourcev1.GitRepository) error {
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(string(data))
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -157,7 +161,7 @@ func exportGitCredentials(ctx context.Context, kubeClient client.Client, source
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(string(data))
|
||||
fmt.Println(resourceToString(data))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
167
cmd/flux/export_source_helm.go
Normal file
167
cmd/flux/export_source_helm.go
Normal file
@@ -0,0 +1,167 @@
|
||||
/*
|
||||
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 (
|
||||
"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.",
|
||||
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,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportSourceCmd.AddCommand(exportSourceHelmCmd)
|
||||
}
|
||||
|
||||
func exportSourceHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if !exportAll && len(args) < 1 {
|
||||
return fmt.Errorf("name is required")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if exportAll {
|
||||
var list sourcev1.HelmRepositoryList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no source found in %s namespace", 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: 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 {
|
||||
gvk := sourcev1.GroupVersion.WithKind(sourcev1.HelmRepositoryKind)
|
||||
export := sourcev1.HelmRepository{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
Kind: gvk.Kind,
|
||||
APIVersion: gvk.GroupVersion().String(),
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: source.Name,
|
||||
Namespace: source.Namespace,
|
||||
Labels: source.Labels,
|
||||
Annotations: source.Annotations,
|
||||
},
|
||||
Spec: source.Spec,
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(export)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("---")
|
||||
fmt.Println(resourceToString(data))
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportHelmCredentials(ctx context.Context, kubeClient client.Client, source sourcev1.HelmRepository) error {
|
||||
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 nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -26,6 +26,10 @@ var getCmd = &cobra.Command{
|
||||
Long: "The get sub-commands print the statuses of sources and resources.",
|
||||
}
|
||||
|
||||
var allNamespaces bool
|
||||
|
||||
func init() {
|
||||
getCmd.PersistentFlags().BoolVarP(&allNamespaces, "all-namespaces", "A", false,
|
||||
"list the requested object(s) across all namespaces")
|
||||
rootCmd.AddCommand(getCmd)
|
||||
}
|
||||
103
cmd/flux/get_alert.go
Normal file
103
cmd/flux/get_alert.go
Normal file
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"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.",
|
||||
Example: ` # List all Alerts and their status
|
||||
flux get alerts
|
||||
`,
|
||||
RunE: getAlertCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
getCmd.AddCommand(getAlertCmd)
|
||||
}
|
||||
|
||||
func getAlertCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var listOpts []client.ListOption
|
||||
if !allNamespaces {
|
||||
listOpts = append(listOpts, client.InNamespace(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", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Suspended", "Ready", "Message"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, alert := range list.Items {
|
||||
row := []string{}
|
||||
if c := meta.GetCondition(alert.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
alert.GetName(),
|
||||
//alert.Status.LastAppliedRevision,
|
||||
strings.Title(strconv.FormatBool(alert.Spec.Suspend)),
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
alert.GetName(),
|
||||
//alert.Status.LastAppliedRevision,
|
||||
strings.Title(strconv.FormatBool(alert.Spec.Suspend)),
|
||||
string(corev1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
}
|
||||
}
|
||||
if allNamespaces {
|
||||
row = append([]string{alert.Namespace}, row...)
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
utils.PrintTable(os.Stdout, header, rows)
|
||||
return nil
|
||||
}
|
||||
97
cmd/flux/get_alertprovider.go
Normal file
97
cmd/flux/get_alertprovider.go
Normal file
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"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.",
|
||||
Example: ` # List all Providers and their status
|
||||
flux get alert-providers
|
||||
`,
|
||||
RunE: getAlertProviderCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
getCmd.AddCommand(getAlertProviderCmd)
|
||||
}
|
||||
|
||||
func getAlertProviderCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var listOpts []client.ListOption
|
||||
if !allNamespaces {
|
||||
listOpts = append(listOpts, client.InNamespace(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", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Ready", "Message"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, provider := range list.Items {
|
||||
row := []string{}
|
||||
if c := meta.GetCondition(provider.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
provider.GetName(),
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
provider.GetName(),
|
||||
string(corev1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
}
|
||||
}
|
||||
if allNamespaces {
|
||||
row = append([]string{provider.Namespace}, row...)
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
utils.PrintTable(os.Stdout, header, rows)
|
||||
return nil
|
||||
}
|
||||
105
cmd/flux/get_helmrelease.go
Normal file
105
cmd/flux/get_helmrelease.go
Normal file
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
|
||||
)
|
||||
|
||||
var getHelmReleaseCmd = &cobra.Command{
|
||||
Use: "helmreleases",
|
||||
Aliases: []string{"hr"},
|
||||
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: getHelmReleaseCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
getCmd.AddCommand(getHelmReleaseCmd)
|
||||
}
|
||||
|
||||
func getHelmReleaseCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var listOpts []client.ListOption
|
||||
if !allNamespaces {
|
||||
listOpts = append(listOpts, client.InNamespace(namespace))
|
||||
}
|
||||
var list helmv2.HelmReleaseList
|
||||
err = kubeClient.List(ctx, &list, listOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no releases found in %s namespace", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Revision", "Suspended", "Ready", "Message"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, helmRelease := range list.Items {
|
||||
row := []string{}
|
||||
if c := meta.GetCondition(helmRelease.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
helmRelease.GetName(),
|
||||
helmRelease.Status.LastAppliedRevision,
|
||||
strings.Title(strconv.FormatBool(helmRelease.Spec.Suspend)),
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
helmRelease.GetName(),
|
||||
helmRelease.Status.LastAppliedRevision,
|
||||
strings.Title(strconv.FormatBool(helmRelease.Spec.Suspend)),
|
||||
string(corev1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
}
|
||||
}
|
||||
if allNamespaces {
|
||||
row = append([]string{helmRelease.Namespace}, row...)
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
utils.PrintTable(os.Stdout, header, rows)
|
||||
return nil
|
||||
}
|
||||
104
cmd/flux/get_kustomization.go
Normal file
104
cmd/flux/get_kustomization.go
Normal file
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
var getKsCmd = &cobra.Command{
|
||||
Use: "kustomizations",
|
||||
Aliases: []string{"ks"},
|
||||
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: getKsCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
getCmd.AddCommand(getKsCmd)
|
||||
}
|
||||
|
||||
func getKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var listOpts []client.ListOption
|
||||
if !allNamespaces {
|
||||
listOpts = append(listOpts, client.InNamespace(namespace))
|
||||
}
|
||||
var list kustomizev1.KustomizationList
|
||||
err = kubeClient.List(ctx, &list, listOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no kustomizations found in %s namespace", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Revision", "Suspended", "Ready", "Message"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, kustomization := range list.Items {
|
||||
row := []string{}
|
||||
if c := meta.GetCondition(kustomization.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
kustomization.GetName(),
|
||||
kustomization.Status.LastAppliedRevision,
|
||||
strings.Title(strconv.FormatBool(kustomization.Spec.Suspend)),
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
kustomization.GetName(),
|
||||
kustomization.Status.LastAppliedRevision,
|
||||
strings.Title(strconv.FormatBool(kustomization.Spec.Suspend)),
|
||||
string(corev1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
}
|
||||
}
|
||||
if allNamespaces {
|
||||
row = append([]string{kustomization.Namespace}, row...)
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
utils.PrintTable(os.Stdout, header, rows)
|
||||
return nil
|
||||
}
|
||||
98
cmd/flux/get_receiver.go
Normal file
98
cmd/flux/get_receiver.go
Normal file
@@ -0,0 +1,98 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"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.",
|
||||
Example: ` # List all Receiver and their status
|
||||
flux get receivers
|
||||
`,
|
||||
RunE: getReceiverCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
getCmd.AddCommand(getReceiverCmd)
|
||||
}
|
||||
|
||||
func getReceiverCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var listOpts []client.ListOption
|
||||
if !allNamespaces {
|
||||
listOpts = append(listOpts, client.InNamespace(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", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Suspended", "Ready", "Message"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, receiver := range list.Items {
|
||||
row := []string{}
|
||||
if c := meta.GetCondition(receiver.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
receiver.GetName(),
|
||||
strings.Title(strconv.FormatBool(receiver.Spec.Suspend)),
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
receiver.GetName(),
|
||||
strings.Title(strconv.FormatBool(receiver.Spec.Suspend)),
|
||||
string(corev1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
}
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
utils.PrintTable(os.Stdout, header, rows)
|
||||
return nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
103
cmd/flux/get_source_bucket.go
Normal file
103
cmd/flux/get_source_bucket.go
Normal file
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"os"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
var getSourceBucketCmd = &cobra.Command{
|
||||
Use: "bucket",
|
||||
Short: "Get Bucket source statuses",
|
||||
Long: "The get sources bucket command prints the status of the Bucket sources.",
|
||||
Example: ` # List all Buckets and their status
|
||||
flux get sources bucket
|
||||
`,
|
||||
RunE: getSourceBucketCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
getSourceCmd.AddCommand(getSourceBucketCmd)
|
||||
}
|
||||
|
||||
func getSourceBucketCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var listOpts []client.ListOption
|
||||
if !allNamespaces {
|
||||
listOpts = append(listOpts, client.InNamespace(namespace))
|
||||
}
|
||||
var list sourcev1.BucketList
|
||||
err = kubeClient.List(ctx, &list, listOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no bucket sources found in %s namespace", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Revision", "Ready", "Message"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, source := range list.Items {
|
||||
var row []string
|
||||
var revision string
|
||||
if source.GetArtifact() != nil {
|
||||
revision = source.GetArtifact().Revision
|
||||
}
|
||||
if c := meta.GetCondition(source.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
source.GetName(),
|
||||
revision,
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
source.GetName(),
|
||||
revision,
|
||||
string(corev1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
}
|
||||
}
|
||||
if allNamespaces {
|
||||
row = append([]string{source.Namespace}, row...)
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
utils.PrintTable(os.Stdout, header, rows)
|
||||
return nil
|
||||
}
|
||||
103
cmd/flux/get_source_git.go
Normal file
103
cmd/flux/get_source_git.go
Normal file
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"os"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
var getSourceGitCmd = &cobra.Command{
|
||||
Use: "git",
|
||||
Short: "Get GitRepository source statuses",
|
||||
Long: "The get sources git command prints the status of the GitRepository sources.",
|
||||
Example: ` # List all Git repositories and their status
|
||||
flux get sources git
|
||||
`,
|
||||
RunE: getSourceGitCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
getSourceCmd.AddCommand(getSourceGitCmd)
|
||||
}
|
||||
|
||||
func getSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var listOpts []client.ListOption
|
||||
if !allNamespaces {
|
||||
listOpts = append(listOpts, client.InNamespace(namespace))
|
||||
}
|
||||
var list sourcev1.GitRepositoryList
|
||||
err = kubeClient.List(ctx, &list, listOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no git sources found in %s namespace", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Revision", "Ready", "Message"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, source := range list.Items {
|
||||
var row []string
|
||||
var revision string
|
||||
if source.GetArtifact() != nil {
|
||||
revision = source.GetArtifact().Revision
|
||||
}
|
||||
if c := meta.GetCondition(source.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
source.GetName(),
|
||||
revision,
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
source.GetName(),
|
||||
revision,
|
||||
string(corev1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
}
|
||||
}
|
||||
if allNamespaces {
|
||||
row = append([]string{source.Namespace}, row...)
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
utils.PrintTable(os.Stdout, header, rows)
|
||||
return nil
|
||||
}
|
||||
103
cmd/flux/get_source_helm.go
Normal file
103
cmd/flux/get_source_helm.go
Normal file
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"os"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
var getSourceHelmCmd = &cobra.Command{
|
||||
Use: "helm",
|
||||
Short: "Get HelmRepository source statuses",
|
||||
Long: "The get sources helm command prints the status of the HelmRepository sources.",
|
||||
Example: ` # List all Helm repositories and their status
|
||||
flux get sources helm
|
||||
`,
|
||||
RunE: getSourceHelmCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
getSourceCmd.AddCommand(getSourceHelmCmd)
|
||||
}
|
||||
|
||||
func getSourceHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var listOpts []client.ListOption
|
||||
if !allNamespaces {
|
||||
listOpts = append(listOpts, client.InNamespace(namespace))
|
||||
}
|
||||
var list sourcev1.HelmRepositoryList
|
||||
err = kubeClient.List(ctx, &list, listOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no helm sources found in %s namespace", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
header := []string{"Name", "Revision", "Ready", "Message"}
|
||||
if allNamespaces {
|
||||
header = append([]string{"Namespace"}, header...)
|
||||
}
|
||||
var rows [][]string
|
||||
for _, source := range list.Items {
|
||||
var row []string
|
||||
var revision string
|
||||
if source.GetArtifact() != nil {
|
||||
revision = source.GetArtifact().Revision
|
||||
}
|
||||
if c := meta.GetCondition(source.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
row = []string{
|
||||
source.GetName(),
|
||||
revision,
|
||||
string(c.Status),
|
||||
c.Message,
|
||||
}
|
||||
} else {
|
||||
row = []string{
|
||||
source.GetName(),
|
||||
revision,
|
||||
string(corev1.ConditionFalse),
|
||||
"waiting to be reconciled",
|
||||
}
|
||||
}
|
||||
if allNamespaces {
|
||||
row = append([]string{source.Namespace}, row...)
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
utils.PrintTable(os.Stdout, header, rows)
|
||||
return nil
|
||||
}
|
||||
181
cmd/flux/install.go
Normal file
181
cmd/flux/install.go
Normal file
@@ -0,0 +1,181 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/flags"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/install"
|
||||
)
|
||||
|
||||
var installCmd = &cobra.Command{
|
||||
Use: "install",
|
||||
Short: "Install the toolkit components",
|
||||
Long: `The install command deploys the toolkit components in the specified namespace.
|
||||
If a previous version is installed, then an in-place upgrade will be performed.`,
|
||||
Example: ` # Install the latest version in the flux-system namespace
|
||||
flux install --version=latest --namespace=flux-system
|
||||
|
||||
# Dry-run install for a specific version and a series of components
|
||||
flux install --dry-run --version=v0.0.7 --components="source-controller,kustomize-controller"
|
||||
|
||||
# Dry-run install with manifests preview
|
||||
flux install --dry-run --verbose
|
||||
|
||||
# Write install manifests to file
|
||||
flux install --export > flux-system.yaml
|
||||
`,
|
||||
RunE: installCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
installExport bool
|
||||
installDryRun bool
|
||||
installManifestsPath string
|
||||
installVersion string
|
||||
installComponents []string
|
||||
installRegistry string
|
||||
installImagePullSecret string
|
||||
installWatchAllNamespaces bool
|
||||
installNetworkPolicy bool
|
||||
installArch = flags.Arch(defaults.Arch)
|
||||
installLogLevel = flags.LogLevel(defaults.LogLevel)
|
||||
)
|
||||
|
||||
func init() {
|
||||
installCmd.Flags().BoolVar(&installExport, "export", false,
|
||||
"write the install manifests to stdout and exit")
|
||||
installCmd.Flags().BoolVarP(&installDryRun, "dry-run", "", false,
|
||||
"only print the object that would be applied")
|
||||
installCmd.Flags().StringVarP(&installVersion, "version", "v", defaults.Version,
|
||||
"toolkit version")
|
||||
installCmd.Flags().StringSliceVar(&installComponents, "components", defaults.Components,
|
||||
"list of components, accepts comma-separated values")
|
||||
installCmd.Flags().StringVar(&installManifestsPath, "manifests", "", "path to the manifest directory")
|
||||
installCmd.Flags().MarkHidden("manifests")
|
||||
installCmd.Flags().StringVar(&installRegistry, "registry", defaults.Registry,
|
||||
"container registry where the toolkit images are published")
|
||||
installCmd.Flags().StringVar(&installImagePullSecret, "image-pull-secret", "",
|
||||
"Kubernetes secret name used for pulling the toolkit images from a private registry")
|
||||
installCmd.Flags().Var(&installArch, "arch", installArch.Description())
|
||||
installCmd.Flags().BoolVar(&installWatchAllNamespaces, "watch-all-namespaces", defaults.WatchAllNamespaces,
|
||||
"watch for custom resources in all namespaces, if set to false it will only watch the namespace where the toolkit is installed")
|
||||
installCmd.Flags().Var(&installLogLevel, "log-level", installLogLevel.Description())
|
||||
installCmd.Flags().BoolVar(&installNetworkPolicy, "network-policy", defaults.NetworkPolicy,
|
||||
"deny ingress access to the toolkit controllers from other namespaces using network policies")
|
||||
rootCmd.AddCommand(installCmd)
|
||||
}
|
||||
|
||||
func installCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
tmpDir, err := ioutil.TempDir("", namespace)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
if !installExport {
|
||||
logger.Generatef("generating manifests")
|
||||
}
|
||||
|
||||
opts := install.Options{
|
||||
BaseURL: installManifestsPath,
|
||||
Version: installVersion,
|
||||
Namespace: namespace,
|
||||
Components: installComponents,
|
||||
Registry: installRegistry,
|
||||
ImagePullSecret: installImagePullSecret,
|
||||
Arch: installArch.String(),
|
||||
WatchAllNamespaces: installWatchAllNamespaces,
|
||||
NetworkPolicy: installNetworkPolicy,
|
||||
LogLevel: installLogLevel.String(),
|
||||
NotificationController: defaults.NotificationController,
|
||||
ManifestFile: fmt.Sprintf("%s.yaml", namespace),
|
||||
Timeout: timeout,
|
||||
}
|
||||
|
||||
if installManifestsPath == "" {
|
||||
opts.BaseURL = install.MakeDefaultOptions().BaseURL
|
||||
}
|
||||
|
||||
manifest, err := install.Generate(opts)
|
||||
if err != nil {
|
||||
return fmt.Errorf("install failed: %w", err)
|
||||
}
|
||||
|
||||
if _, err := manifest.WriteFile(tmpDir); err != nil {
|
||||
return fmt.Errorf("install failed: %w", err)
|
||||
}
|
||||
|
||||
if verbose {
|
||||
fmt.Print(manifest.Content)
|
||||
} else if installExport {
|
||||
fmt.Println("---")
|
||||
fmt.Println("# GitOps Toolkit revision", installVersion)
|
||||
fmt.Println("# Components:", strings.Join(installComponents, ","))
|
||||
fmt.Print(manifest.Content)
|
||||
fmt.Println("---")
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.Successf("manifests build completed")
|
||||
logger.Actionf("installing components in %s namespace", namespace)
|
||||
applyOutput := utils.ModeStderrOS
|
||||
if verbose {
|
||||
applyOutput = utils.ModeOS
|
||||
}
|
||||
|
||||
kubectlArgs := []string{"apply", "-f", filepath.Join(tmpDir, manifest.Path)}
|
||||
if installDryRun {
|
||||
args = append(args, "--dry-run=client")
|
||||
applyOutput = utils.ModeOS
|
||||
}
|
||||
if _, err := utils.ExecKubectlCommand(ctx, applyOutput, kubectlArgs...); err != nil {
|
||||
return fmt.Errorf("install failed")
|
||||
}
|
||||
|
||||
if installDryRun {
|
||||
logger.Successf("install dry-run finished")
|
||||
return nil
|
||||
} else {
|
||||
logger.Successf("install completed")
|
||||
}
|
||||
|
||||
logger.Waitingf("verifying installation")
|
||||
for _, deployment := range installComponents {
|
||||
kubectlArgs = []string{"-n", namespace, "rollout", "status", "deployment", deployment, "--timeout", timeout.String()}
|
||||
if _, err := utils.ExecKubectlCommand(ctx, applyOutput, kubectlArgs...); err != nil {
|
||||
return fmt.Errorf("install failed")
|
||||
} else {
|
||||
logger.Successf("%s ready", deployment)
|
||||
}
|
||||
}
|
||||
|
||||
logger.Successf("install finished")
|
||||
return nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -26,94 +26,90 @@ import (
|
||||
"github.com/spf13/cobra/doc"
|
||||
_ "k8s.io/client-go/plugin/pkg/client/auth"
|
||||
|
||||
tklog "github.com/fluxcd/toolkit/pkg/log"
|
||||
fluxlog "github.com/fluxcd/flux2/pkg/log"
|
||||
"github.com/fluxcd/flux2/pkg/manifestgen/install"
|
||||
)
|
||||
|
||||
var VERSION = "0.0.0-dev.0"
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "tk",
|
||||
Use: "flux",
|
||||
Version: VERSION,
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
Short: "Command line utility for assembling Kubernetes CD pipelines",
|
||||
Long: `Command line utility for assembling Kubernetes CD pipelines the GitOps way.`,
|
||||
Example: ` # Check prerequisites
|
||||
tk check --pre
|
||||
Example: ` # Check prerequisites
|
||||
flux check --pre
|
||||
|
||||
# Install the latest version of the toolkit
|
||||
tk install --version=master
|
||||
flux install --version=master
|
||||
|
||||
# Create a source from a public Git repository
|
||||
tk create source git webapp-latest \
|
||||
flux create source git webapp-latest \
|
||||
--url=https://github.com/stefanprodan/podinfo \
|
||||
--branch=master \
|
||||
--interval=3m
|
||||
|
||||
# List GitRepository sources and their status
|
||||
tk get sources git
|
||||
flux get sources git
|
||||
|
||||
# Trigger a GitRepository source sync
|
||||
tk sync source git webapp-latest
|
||||
# Trigger a GitRepository source reconciliation
|
||||
flux reconcile source git flux-system
|
||||
|
||||
# Export GitRepository sources in YAML format
|
||||
tk export source git --all > sources.yaml
|
||||
flux export source git --all > sources.yaml
|
||||
|
||||
# Create a Kustomization for deploying a series of microservices
|
||||
tk create kustomization webapp-dev \
|
||||
flux create kustomization webapp-dev \
|
||||
--source=webapp-latest \
|
||||
--path="./deploy/webapp/" \
|
||||
--prune=true \
|
||||
--interval=5m \
|
||||
--validate=client \
|
||||
--validation=client \
|
||||
--health-check="Deployment/backend.webapp" \
|
||||
--health-check="Deployment/frontend.webapp" \
|
||||
--health-check-timeout=2m
|
||||
|
||||
# Trigger a git sync of the Kustomization's source and apply changes
|
||||
tk sync kustomization webapp-dev --with-source
|
||||
flux reconcile kustomization webapp-dev --with-source
|
||||
|
||||
# Suspend a Kustomization reconciliation
|
||||
tk suspend kustomization webapp-dev
|
||||
flux suspend kustomization webapp-dev
|
||||
|
||||
# Export Kustomizations in YAML format
|
||||
tk export kustomization --all > kustomizations.yaml
|
||||
flux export kustomization --all > kustomizations.yaml
|
||||
|
||||
# Resume a Kustomization reconciliation
|
||||
tk resume kustomization webapp-dev
|
||||
flux resume kustomization webapp-dev
|
||||
|
||||
# Delete a Kustomization
|
||||
tk delete kustomization webapp-dev
|
||||
flux delete kustomization webapp-dev
|
||||
|
||||
# Delete a GitRepository source
|
||||
tk delete source git webapp-latest
|
||||
flux delete source git webapp-latest
|
||||
|
||||
# Uninstall the toolkit and delete CRDs
|
||||
tk uninstall --crds
|
||||
flux uninstall --crds
|
||||
`,
|
||||
}
|
||||
|
||||
var (
|
||||
kubeconfig string
|
||||
kubecontext string
|
||||
namespace string
|
||||
timeout time.Duration
|
||||
verbose bool
|
||||
components []string
|
||||
utils Utils
|
||||
pollInterval = 2 * time.Second
|
||||
logger tklog.Logger = printLogger{}
|
||||
pollInterval = 2 * time.Second
|
||||
logger fluxlog.Logger = printLogger{}
|
||||
defaults = install.MakeDefaultOptions()
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.PersistentFlags().StringVarP(&namespace, "namespace", "", "gitops-system",
|
||||
"the namespace scope for this operation")
|
||||
rootCmd.PersistentFlags().DurationVarP(&timeout, "timeout", "", 5*time.Minute,
|
||||
"timeout for this operation")
|
||||
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "", false,
|
||||
"print generated objects")
|
||||
rootCmd.PersistentFlags().StringSliceVar(&components, "components",
|
||||
[]string{"source-controller", "kustomize-controller", "notification-controller"},
|
||||
"list of components, accepts comma-separated values")
|
||||
rootCmd.PersistentFlags().StringVarP(&namespace, "namespace", "n", defaults.Namespace, "the namespace scope for this operation")
|
||||
rootCmd.PersistentFlags().DurationVar(&timeout, "timeout", 5*time.Minute, "timeout for this operation")
|
||||
rootCmd.PersistentFlags().BoolVar(&verbose, "verbose", false, "print generated objects")
|
||||
rootCmd.PersistentFlags().StringVarP(&kubecontext, "context", "", "", "kubernetes context to use")
|
||||
}
|
||||
|
||||
func main() {
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -20,12 +20,12 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var syncCmd = &cobra.Command{
|
||||
Use: "sync",
|
||||
Short: "Synchronize sources and resources",
|
||||
Long: "The sync sub-commands trigger a reconciliation of sources and resources.",
|
||||
var reconcileCmd = &cobra.Command{
|
||||
Use: "reconcile",
|
||||
Short: "Reconcile sources and resources",
|
||||
Long: "The reconcile sub-commands trigger a reconciliation of sources and resources.",
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(syncCmd)
|
||||
rootCmd.AddCommand(reconcileCmd)
|
||||
}
|
||||
93
cmd/flux/reconcile_alert.go
Normal file
93
cmd/flux/reconcile_alert.go
Normal file
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var reconcileAlertCmd = &cobra.Command{
|
||||
Use: "alert [name]",
|
||||
Short: "Reconcile an Alert",
|
||||
Long: `The reconcile alert command triggers a reconciliation of an Alert resource and waits for it to finish.`,
|
||||
Example: ` # Trigger a reconciliation for an existing alert
|
||||
flux reconcile alert main
|
||||
`,
|
||||
RunE: reconcileAlertCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
reconcileCmd.AddCommand(reconcileAlertCmd)
|
||||
}
|
||||
|
||||
func reconcileAlertCmdRun(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(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
logger.Actionf("annotating Alert %s in %s namespace", name, namespace)
|
||||
var alert notificationv1.Alert
|
||||
err = kubeClient.Get(ctx, namespacedName, &alert)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if alert.Annotations == nil {
|
||||
alert.Annotations = map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
}
|
||||
} else {
|
||||
alert.Annotations[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
}
|
||||
if err := kubeClient.Update(ctx, &alert); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Alert annotated")
|
||||
|
||||
logger.Waitingf("waiting for reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isAlertReady(ctx, kubeClient, namespacedName, &alert)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Alert reconciliation completed")
|
||||
return nil
|
||||
}
|
||||
93
cmd/flux/reconcile_alertprovider.go
Normal file
93
cmd/flux/reconcile_alertprovider.go
Normal file
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var reconcileAlertProviderCmd = &cobra.Command{
|
||||
Use: "alert-provider [name]",
|
||||
Short: "Reconcile a Provider",
|
||||
Long: `The reconcile alert-provider command triggers a reconciliation of a Provider resource and waits for it to finish.`,
|
||||
Example: ` # Trigger a reconciliation for an existing provider
|
||||
flux reconcile alert-provider slack
|
||||
`,
|
||||
RunE: reconcileAlertProviderCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
reconcileCmd.AddCommand(reconcileAlertProviderCmd)
|
||||
}
|
||||
|
||||
func reconcileAlertProviderCmdRun(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(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
logger.Actionf("annotating Provider %s in %s namespace", name, namespace)
|
||||
var alertProvider notificationv1.Provider
|
||||
err = kubeClient.Get(ctx, namespacedName, &alertProvider)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if alertProvider.Annotations == nil {
|
||||
alertProvider.Annotations = map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
}
|
||||
} else {
|
||||
alertProvider.Annotations[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
}
|
||||
if err := kubeClient.Update(ctx, &alertProvider); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Provider annotated")
|
||||
|
||||
logger.Waitingf("waiting for reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isAlertProviderReady(ctx, kubeClient, namespacedName, &alertProvider)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Provider reconciliation completed")
|
||||
return nil
|
||||
}
|
||||
158
cmd/flux/reconcile_helmrelease.go
Normal file
158
cmd/flux/reconcile_helmrelease.go
Normal file
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"k8s.io/client-go/util/retry"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var reconcileHrCmd = &cobra.Command{
|
||||
Use: "helmrelease [name]",
|
||||
Aliases: []string{"hr"},
|
||||
Short: "Reconcile a HelmRelease resource",
|
||||
Long: `
|
||||
The reconcile kustomization command triggers a reconciliation of a HelmRelease resource and waits for it to finish.`,
|
||||
Example: ` # Trigger a HelmRelease apply outside of the reconciliation interval
|
||||
flux reconcile hr podinfo
|
||||
|
||||
# Trigger a reconciliation of the HelmRelease's source and apply changes
|
||||
flux reconcile hr podinfo --with-source
|
||||
`,
|
||||
RunE: reconcileHrCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
syncHrWithSource bool
|
||||
)
|
||||
|
||||
func init() {
|
||||
reconcileHrCmd.Flags().BoolVar(&syncHrWithSource, "with-source", false, "reconcile HelmRelease source")
|
||||
|
||||
reconcileCmd.AddCommand(reconcileHrCmd)
|
||||
}
|
||||
|
||||
func reconcileHrCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("HelmRelease name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
var helmRelease helmv2.HelmRelease
|
||||
err = kubeClient.Get(ctx, namespacedName, &helmRelease)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if syncHrWithSource {
|
||||
switch helmRelease.Spec.Chart.Spec.SourceRef.Kind {
|
||||
case sourcev1.HelmRepositoryKind:
|
||||
err = reconcileSourceHelmCmdRun(nil, []string{helmRelease.Spec.Chart.Spec.SourceRef.Name})
|
||||
case sourcev1.GitRepositoryKind:
|
||||
err = reconcileSourceGitCmdRun(nil, []string{helmRelease.Spec.Chart.Spec.SourceRef.Name})
|
||||
case sourcev1.BucketKind:
|
||||
err = reconcileSourceBucketCmdRun(nil, []string{helmRelease.Spec.Chart.Spec.SourceRef.Name})
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
lastHandledReconcileAt := helmRelease.Status.LastHandledReconcileAt
|
||||
logger.Actionf("annotating HelmRelease %s in %s namespace", name, namespace)
|
||||
if err := requestHelmReleaseReconciliation(ctx, kubeClient, namespacedName, &helmRelease); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("HelmRelease annotated")
|
||||
|
||||
logger.Waitingf("waiting for HelmRelease reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
helmReleaseReconciliationHandled(ctx, kubeClient, namespacedName, &helmRelease, lastHandledReconcileAt),
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("HelmRelease reconciliation completed")
|
||||
|
||||
err = kubeClient.Get(ctx, namespacedName, &helmRelease)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c := meta.GetCondition(helmRelease.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionFalse:
|
||||
return fmt.Errorf("HelmRelease reconciliation failed: %s", c.Message)
|
||||
default:
|
||||
logger.Successf("reconciled revision %s", helmRelease.Status.LastAppliedRevision)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func helmReleaseReconciliationHandled(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, helmRelease *helmv2.HelmRelease, lastHandledReconcileAt string) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, helmRelease)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return helmRelease.Status.LastHandledReconcileAt != lastHandledReconcileAt, nil
|
||||
}
|
||||
}
|
||||
|
||||
func requestHelmReleaseReconciliation(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, helmRelease *helmv2.HelmRelease) error {
|
||||
return retry.RetryOnConflict(retry.DefaultBackoff, func() (err error) {
|
||||
if err := kubeClient.Get(ctx, namespacedName, helmRelease); err != nil {
|
||||
return err
|
||||
}
|
||||
if helmRelease.Annotations == nil {
|
||||
helmRelease.Annotations = map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
}
|
||||
} else {
|
||||
helmRelease.Annotations[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
}
|
||||
return kubeClient.Update(ctx, helmRelease)
|
||||
})
|
||||
}
|
||||
152
cmd/flux/reconcile_kustomization.go
Normal file
152
cmd/flux/reconcile_kustomization.go
Normal file
@@ -0,0 +1,152 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/client-go/util/retry"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var reconcileKsCmd = &cobra.Command{
|
||||
Use: "kustomization [name]",
|
||||
Aliases: []string{"ks"},
|
||||
Short: "Reconcile a Kustomization resource",
|
||||
Long: `
|
||||
The reconcile kustomization command triggers a reconciliation of a Kustomization resource and waits for it to finish.`,
|
||||
Example: ` # Trigger a Kustomization apply outside of the reconciliation interval
|
||||
flux reconcile kustomization podinfo
|
||||
|
||||
# Trigger a sync of the Kustomization's source and apply changes
|
||||
flux reconcile kustomization podinfo --with-source
|
||||
`,
|
||||
RunE: reconcileKsCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
syncKsWithSource bool
|
||||
)
|
||||
|
||||
func init() {
|
||||
reconcileKsCmd.Flags().BoolVar(&syncKsWithSource, "with-source", false, "reconcile Kustomization source")
|
||||
|
||||
reconcileCmd.AddCommand(reconcileKsCmd)
|
||||
}
|
||||
|
||||
func reconcileKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("Kustomization name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
var kustomization kustomizev1.Kustomization
|
||||
err = kubeClient.Get(ctx, namespacedName, &kustomization)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if syncKsWithSource {
|
||||
switch kustomization.Spec.SourceRef.Kind {
|
||||
case sourcev1.GitRepositoryKind:
|
||||
err = reconcileSourceGitCmdRun(nil, []string{kustomization.Spec.SourceRef.Name})
|
||||
case sourcev1.BucketKind:
|
||||
err = reconcileSourceBucketCmdRun(nil, []string{kustomization.Spec.SourceRef.Name})
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
lastHandledReconcileAt := kustomization.Status.LastHandledReconcileAt
|
||||
logger.Actionf("annotating Kustomization %s in %s namespace", name, namespace)
|
||||
if err := requestKustomizeReconciliation(ctx, kubeClient, namespacedName, &kustomization); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Kustomization annotated")
|
||||
|
||||
logger.Waitingf("waiting for Kustomization reconciliation")
|
||||
if err := wait.PollImmediate(
|
||||
pollInterval, timeout,
|
||||
kustomizeReconciliationHandled(ctx, kubeClient, namespacedName, &kustomization, lastHandledReconcileAt),
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Kustomization reconciliation completed")
|
||||
|
||||
if c := meta.GetCondition(kustomization.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionFalse:
|
||||
return fmt.Errorf("Kustomization reconciliation failed")
|
||||
default:
|
||||
logger.Successf("reconciled revision %s", kustomization.Status.LastAppliedRevision)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func kustomizeReconciliationHandled(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, kustomization *kustomizev1.Kustomization, lastHandledReconcileAt string) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, kustomization)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return kustomization.Status.LastHandledReconcileAt != lastHandledReconcileAt, nil
|
||||
}
|
||||
}
|
||||
|
||||
func requestKustomizeReconciliation(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, kustomization *kustomizev1.Kustomization) error {
|
||||
return retry.RetryOnConflict(retry.DefaultBackoff, func() (err error) {
|
||||
if err := kubeClient.Get(ctx, namespacedName, kustomization); err != nil {
|
||||
return err
|
||||
}
|
||||
if kustomization.Annotations == nil {
|
||||
kustomization.Annotations = map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
}
|
||||
} else {
|
||||
kustomization.Annotations[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
}
|
||||
return kubeClient.Update(ctx, kustomization)
|
||||
})
|
||||
}
|
||||
95
cmd/flux/reconcile_receiver.go
Normal file
95
cmd/flux/reconcile_receiver.go
Normal file
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var reconcileReceiverCmd = &cobra.Command{
|
||||
Use: "receiver [name]",
|
||||
Short: "Reconcile a Receiver",
|
||||
Long: `The reconcile receiver command triggers a reconciliation of a Receiver resource and waits for it to finish.`,
|
||||
Example: ` # Trigger a reconciliation for an existing receiver
|
||||
flux reconcile receiver main
|
||||
`,
|
||||
RunE: reconcileReceiverCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
reconcileCmd.AddCommand(reconcileReceiverCmd)
|
||||
}
|
||||
|
||||
func reconcileReceiverCmdRun(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(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
logger.Actionf("annotating Receiver %s in %s namespace", name, namespace)
|
||||
var receiver notificationv1.Receiver
|
||||
err = kubeClient.Get(ctx, namespacedName, &receiver)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if receiver.Annotations == nil {
|
||||
receiver.Annotations = map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
}
|
||||
} else {
|
||||
receiver.Annotations[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
}
|
||||
if err := kubeClient.Update(ctx, &receiver); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Receiver annotated")
|
||||
|
||||
logger.Waitingf("waiting for Receiver reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isReceiverReady(ctx, kubeClient, namespacedName, &receiver)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Successf("Receiver reconciliation completed")
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -20,12 +20,12 @@ import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var syncSourceCmd = &cobra.Command{
|
||||
var reconcileSourceCmd = &cobra.Command{
|
||||
Use: "source",
|
||||
Short: "Synchronize sources",
|
||||
Long: "The sync source sub-commands trigger a reconciliation of sources.",
|
||||
Short: "Reconcile sources",
|
||||
Long: "The reconcile source sub-commands trigger a reconciliation of sources.",
|
||||
}
|
||||
|
||||
func init() {
|
||||
syncCmd.AddCommand(syncSourceCmd)
|
||||
reconcileCmd.AddCommand(reconcileSourceCmd)
|
||||
}
|
||||
125
cmd/flux/reconcile_source_bucket.go
Normal file
125
cmd/flux/reconcile_source_bucket.go
Normal file
@@ -0,0 +1,125 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var reconcileSourceBucketCmd = &cobra.Command{
|
||||
Use: "bucket [name]",
|
||||
Short: "Reconcile a Bucket source",
|
||||
Long: `The reconcile source command triggers a reconciliation of a Bucket resource and waits for it to finish.`,
|
||||
Example: ` # Trigger a reconciliation for an existing source
|
||||
flux reconcile source bucket podinfo
|
||||
`,
|
||||
RunE: reconcileSourceBucketCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
reconcileSourceCmd.AddCommand(reconcileSourceBucketCmd)
|
||||
}
|
||||
|
||||
func reconcileSourceBucketCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("source name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
logger.Actionf("annotating Bucket source %s in %s namespace", name, namespace)
|
||||
var bucket sourcev1.Bucket
|
||||
err = kubeClient.Get(ctx, namespacedName, &bucket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if bucket.Annotations == nil {
|
||||
bucket.Annotations = map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
}
|
||||
} else {
|
||||
bucket.Annotations[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
}
|
||||
if err := kubeClient.Update(ctx, &bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Bucket source annotated")
|
||||
|
||||
logger.Waitingf("waiting for Bucket source reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isBucketReady(ctx, kubeClient, namespacedName, &bucket)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Bucket source reconciliation completed")
|
||||
|
||||
if bucket.Status.Artifact == nil {
|
||||
return fmt.Errorf("Bucket source reconciliation completed but no artifact was found")
|
||||
}
|
||||
logger.Successf("fetched revision %s", bucket.Status.Artifact.Revision)
|
||||
return nil
|
||||
}
|
||||
|
||||
func isBucketReady(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, bucket *sourcev1.Bucket) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, bucket)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Confirm the state we are observing is for the current generation
|
||||
if bucket.Generation != bucket.Status.ObservedGeneration {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(bucket.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -19,28 +19,33 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1alpha1"
|
||||
"time"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"time"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var syncSourceGitCmd = &cobra.Command{
|
||||
var reconcileSourceGitCmd = &cobra.Command{
|
||||
Use: "git [name]",
|
||||
Short: "Synchronize a GitRepository source",
|
||||
Long: `The sync source command triggers a reconciliation of a GitRepository resource and waits for it to finish.`,
|
||||
Short: "Reconcile a GitRepository source",
|
||||
Long: `The reconcile source command triggers a reconciliation of a GitRepository resource and waits for it to finish.`,
|
||||
Example: ` # Trigger a git pull for an existing source
|
||||
sync source git podinfo
|
||||
flux reconcile source git podinfo
|
||||
`,
|
||||
RunE: syncSourceGitCmdRun,
|
||||
RunE: reconcileSourceGitCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
syncSourceCmd.AddCommand(syncSourceGitCmd)
|
||||
reconcileSourceCmd.AddCommand(reconcileSourceGitCmd)
|
||||
}
|
||||
|
||||
func syncSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
func reconcileSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("source name is required")
|
||||
}
|
||||
@@ -49,7 +54,7 @@ func syncSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.kubeClient(kubeconfig)
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -59,7 +64,7 @@ func syncSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
Name: name,
|
||||
}
|
||||
|
||||
logger.Actionf("annotating source %s in %s namespace", name, namespace)
|
||||
logger.Actionf("annotating GitRepository source %s in %s namespace", name, namespace)
|
||||
var gitRepository sourcev1.GitRepository
|
||||
err = kubeClient.Get(ctx, namespacedName, &gitRepository)
|
||||
if err != nil {
|
||||
@@ -68,33 +73,26 @@ func syncSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
|
||||
if gitRepository.Annotations == nil {
|
||||
gitRepository.Annotations = map[string]string{
|
||||
sourcev1.SyncAtAnnotation: time.Now().String(),
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
}
|
||||
} else {
|
||||
gitRepository.Annotations[sourcev1.SyncAtAnnotation] = time.Now().String()
|
||||
gitRepository.Annotations[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
}
|
||||
if err := kubeClient.Update(ctx, &gitRepository); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("source annotated")
|
||||
logger.Successf("GitRepository source annotated")
|
||||
|
||||
logger.Waitingf("waiting for git sync")
|
||||
logger.Waitingf("waiting for GitRepository source reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isGitRepositoryReady(ctx, kubeClient, name, namespace)); err != nil {
|
||||
isGitRepositoryReady(ctx, kubeClient, namespacedName, &gitRepository)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("GitRepository source reconciliation completed")
|
||||
|
||||
logger.Successf("git sync completed")
|
||||
|
||||
err = kubeClient.Get(ctx, namespacedName, &gitRepository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if gitRepository.Status.Artifact != nil {
|
||||
logger.Successf("fetched revision %s", gitRepository.Status.Artifact.Revision)
|
||||
} else {
|
||||
return fmt.Errorf("git sync failed, artifact not found")
|
||||
if gitRepository.Status.Artifact == nil {
|
||||
return fmt.Errorf("GitRepository source reconciliation completed but no artifact was found")
|
||||
}
|
||||
logger.Successf("fetched revision %s", gitRepository.Status.Artifact.Revision)
|
||||
return nil
|
||||
}
|
||||
125
cmd/flux/reconcile_source_helm.go
Normal file
125
cmd/flux/reconcile_source_helm.go
Normal file
@@ -0,0 +1,125 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var reconcileSourceHelmCmd = &cobra.Command{
|
||||
Use: "helm [name]",
|
||||
Short: "Reconcile a HelmRepository source",
|
||||
Long: `The reconcile source command triggers a reconciliation of a HelmRepository resource and waits for it to finish.`,
|
||||
Example: ` # Trigger a reconciliation for an existing source
|
||||
flux reconcile source helm podinfo
|
||||
`,
|
||||
RunE: reconcileSourceHelmCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
reconcileSourceCmd.AddCommand(reconcileSourceHelmCmd)
|
||||
}
|
||||
|
||||
func reconcileSourceHelmCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("HelmRepository source name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
logger.Actionf("annotating HelmRepository source %s in %s namespace", name, namespace)
|
||||
var helmRepository sourcev1.HelmRepository
|
||||
err = kubeClient.Get(ctx, namespacedName, &helmRepository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if helmRepository.Annotations == nil {
|
||||
helmRepository.Annotations = map[string]string{
|
||||
meta.ReconcileAtAnnotation: time.Now().Format(time.RFC3339Nano),
|
||||
}
|
||||
} else {
|
||||
helmRepository.Annotations[meta.ReconcileAtAnnotation] = time.Now().Format(time.RFC3339Nano)
|
||||
}
|
||||
if err := kubeClient.Update(ctx, &helmRepository); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("HelmRepository source annotated")
|
||||
|
||||
logger.Waitingf("waiting for HelmRepository source reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isHelmRepositoryReady(ctx, kubeClient, namespacedName, &helmRepository)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("HelmRepository source reconciliation completed")
|
||||
|
||||
if helmRepository.Status.Artifact == nil {
|
||||
return fmt.Errorf("HelmRepository source reconciliation completed but no artifact was found")
|
||||
}
|
||||
logger.Successf("fetched revision %s", helmRepository.Status.Artifact.Revision)
|
||||
return nil
|
||||
}
|
||||
|
||||
func isHelmRepositoryReady(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, helmRepository *sourcev1.HelmRepository) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, helmRepository)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Confirm the state we are observing is for the current generation
|
||||
if helmRepository.Generation != helmRepository.Status.ObservedGeneration {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(helmRepository.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
111
cmd/flux/resume_alert.go
Normal file
111
cmd/flux/resume_alert.go
Normal file
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var resumeAlertCmd = &cobra.Command{
|
||||
Use: "alert [name]",
|
||||
Short: "Resume a suspended Alert",
|
||||
Long: `The resume command marks a previously suspended Alert resource for reconciliation and waits for it to
|
||||
finish the apply.`,
|
||||
Example: ` # Resume reconciliation for an existing Alert
|
||||
flux resume alert main
|
||||
`,
|
||||
RunE: resumeAlertCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
resumeCmd.AddCommand(resumeAlertCmd)
|
||||
}
|
||||
|
||||
func resumeAlertCmdRun(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(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
var alert notificationv1.Alert
|
||||
err = kubeClient.Get(ctx, namespacedName, &alert)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("resuming Alert %s in %s namespace", name, namespace)
|
||||
alert.Spec.Suspend = false
|
||||
if err := kubeClient.Update(ctx, &alert); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Alert resumed")
|
||||
|
||||
logger.Waitingf("waiting for Alert reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isAlertResumed(ctx, kubeClient, namespacedName, &alert)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Alert reconciliation completed")
|
||||
return nil
|
||||
}
|
||||
|
||||
func isAlertResumed(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, alert *notificationv1.Alert) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, alert)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(alert.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
if c.Reason == meta.SuspendedReason {
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
119
cmd/flux/resume_helmrelease.go
Normal file
119
cmd/flux/resume_helmrelease.go
Normal file
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
|
||||
)
|
||||
|
||||
var resumeHrCmd = &cobra.Command{
|
||||
Use: "helmrelease [name]",
|
||||
Aliases: []string{"hr"},
|
||||
Short: "Resume a suspended HelmRelease",
|
||||
Long: `The resume command marks a previously suspended HelmRelease resource for reconciliation and waits for it to
|
||||
finish the apply.`,
|
||||
Example: ` # Resume reconciliation for an existing Helm release
|
||||
flux resume hr podinfo
|
||||
`,
|
||||
RunE: resumeHrCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
resumeCmd.AddCommand(resumeHrCmd)
|
||||
}
|
||||
|
||||
func resumeHrCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("HelmRelease name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
var helmRelease helmv2.HelmRelease
|
||||
err = kubeClient.Get(ctx, namespacedName, &helmRelease)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("resuming HelmRelease %s in %s namespace", name, namespace)
|
||||
helmRelease.Spec.Suspend = false
|
||||
if err := kubeClient.Update(ctx, &helmRelease); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("HelmRelease resumed")
|
||||
|
||||
logger.Waitingf("waiting for HelmRelease reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isHelmReleaseResumed(ctx, kubeClient, namespacedName, &helmRelease)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("HelmRelease reconciliation completed")
|
||||
|
||||
logger.Successf("applied revision %s", helmRelease.Status.LastAppliedRevision)
|
||||
return nil
|
||||
}
|
||||
|
||||
func isHelmReleaseResumed(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, helmRelease *helmv2.HelmRelease) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, helmRelease)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Confirm the state we are observing is for the current generation
|
||||
if helmRelease.Generation != helmRelease.Status.ObservedGeneration {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(helmRelease.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
if c.Reason == meta.SuspendedReason {
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -20,8 +20,10 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1alpha1"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1alpha1"
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
@@ -35,6 +37,9 @@ var resumeKsCmd = &cobra.Command{
|
||||
Short: "Resume a suspended Kustomization",
|
||||
Long: `The resume command marks a previously suspended Kustomization resource for reconciliation and waits for it to
|
||||
finish the apply.`,
|
||||
Example: ` # Resume reconciliation for an existing Kustomization
|
||||
flux resume ks podinfo
|
||||
`,
|
||||
RunE: resumeKsCmdRun,
|
||||
}
|
||||
|
||||
@@ -44,14 +49,14 @@ func init() {
|
||||
|
||||
func resumeKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("kustomization name is required")
|
||||
return fmt.Errorf("Kustomization name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.kubeClient(kubeconfig)
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -66,59 +71,46 @@ func resumeKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("resuming kustomization %s in %s namespace", name, namespace)
|
||||
logger.Actionf("resuming Kustomization %s in %s namespace", name, namespace)
|
||||
kustomization.Spec.Suspend = false
|
||||
if err := kubeClient.Update(ctx, &kustomization); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("kustomization resumed")
|
||||
logger.Successf("Kustomization resumed")
|
||||
|
||||
logger.Waitingf("waiting for kustomization sync")
|
||||
logger.Waitingf("waiting for Kustomization reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isKustomizationResumed(ctx, kubeClient, name, namespace)); err != nil {
|
||||
isKustomizationResumed(ctx, kubeClient, namespacedName, &kustomization)); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Kustomization reconciliation completed")
|
||||
|
||||
logger.Successf("kustomization sync completed")
|
||||
|
||||
err = kubeClient.Get(ctx, namespacedName, &kustomization)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if kustomization.Status.LastAppliedRevision != "" {
|
||||
logger.Successf("applied revision %s", kustomization.Status.LastAppliedRevision)
|
||||
} else {
|
||||
return fmt.Errorf("kustomization sync failed")
|
||||
}
|
||||
|
||||
logger.Successf("applied revision %s", kustomization.Status.LastAppliedRevision)
|
||||
return nil
|
||||
}
|
||||
|
||||
func isKustomizationResumed(ctx context.Context, kubeClient client.Client, name, namespace string) wait.ConditionFunc {
|
||||
func isKustomizationResumed(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, kustomization *kustomizev1.Kustomization) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
var kustomization kustomizev1.Kustomization
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
err := kubeClient.Get(ctx, namespacedName, &kustomization)
|
||||
err := kubeClient.Get(ctx, namespacedName, kustomization)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
for _, condition := range kustomization.Status.Conditions {
|
||||
if condition.Type == sourcev1.ReadyCondition {
|
||||
if condition.Status == corev1.ConditionTrue {
|
||||
return true, nil
|
||||
} else if condition.Status == corev1.ConditionFalse {
|
||||
if condition.Reason == kustomizev1.SuspendedReason {
|
||||
return false, nil
|
||||
}
|
||||
// Confirm the state we are observing is for the current generation
|
||||
if kustomization.Generation != kustomization.Status.ObservedGeneration {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return false, fmt.Errorf(condition.Message)
|
||||
if c := meta.GetCondition(kustomization.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
if c.Reason == meta.SuspendedReason {
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
112
cmd/flux/resume_receiver.go
Normal file
112
cmd/flux/resume_receiver.go
Normal file
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
"github.com/fluxcd/pkg/apis/meta"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var resumeReceiverCmd = &cobra.Command{
|
||||
Use: "receiver [name]",
|
||||
Short: "Resume a suspended Receiver",
|
||||
Long: `The resume command marks a previously suspended Receiver resource for reconciliation and waits for it to
|
||||
finish the apply.`,
|
||||
Example: ` # Resume reconciliation for an existing Receiver
|
||||
flux resume receiver main
|
||||
`,
|
||||
RunE: resumeReceiverCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
resumeCmd.AddCommand(resumeReceiverCmd)
|
||||
}
|
||||
|
||||
func resumeReceiverCmdRun(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(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
var receiver notificationv1.Receiver
|
||||
err = kubeClient.Get(ctx, namespacedName, &receiver)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("resuming Receiver %s in %s namespace", name, namespace)
|
||||
receiver.Spec.Suspend = false
|
||||
if err := kubeClient.Update(ctx, &receiver); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Receiver resumed")
|
||||
|
||||
logger.Waitingf("waiting for Receiver reconciliation")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isReceiverResumed(ctx, kubeClient, namespacedName, &receiver)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Successf("Receiver reconciliation completed")
|
||||
return nil
|
||||
}
|
||||
|
||||
func isReceiverResumed(ctx context.Context, kubeClient client.Client,
|
||||
namespacedName types.NamespacedName, receiver *notificationv1.Receiver) wait.ConditionFunc {
|
||||
return func() (bool, error) {
|
||||
err := kubeClient.Get(ctx, namespacedName, receiver)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if c := meta.GetCondition(receiver.Status.Conditions, meta.ReadyCondition); c != nil {
|
||||
switch c.Status {
|
||||
case corev1.ConditionTrue:
|
||||
return true, nil
|
||||
case corev1.ConditionFalse:
|
||||
if c.Reason == meta.SuspendedReason {
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf(c.Message)
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
76
cmd/flux/suspend_alert.go
Normal file
76
cmd/flux/suspend_alert.go
Normal file
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var suspendAlertCmd = &cobra.Command{
|
||||
Use: "alert [name]",
|
||||
Short: "Suspend reconciliation of Alert",
|
||||
Long: "The suspend command disables the reconciliation of a Alert resource.",
|
||||
Example: ` # Suspend reconciliation for an existing Alert
|
||||
flux suspend alert main
|
||||
`,
|
||||
RunE: suspendAlertCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
suspendCmd.AddCommand(suspendAlertCmd)
|
||||
}
|
||||
|
||||
func suspendAlertCmdRun(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(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
var alert notificationv1.Alert
|
||||
err = kubeClient.Get(ctx, namespacedName, &alert)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("suspending Alert %s in %s namespace", name, namespace)
|
||||
alert.Spec.Suspend = true
|
||||
if err := kubeClient.Update(ctx, &alert); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Alert suspended")
|
||||
|
||||
return nil
|
||||
}
|
||||
77
cmd/flux/suspend_helmrelease.go
Normal file
77
cmd/flux/suspend_helmrelease.go
Normal file
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
|
||||
)
|
||||
|
||||
var suspendHrCmd = &cobra.Command{
|
||||
Use: "helmrelease [name]",
|
||||
Aliases: []string{"hr"},
|
||||
Short: "Suspend reconciliation of HelmRelease",
|
||||
Long: "The suspend command disables the reconciliation of a HelmRelease resource.",
|
||||
Example: ` # Suspend reconciliation for an existing Helm release
|
||||
flux suspend hr podinfo
|
||||
`,
|
||||
RunE: suspendHrCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
suspendCmd.AddCommand(suspendHrCmd)
|
||||
}
|
||||
|
||||
func suspendHrCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("HelmRelease name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
var helmRelease helmv2.HelmRelease
|
||||
err = kubeClient.Get(ctx, namespacedName, &helmRelease)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("suspending HelmRelease %s in %s namespace", name, namespace)
|
||||
helmRelease.Spec.Suspend = true
|
||||
if err := kubeClient.Update(ctx, &helmRelease); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("HelmRelease suspended")
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
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.
|
||||
@@ -19,7 +19,9 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1alpha1"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
)
|
||||
@@ -29,7 +31,10 @@ var suspendKsCmd = &cobra.Command{
|
||||
Aliases: []string{"ks"},
|
||||
Short: "Suspend reconciliation of Kustomization",
|
||||
Long: "The suspend command disables the reconciliation of a Kustomization resource.",
|
||||
RunE: suspendKsCmdRun,
|
||||
Example: ` # Suspend reconciliation for an existing Kustomization
|
||||
flux suspend ks podinfo
|
||||
`,
|
||||
RunE: suspendKsCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -45,7 +50,7 @@ func suspendKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.kubeClient(kubeconfig)
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
76
cmd/flux/suspend_receiver.go
Normal file
76
cmd/flux/suspend_receiver.go
Normal file
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
notificationv1 "github.com/fluxcd/notification-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var suspendReceiverCmd = &cobra.Command{
|
||||
Use: "receiver [name]",
|
||||
Short: "Suspend reconciliation of Receiver",
|
||||
Long: "The suspend command disables the reconciliation of a Receiver resource.",
|
||||
Example: ` # Suspend reconciliation for an existing Receiver
|
||||
flux suspend receiver main
|
||||
`,
|
||||
RunE: suspendReceiverCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
suspendCmd.AddCommand(suspendReceiverCmd)
|
||||
}
|
||||
|
||||
func suspendReceiverCmdRun(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(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
var receiver notificationv1.Receiver
|
||||
err = kubeClient.Get(ctx, namespacedName, &receiver)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Actionf("suspending Receiver %s in %s namespace", name, namespace)
|
||||
receiver.Spec.Suspend = true
|
||||
if err := kubeClient.Update(ctx, &receiver); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("Receiver suspended")
|
||||
|
||||
return nil
|
||||
}
|
||||
169
cmd/flux/uninstall.go
Normal file
169
cmd/flux/uninstall.go
Normal file
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
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 (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/manifoldco/promptui"
|
||||
"github.com/spf13/cobra"
|
||||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/fluxcd/flux2/internal/utils"
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2beta1"
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
|
||||
)
|
||||
|
||||
var uninstallCmd = &cobra.Command{
|
||||
Use: "uninstall",
|
||||
Short: "Uninstall the toolkit components",
|
||||
Long: "The uninstall command removes the namespace, cluster roles, cluster role bindings and CRDs from the cluster.",
|
||||
Example: ` # Dry-run uninstall of all components
|
||||
flux uninstall --dry-run --namespace=flux-system
|
||||
|
||||
# Uninstall all components and delete custom resource definitions
|
||||
flux uninstall --resources --crds --namespace=flux-system
|
||||
`,
|
||||
RunE: uninstallCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
uninstallCRDs bool
|
||||
uninstallResources bool
|
||||
uninstallDryRun bool
|
||||
uninstallSilent bool
|
||||
)
|
||||
|
||||
func init() {
|
||||
uninstallCmd.Flags().BoolVar(&uninstallResources, "resources", true,
|
||||
"removes custom resources such as Kustomizations, GitRepositories and HelmRepositories")
|
||||
uninstallCmd.Flags().BoolVar(&uninstallCRDs, "crds", false,
|
||||
"removes all CRDs previously installed")
|
||||
uninstallCmd.Flags().BoolVar(&uninstallDryRun, "dry-run", false,
|
||||
"only print the object that would be deleted")
|
||||
uninstallCmd.Flags().BoolVarP(&uninstallSilent, "silent", "s", false,
|
||||
"delete components without asking for confirmation")
|
||||
|
||||
rootCmd.AddCommand(uninstallCmd)
|
||||
}
|
||||
|
||||
func uninstallCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.KubeClient(kubeconfig, kubecontext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !uninstallDryRun && !uninstallSilent {
|
||||
prompt := promptui.Prompt{
|
||||
Label: fmt.Sprintf("Are you sure you want to delete the %s namespace", namespace),
|
||||
IsConfirm: true,
|
||||
}
|
||||
if _, err := prompt.Run(); err != nil {
|
||||
return fmt.Errorf("aborting")
|
||||
}
|
||||
}
|
||||
|
||||
dryRun := "--dry-run=server"
|
||||
deleteResources := uninstallResources || uninstallCRDs
|
||||
|
||||
// known kinds with finalizers
|
||||
namespacedKinds := []string{
|
||||
sourcev1.GitRepositoryKind,
|
||||
sourcev1.HelmRepositoryKind,
|
||||
sourcev1.BucketKind,
|
||||
}
|
||||
|
||||
// suspend bootstrap kustomization to avoid finalizers deadlock
|
||||
kustomizationName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: namespace,
|
||||
}
|
||||
var kustomization kustomizev1.Kustomization
|
||||
err = kubeClient.Get(ctx, kustomizationName, &kustomization)
|
||||
if err == nil {
|
||||
kustomization.Spec.Suspend = true
|
||||
if err := kubeClient.Update(ctx, &kustomization); err != nil {
|
||||
return fmt.Errorf("unable to suspend kustomization '%s': %w", kustomizationName.String(), err)
|
||||
}
|
||||
}
|
||||
if err == nil || apierrors.IsNotFound(err) {
|
||||
namespacedKinds = append(namespacedKinds, kustomizev1.KustomizationKind)
|
||||
}
|
||||
|
||||
// add HelmRelease kind to deletion list if exists
|
||||
var list helmv2.HelmReleaseList
|
||||
if err := kubeClient.List(ctx, &list, client.InNamespace(namespace)); err == nil {
|
||||
namespacedKinds = append(namespacedKinds, helmv2.HelmReleaseKind)
|
||||
}
|
||||
|
||||
if deleteResources {
|
||||
logger.Actionf("uninstalling custom resources")
|
||||
for _, kind := range namespacedKinds {
|
||||
if err := deleteAll(ctx, kind, uninstallDryRun); err != nil {
|
||||
logger.Failuref("kubectl: %s", err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var kinds []string
|
||||
if uninstallCRDs {
|
||||
kinds = append(kinds, "crds")
|
||||
}
|
||||
|
||||
kinds = append(kinds, "clusterroles,clusterrolebindings", "namespace")
|
||||
|
||||
logger.Actionf("uninstalling components")
|
||||
|
||||
for _, kind := range kinds {
|
||||
kubectlArgs := []string{
|
||||
"delete", kind,
|
||||
"-l", fmt.Sprintf("app.kubernetes.io/instance=%s", namespace),
|
||||
"--ignore-not-found", "--timeout", timeout.String(),
|
||||
}
|
||||
if uninstallDryRun {
|
||||
kubectlArgs = append(kubectlArgs, dryRun)
|
||||
}
|
||||
if _, err := utils.ExecKubectlCommand(ctx, utils.ModeOS, kubectlArgs...); err != nil {
|
||||
return fmt.Errorf("uninstall failed: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
logger.Successf("uninstall finished")
|
||||
return nil
|
||||
}
|
||||
|
||||
func deleteAll(ctx context.Context, kind string, dryRun bool) error {
|
||||
kubectlArgs := []string{
|
||||
"delete", kind, "--ignore-not-found",
|
||||
"--all", "--all-namespaces",
|
||||
"--timeout", timeout.String(),
|
||||
}
|
||||
|
||||
if dryRun {
|
||||
kubectlArgs = append(kubectlArgs, "--dry-run=server")
|
||||
}
|
||||
|
||||
_, err := utils.ExecKubectlCommand(ctx, utils.ModeOS, kubectlArgs...)
|
||||
return err
|
||||
}
|
||||
@@ -1,250 +0,0 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
|
||||
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"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sigs.k8s.io/yaml"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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/v1alpha1"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1alpha1"
|
||||
)
|
||||
|
||||
var bootstrapCmd = &cobra.Command{
|
||||
Use: "bootstrap",
|
||||
Short: "Bootstrap toolkit components",
|
||||
Long: "The bootstrap sub-commands bootstrap the toolkit components on the targeted Git provider.",
|
||||
}
|
||||
|
||||
var (
|
||||
bootstrapVersion string
|
||||
)
|
||||
|
||||
const (
|
||||
bootstrapBranch = "master"
|
||||
bootstrapInstallManifest = "toolkit-components.yaml"
|
||||
bootstrapSourceManifest = "toolkit-source.yaml"
|
||||
bootstrapKustomizationManifest = "toolkit-kustomization.yaml"
|
||||
)
|
||||
|
||||
func init() {
|
||||
bootstrapCmd.PersistentFlags().StringVar(&bootstrapVersion, "version", "master", "toolkit tag or branch")
|
||||
|
||||
rootCmd.AddCommand(bootstrapCmd)
|
||||
}
|
||||
|
||||
func generateInstallManifests(targetPath, namespace, tmpDir string) (string, error) {
|
||||
tkDir := path.Join(tmpDir, ".tk")
|
||||
defer os.RemoveAll(tkDir)
|
||||
|
||||
if err := os.MkdirAll(tkDir, os.ModePerm); err != nil {
|
||||
return "", fmt.Errorf("generating manifests failed: %w", err)
|
||||
}
|
||||
|
||||
if err := genInstallManifests(bootstrapVersion, namespace, components, tkDir); err != nil {
|
||||
return "", fmt.Errorf("generating manifests failed: %w", err)
|
||||
}
|
||||
|
||||
manifestsDir := path.Join(tmpDir, targetPath, namespace)
|
||||
if err := os.MkdirAll(manifestsDir, os.ModePerm); err != nil {
|
||||
return "", fmt.Errorf("generating manifests failed: %w", err)
|
||||
}
|
||||
|
||||
manifest := path.Join(manifestsDir, bootstrapInstallManifest)
|
||||
if err := buildKustomization(tkDir, manifest); err != nil {
|
||||
return "", fmt.Errorf("build kustomization failed: %w", err)
|
||||
}
|
||||
|
||||
return manifest, nil
|
||||
}
|
||||
|
||||
func applyInstallManifests(ctx context.Context, manifestPath string, components []string) error {
|
||||
command := fmt.Sprintf("kubectl apply -f %s", manifestPath)
|
||||
if _, err := utils.execCommand(ctx, ModeOS, command); err != nil {
|
||||
return fmt.Errorf("install failed")
|
||||
}
|
||||
|
||||
for _, deployment := range components {
|
||||
command = fmt.Sprintf("kubectl -n %s rollout status deployment %s --timeout=%s",
|
||||
namespace, deployment, timeout.String())
|
||||
if _, err := utils.execCommand(ctx, ModeOS, command); err != nil {
|
||||
return fmt.Errorf("install failed")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateSyncManifests(url, name, namespace, targetPath, tmpDir string, interval time.Duration) error {
|
||||
gvk := sourcev1.GroupVersion.WithKind("GitRepository")
|
||||
gitRepository := sourcev1.GitRepository{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
Kind: gvk.Kind,
|
||||
APIVersion: gvk.GroupVersion().String(),
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
},
|
||||
Spec: sourcev1.GitRepositorySpec{
|
||||
URL: url,
|
||||
Interval: metav1.Duration{
|
||||
Duration: interval,
|
||||
},
|
||||
Reference: &sourcev1.GitRepositoryRef{
|
||||
Branch: "master",
|
||||
},
|
||||
SecretRef: &corev1.LocalObjectReference{
|
||||
Name: name,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
gitData, err := yaml.Marshal(gitRepository)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := utils.writeFile(string(gitData), filepath.Join(tmpDir, targetPath, namespace, bootstrapSourceManifest)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
gvk = kustomizev1.GroupVersion.WithKind("Kustomization")
|
||||
emptyAPIGroup := ""
|
||||
kustomization := kustomizev1.Kustomization{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
Kind: gvk.Kind,
|
||||
APIVersion: gvk.GroupVersion().String(),
|
||||
},
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
Namespace: namespace,
|
||||
},
|
||||
Spec: kustomizev1.KustomizationSpec{
|
||||
Interval: metav1.Duration{
|
||||
Duration: 10 * time.Minute,
|
||||
},
|
||||
Path: fmt.Sprintf("./%s", strings.TrimPrefix(targetPath, "./")),
|
||||
Prune: true,
|
||||
SourceRef: corev1.TypedLocalObjectReference{
|
||||
APIGroup: &emptyAPIGroup,
|
||||
Kind: "GitRepository",
|
||||
Name: name,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
ksData, err := yaml.Marshal(kustomization)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := utils.writeFile(string(ksData), filepath.Join(tmpDir, targetPath, namespace, bootstrapKustomizationManifest)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func applySyncManifests(ctx context.Context, kubeClient client.Client, name, namespace, targetPath, tmpDir string) error {
|
||||
command := fmt.Sprintf("kubectl apply -f %s", filepath.Join(tmpDir, targetPath, namespace))
|
||||
if _, err := utils.execCommand(ctx, ModeStderrOS, command); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Waitingf("waiting for cluster sync")
|
||||
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isGitRepositoryReady(ctx, kubeClient, name, namespace)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isKustomizationReady(ctx, kubeClient, name, namespace)); 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)
|
||||
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
|
||||
}
|
||||
130
cmd/tk/flags.go
130
cmd/tk/flags.go
@@ -1,130 +0,0 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
|
||||
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 (
|
||||
"crypto/elliptic"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var supportedPublicKeyAlgorithms = []string{"rsa", "ecdsa", "ed25519"}
|
||||
|
||||
type PublicKeyAlgorithm string
|
||||
|
||||
func (a *PublicKeyAlgorithm) String() string {
|
||||
return string(*a)
|
||||
}
|
||||
|
||||
func (a *PublicKeyAlgorithm) Set(str string) error {
|
||||
if strings.TrimSpace(str) == "" {
|
||||
return fmt.Errorf("no public key algorithm given, must be one of: %s",
|
||||
strings.Join(supportedPublicKeyAlgorithms, ", "))
|
||||
}
|
||||
for _, v := range supportedPublicKeyAlgorithms {
|
||||
if str == v {
|
||||
*a = PublicKeyAlgorithm(str)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("unsupported public key algorithm '%s', must be one of: %s",
|
||||
str, strings.Join(supportedPublicKeyAlgorithms, ", "))
|
||||
}
|
||||
|
||||
func (a *PublicKeyAlgorithm) Type() string {
|
||||
return "publicKeyAlgorithm"
|
||||
}
|
||||
|
||||
func (a *PublicKeyAlgorithm) Description() string {
|
||||
return fmt.Sprintf("SSH public key algorithm (%s)", strings.Join(supportedPublicKeyAlgorithms, ", "))
|
||||
}
|
||||
|
||||
var defaultRSAKeyBits = 2048
|
||||
|
||||
type RSAKeyBits int
|
||||
|
||||
func (b *RSAKeyBits) String() string {
|
||||
return strconv.Itoa(int(*b))
|
||||
}
|
||||
|
||||
func (b *RSAKeyBits) Set(str string) error {
|
||||
if strings.TrimSpace(str) == "" {
|
||||
*b = RSAKeyBits(defaultRSAKeyBits)
|
||||
return nil
|
||||
}
|
||||
bits, err := strconv.Atoi(str)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if bits%8 != 0 {
|
||||
return fmt.Errorf("RSA key bit size should be a multiples of 8")
|
||||
}
|
||||
*b = RSAKeyBits(bits)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *RSAKeyBits) Type() string {
|
||||
return "rsaKeyBits"
|
||||
}
|
||||
|
||||
func (b *RSAKeyBits) Description() string {
|
||||
return "SSH RSA public key bit size (multiplies of 8)"
|
||||
}
|
||||
|
||||
type ECDSACurve struct {
|
||||
elliptic.Curve
|
||||
}
|
||||
|
||||
var supportedECDSACurves = map[string]elliptic.Curve{
|
||||
"p256": elliptic.P256(),
|
||||
"p384": elliptic.P384(),
|
||||
"p521": elliptic.P521(),
|
||||
}
|
||||
|
||||
func (c *ECDSACurve) String() string {
|
||||
if c.Curve == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.ToLower(strings.Replace(c.Curve.Params().Name, "-", "", 1))
|
||||
}
|
||||
|
||||
func (c *ECDSACurve) Set(str string) error {
|
||||
if v, ok := supportedECDSACurves[str]; ok {
|
||||
*c = ECDSACurve{v}
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unsupported curve '%s', should be one of: %s", str, strings.Join(ecdsaCurves(), ", "))
|
||||
}
|
||||
|
||||
func (c *ECDSACurve) Type() string {
|
||||
return "ecdsaCurve"
|
||||
}
|
||||
|
||||
func (c *ECDSACurve) Description() string {
|
||||
return fmt.Sprintf("SSH ECDSA public key curve (%s)", strings.Join(ecdsaCurves(), ", "))
|
||||
}
|
||||
|
||||
func ecdsaCurves() []string {
|
||||
keys := make([]string, 0, len(supportedECDSACurves))
|
||||
for k := range supportedECDSACurves {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
|
||||
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"
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1alpha1"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
var getKsCmd = &cobra.Command{
|
||||
Use: "kustomizations",
|
||||
Aliases: []string{"ks"},
|
||||
Short: "Get Kustomization source statuses",
|
||||
Long: "The get kustomizations command prints the statuses of the resources.",
|
||||
RunE: getKsCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
getCmd.AddCommand(getKsCmd)
|
||||
}
|
||||
|
||||
func getKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.kubeClient(kubeconfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var list kustomizev1.KustomizationList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no kustomizations found in %s namespace", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, kustomization := range list.Items {
|
||||
if kustomization.Spec.Suspend {
|
||||
logger.Successf("%s is suspended", kustomization.GetName())
|
||||
continue
|
||||
}
|
||||
isInitialized := false
|
||||
for _, condition := range kustomization.Status.Conditions {
|
||||
if condition.Type == kustomizev1.ReadyCondition {
|
||||
if condition.Status != corev1.ConditionFalse {
|
||||
if kustomization.Status.LastAppliedRevision != "" {
|
||||
logger.Successf("%s last applied revision %s", kustomization.GetName(), kustomization.Status.LastAppliedRevision)
|
||||
} else {
|
||||
logger.Successf("%s reconciling", kustomization.GetName())
|
||||
}
|
||||
} else {
|
||||
logger.Failuref("%s %s", kustomization.GetName(), condition.Message)
|
||||
}
|
||||
isInitialized = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isInitialized {
|
||||
logger.Failuref("%s is not ready", kustomization.GetName())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
|
||||
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"
|
||||
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1alpha1"
|
||||
"github.com/spf13/cobra"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
var getSourceGitCmd = &cobra.Command{
|
||||
Use: "git",
|
||||
Short: "Get GitRepository source statuses",
|
||||
Long: "The get sources git command prints the status of the GitRepository sources.",
|
||||
RunE: getSourceGitCmdRun,
|
||||
}
|
||||
|
||||
func init() {
|
||||
getSourceCmd.AddCommand(getSourceGitCmd)
|
||||
}
|
||||
|
||||
func getSourceGitCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.kubeClient(kubeconfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var list sourcev1.GitRepositoryList
|
||||
err = kubeClient.List(ctx, &list, client.InNamespace(namespace))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(list.Items) == 0 {
|
||||
logger.Failuref("no sources found in %s namespace", namespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, source := range list.Items {
|
||||
isInitialized := false
|
||||
for _, condition := range source.Status.Conditions {
|
||||
if condition.Type == sourcev1.ReadyCondition {
|
||||
if condition.Status != corev1.ConditionFalse {
|
||||
logger.Successf("%s last fetched revision: %s", source.GetName(), source.Status.Artifact.Revision)
|
||||
} else {
|
||||
logger.Failuref("%s %s", source.GetName(), condition.Message)
|
||||
}
|
||||
isInitialized = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isInitialized {
|
||||
logger.Failuref("%s is not ready", source.GetName())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,248 +0,0 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
|
||||
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"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"sigs.k8s.io/kustomize/api/filesys"
|
||||
"sigs.k8s.io/kustomize/api/krusty"
|
||||
)
|
||||
|
||||
var installCmd = &cobra.Command{
|
||||
Use: "install",
|
||||
Short: "Install the toolkit components",
|
||||
Long: `The install command deploys the toolkit components in the specified namespace.
|
||||
If a previous version is installed, then an in-place upgrade will be performed.`,
|
||||
Example: ` # Install the latest version in the gitops-systems namespace
|
||||
install --version=master --namespace=gitops-systems
|
||||
|
||||
# Dry-run install for a specific version and a series of components
|
||||
install --dry-run --version=0.0.1 --components="source-controller,kustomize-controller"
|
||||
|
||||
# Dry-run install with manifests preview
|
||||
install --dry-run --verbose
|
||||
`,
|
||||
RunE: installCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
installDryRun bool
|
||||
installManifestsPath string
|
||||
installVersion string
|
||||
)
|
||||
|
||||
func init() {
|
||||
installCmd.Flags().BoolVarP(&installDryRun, "dry-run", "", false,
|
||||
"only print the object that would be applied")
|
||||
installCmd.Flags().StringVarP(&installVersion, "version", "v", "master",
|
||||
"toolkit tag or branch")
|
||||
installCmd.Flags().StringVarP(&installManifestsPath, "manifests", "", "",
|
||||
"path to the manifest directory, dev only")
|
||||
rootCmd.AddCommand(installCmd)
|
||||
}
|
||||
|
||||
func installCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
var kustomizePath string
|
||||
if installVersion == "" && !strings.HasPrefix(installManifestsPath, "github.com/") {
|
||||
if _, err := os.Stat(installManifestsPath); err != nil {
|
||||
return fmt.Errorf("manifests not found: %w", err)
|
||||
}
|
||||
kustomizePath = installManifestsPath
|
||||
}
|
||||
|
||||
tmpDir, err := ioutil.TempDir("", namespace)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
logger.Generatef("generating manifests")
|
||||
if kustomizePath == "" {
|
||||
err = genInstallManifests(installVersion, namespace, components, tmpDir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("install failed: %w", err)
|
||||
}
|
||||
kustomizePath = tmpDir
|
||||
}
|
||||
|
||||
manifest := path.Join(tmpDir, fmt.Sprintf("%s.yaml", namespace))
|
||||
if err := buildKustomization(kustomizePath, manifest); err != nil {
|
||||
return fmt.Errorf("install failed: %w", err)
|
||||
}
|
||||
|
||||
command := fmt.Sprintf("cat %s", manifest)
|
||||
if yaml, err := utils.execCommand(ctx, ModeCapture, command); err != nil {
|
||||
return fmt.Errorf("install failed: %w", err)
|
||||
} else {
|
||||
if verbose {
|
||||
fmt.Print(yaml)
|
||||
}
|
||||
}
|
||||
logger.Successf("manifests build completed")
|
||||
|
||||
logger.Actionf("installing components in %s namespace", namespace)
|
||||
applyOutput := ModeStderrOS
|
||||
if verbose {
|
||||
applyOutput = ModeOS
|
||||
}
|
||||
dryRun := ""
|
||||
if installDryRun {
|
||||
dryRun = "--dry-run=client"
|
||||
applyOutput = ModeOS
|
||||
}
|
||||
command = fmt.Sprintf("cat %s | kubectl apply -f- %s", manifest, dryRun)
|
||||
if _, err := utils.execCommand(ctx, applyOutput, command); err != nil {
|
||||
return fmt.Errorf("install failed")
|
||||
}
|
||||
|
||||
if installDryRun {
|
||||
logger.Successf("install dry-run finished")
|
||||
return nil
|
||||
} else {
|
||||
logger.Successf("install completed")
|
||||
}
|
||||
|
||||
logger.Waitingf("verifying installation")
|
||||
for _, deployment := range components {
|
||||
command = fmt.Sprintf("kubectl -n %s rollout status deployment %s --timeout=%s",
|
||||
namespace, deployment, timeout.String())
|
||||
if _, err := utils.execCommand(ctx, applyOutput, command); err != nil {
|
||||
return fmt.Errorf("install failed")
|
||||
} else {
|
||||
logger.Successf("%s ready", deployment)
|
||||
}
|
||||
}
|
||||
|
||||
logger.Successf("install finished")
|
||||
return nil
|
||||
}
|
||||
|
||||
var namespaceTmpl = `---
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: {{.Namespace}}
|
||||
`
|
||||
|
||||
var labelsTmpl = `---
|
||||
apiVersion: builtin
|
||||
kind: LabelTransformer
|
||||
metadata:
|
||||
name: labels
|
||||
labels:
|
||||
app.kubernetes.io/instance: {{.Namespace}}
|
||||
app.kubernetes.io/version: "{{.Version}}"
|
||||
fieldSpecs:
|
||||
- path: metadata/labels
|
||||
create: true
|
||||
`
|
||||
|
||||
var kustomizationTmpl = `---
|
||||
{{- $version := .Version }}
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
namespace: {{.Namespace}}
|
||||
transformers:
|
||||
- labels.yaml
|
||||
resources:
|
||||
- namespace.yaml
|
||||
- roles
|
||||
- github.com/fluxcd/toolkit/manifests/policies?ref={{$version}}
|
||||
{{- range .Components }}
|
||||
- github.com/fluxcd/toolkit/manifests/bases/{{.}}?ref={{$version}}
|
||||
{{- end }}
|
||||
`
|
||||
|
||||
var kustomizationRolesTmpl = `---
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
resources:
|
||||
- github.com/fluxcd/toolkit/manifests/rbac?ref={{.Version}}
|
||||
nameSuffix: -{{.Namespace}}
|
||||
`
|
||||
|
||||
func genInstallManifests(version string, namespace string, components []string, tmpDir string) error {
|
||||
model := struct {
|
||||
Version string
|
||||
Namespace string
|
||||
Components []string
|
||||
}{
|
||||
Version: version,
|
||||
Namespace: namespace,
|
||||
Components: components,
|
||||
}
|
||||
|
||||
if err := utils.execTemplate(model, namespaceTmpl, path.Join(tmpDir, "namespace.yaml")); err != nil {
|
||||
return fmt.Errorf("generate namespace failed: %w", err)
|
||||
}
|
||||
|
||||
if err := utils.execTemplate(model, labelsTmpl, path.Join(tmpDir, "labels.yaml")); err != nil {
|
||||
return fmt.Errorf("generate labels failed: %w", err)
|
||||
}
|
||||
|
||||
if err := utils.execTemplate(model, kustomizationTmpl, path.Join(tmpDir, "kustomization.yaml")); err != nil {
|
||||
return fmt.Errorf("generate kustomization failed: %w", err)
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(path.Join(tmpDir, "roles"), os.ModePerm); err != nil {
|
||||
return fmt.Errorf("generate roles failed: %w", err)
|
||||
}
|
||||
|
||||
if err := utils.execTemplate(model, kustomizationRolesTmpl, path.Join(tmpDir, "roles/kustomization.yaml")); err != nil {
|
||||
return fmt.Errorf("generate roles failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func buildKustomization(base, manifests string) error {
|
||||
kfile := filepath.Join(base, "kustomization.yaml")
|
||||
|
||||
fs := filesys.MakeFsOnDisk()
|
||||
if !fs.Exists(kfile) {
|
||||
return fmt.Errorf("%s not found", kfile)
|
||||
}
|
||||
|
||||
opt := krusty.MakeDefaultOptions()
|
||||
k := krusty.MakeKustomizer(fs, opt)
|
||||
m, err := k.Run(base)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resources, err := m.AsYaml()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := fs.WriteFile(manifests, resources); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
|
||||
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"
|
||||
"time"
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1alpha1"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/wait"
|
||||
)
|
||||
|
||||
var syncKsCmd = &cobra.Command{
|
||||
Use: "kustomization [name]",
|
||||
Aliases: []string{"ks"},
|
||||
Short: "Synchronize a Kustomization resource",
|
||||
Long: `
|
||||
The sync kustomization command triggers a reconciliation of a Kustomization resource and waits for it to finish.`,
|
||||
Example: ` # Trigger a Kustomization apply outside of the reconciliation interval
|
||||
sync kustomization podinfo
|
||||
|
||||
# Trigger a sync of the Kustomization's source and apply changes
|
||||
sync kustomization podinfo --with-source
|
||||
`,
|
||||
RunE: syncKsCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
syncKsWithSource bool
|
||||
)
|
||||
|
||||
func init() {
|
||||
syncKsCmd.Flags().BoolVar(&syncKsWithSource, "with-source", false, "synchronize kustomization source")
|
||||
|
||||
syncCmd.AddCommand(syncKsCmd)
|
||||
}
|
||||
|
||||
func syncKsCmdRun(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return fmt.Errorf("kustomization name is required")
|
||||
}
|
||||
name := args[0]
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
kubeClient, err := utils.kubeClient(kubeconfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
namespacedName := types.NamespacedName{
|
||||
Namespace: namespace,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
var kustomization kustomizev1.Kustomization
|
||||
err = kubeClient.Get(ctx, namespacedName, &kustomization)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if syncKsWithSource {
|
||||
err := syncSourceGitCmdRun(nil, []string{kustomization.Spec.SourceRef.Name})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
logger.Actionf("annotating kustomization %s in %s namespace", name, namespace)
|
||||
if kustomization.Annotations == nil {
|
||||
kustomization.Annotations = map[string]string{
|
||||
kustomizev1.SyncAtAnnotation: time.Now().String(),
|
||||
}
|
||||
} else {
|
||||
kustomization.Annotations[kustomizev1.SyncAtAnnotation] = time.Now().String()
|
||||
}
|
||||
if err := kubeClient.Update(ctx, &kustomization); err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Successf("kustomization annotated")
|
||||
}
|
||||
|
||||
logger.Waitingf("waiting for kustomization sync")
|
||||
if err := wait.PollImmediate(pollInterval, timeout,
|
||||
isKustomizationReady(ctx, kubeClient, name, namespace)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Successf("kustomization sync completed")
|
||||
|
||||
err = kubeClient.Get(ctx, namespacedName, &kustomization)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if kustomization.Status.LastAppliedRevision != "" {
|
||||
logger.Successf("applied revision %s", kustomization.Status.LastAppliedRevision)
|
||||
} else {
|
||||
return fmt.Errorf("kustomization sync failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
|
||||
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"
|
||||
"time"
|
||||
|
||||
"github.com/manifoldco/promptui"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var uninstallCmd = &cobra.Command{
|
||||
Use: "uninstall",
|
||||
Short: "Uninstall the toolkit components",
|
||||
Long: "The uninstall command removes the namespace, cluster roles, cluster role bindings and CRDs from the cluster.",
|
||||
Example: ` # Dry-run uninstall of all components
|
||||
uninstall --dry-run --namespace=gitops-system
|
||||
|
||||
# Uninstall all components and delete custom resource definitions
|
||||
uninstall --crds --namespace=gitops-system
|
||||
`,
|
||||
RunE: uninstallCmdRun,
|
||||
}
|
||||
|
||||
var (
|
||||
uninstallCRDs bool
|
||||
uninstallKustomizations bool
|
||||
uninstallDryRun bool
|
||||
uninstallSilent bool
|
||||
)
|
||||
|
||||
func init() {
|
||||
uninstallCmd.Flags().BoolVarP(&uninstallKustomizations, "kustomizations", "", false,
|
||||
"removes all Kustomizations previously installed")
|
||||
uninstallCmd.Flags().BoolVarP(&uninstallCRDs, "crds", "", false,
|
||||
"removes all CRDs previously installed")
|
||||
uninstallCmd.Flags().BoolVarP(&uninstallDryRun, "dry-run", "", false,
|
||||
"only print the object that would be deleted")
|
||||
uninstallCmd.Flags().BoolVarP(&uninstallSilent, "silent", "s", false,
|
||||
"delete components without asking for confirmation")
|
||||
|
||||
rootCmd.AddCommand(uninstallCmd)
|
||||
}
|
||||
|
||||
func uninstallCmdRun(cmd *cobra.Command, args []string) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
dryRun := ""
|
||||
if uninstallDryRun {
|
||||
dryRun = "--dry-run=client"
|
||||
} else if !uninstallSilent {
|
||||
prompt := promptui.Prompt{
|
||||
Label: fmt.Sprintf("Are you sure you want to delete the %s namespace", namespace),
|
||||
IsConfirm: true,
|
||||
}
|
||||
if _, err := prompt.Run(); err != nil {
|
||||
return fmt.Errorf("aborting")
|
||||
}
|
||||
}
|
||||
|
||||
if uninstallKustomizations {
|
||||
logger.Actionf("uninstalling kustomizations")
|
||||
command := fmt.Sprintf("kubectl -n %s delete kustomizations --all --timeout=%s %s",
|
||||
namespace, timeout.String(), dryRun)
|
||||
if _, err := utils.execCommand(ctx, ModeOS, command); err != nil {
|
||||
return fmt.Errorf("uninstall failed")
|
||||
}
|
||||
|
||||
// TODO: use the kustomizations snapshots to create a list of objects
|
||||
// that are subject to deletion and wait for all of them to be terminated
|
||||
logger.Waitingf("waiting on GC")
|
||||
time.Sleep(30 * time.Second)
|
||||
}
|
||||
|
||||
kinds := "namespace,clusterroles,clusterrolebindings"
|
||||
if uninstallCRDs {
|
||||
kinds += ",crds"
|
||||
}
|
||||
|
||||
logger.Actionf("uninstalling components")
|
||||
command := fmt.Sprintf("kubectl delete %s -l app.kubernetes.io/instance=%s --timeout=%s %s",
|
||||
kinds, namespace, timeout.String(), dryRun)
|
||||
if _, err := utils.execCommand(ctx, ModeOS, command); err != nil {
|
||||
return fmt.Errorf("uninstall failed")
|
||||
}
|
||||
|
||||
logger.Successf("uninstall finished")
|
||||
return nil
|
||||
}
|
||||
145
cmd/tk/utils.go
145
cmd/tk/utils.go
@@ -1,145 +0,0 @@
|
||||
/*
|
||||
Copyright 2020 The Flux CD contributors.
|
||||
|
||||
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 (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"text/template"
|
||||
|
||||
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1alpha1"
|
||||
sourcev1 "github.com/fluxcd/source-controller/api/v1alpha1"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/client-go/tools/clientcmd"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
type Utils struct {
|
||||
}
|
||||
|
||||
type ExecMode string
|
||||
|
||||
const (
|
||||
ModeOS ExecMode = "os.stderr|stdout"
|
||||
ModeStderrOS ExecMode = "os.stderr"
|
||||
ModeCapture ExecMode = "capture.stderr|stdout"
|
||||
)
|
||||
|
||||
func (*Utils) execCommand(ctx context.Context, mode ExecMode, command string) (string, error) {
|
||||
var stdoutBuf, stderrBuf bytes.Buffer
|
||||
c := exec.CommandContext(ctx, "/bin/sh", "-c", command)
|
||||
|
||||
if mode == ModeStderrOS {
|
||||
c.Stderr = io.MultiWriter(os.Stderr, &stderrBuf)
|
||||
}
|
||||
if mode == ModeOS {
|
||||
c.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf)
|
||||
c.Stderr = io.MultiWriter(os.Stderr, &stderrBuf)
|
||||
}
|
||||
|
||||
if mode == ModeStderrOS || mode == ModeOS {
|
||||
if err := c.Run(); err != nil {
|
||||
return "", err
|
||||
} else {
|
||||
return "", nil
|
||||
}
|
||||
}
|
||||
|
||||
if mode == ModeCapture {
|
||||
c.Stdout = &stdoutBuf
|
||||
c.Stderr = &stderrBuf
|
||||
if err := c.Run(); err != nil {
|
||||
return stderrBuf.String(), err
|
||||
} else {
|
||||
return stdoutBuf.String(), nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (*Utils) execTemplate(obj interface{}, tmpl, filename string) error {
|
||||
t, err := template.New("tmpl").Parse(tmpl)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var data bytes.Buffer
|
||||
writer := bufio.NewWriter(&data)
|
||||
if err := t.Execute(writer, obj); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := writer.Flush(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
file, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
_, err = io.WriteString(file, data.String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return file.Sync()
|
||||
}
|
||||
|
||||
func (*Utils) kubeClient(config string) (client.Client, error) {
|
||||
cfg, err := clientcmd.BuildConfigFromFlags("", config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Kubernetes client initialization failed: %w", err)
|
||||
}
|
||||
|
||||
scheme := runtime.NewScheme()
|
||||
_ = corev1.AddToScheme(scheme)
|
||||
_ = sourcev1.AddToScheme(scheme)
|
||||
_ = kustomizev1.AddToScheme(scheme)
|
||||
|
||||
kubeClient, err := client.New(cfg, client.Options{
|
||||
Scheme: scheme,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Kubernetes client initialization failed: %w", err)
|
||||
}
|
||||
|
||||
return kubeClient, nil
|
||||
}
|
||||
|
||||
func (*Utils) writeFile(content, filename string) error {
|
||||
file, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
_, err = io.WriteString(file, content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return file.Sync()
|
||||
}
|
||||
BIN
docs/_files/cluster-dashboard.png
Normal file
BIN
docs/_files/cluster-dashboard.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 232 KiB |
BIN
docs/_files/cp-dashboard-p1.png
Normal file
BIN
docs/_files/cp-dashboard-p1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 144 KiB |
BIN
docs/_files/cp-dashboard-p2.png
Normal file
BIN
docs/_files/cp-dashboard-p2.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 146 KiB |
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user