如何从Argo CD ApplicationSet PR Generator向Kustomize注入环境变量
解决Argo ApplicationSet传递PR变量到Kustomize ConfigMap的方法
下面提供两种可行的方案,直接解决你把PR编号和提交哈希注入ConfigMap的需求:
方案一:直接用Kustomize Patch替换ConfigMap参数
这种方式不需要依赖.env文件,直接通过ApplicationSet的参数替换修改Kustomize的配置:
- 调整你的
kustomization.yaml,改用literals定义ConfigMap的键值对(先写占位符):
# kustomization.yaml configMapGenerator: - name: example-configmap-1 literals: - PULL_REQUEST_NUMBER=PLACEHOLDER_PR - GIT_SHA=PLACEHOLDER_SHA
- 修改ApplicationSet配置,通过Kustomize Patch替换占位符为实际的PR变量:
apiVersion: argoproj.io/v1alpha1 kind: ApplicationSet metadata: name: pr-app-set spec: generators: - pullRequest: github: owner: 你的组织名 repo: 你的仓库名 tokenRef: secretName: github-token # 提前创建包含GitHub token的Secret key: token template: metadata: name: "pr-{{number}}-app" spec: project: default source: repoURL: https://github.com/你的组织名/你的仓库名.git targetRevision: "{{head_sha}}" # 直接用PR的提交哈希作为代码版本 path: ./你的Kustomize配置目录路径 kustomize: patches: - target: kind: ConfigMapGenerator name: example-configmap-1 patch: |- - op: replace path: /literals/0 value: "PULL_REQUEST_NUMBER={{number}}" - op: replace path: /literals/1 value: "GIT_SHA={{head_sha}}" destination: server: https://kubernetes.default.svc namespace: "pr-{{number}}" # 每个PR用独立Namespace,避免资源冲突
方案二:通过模板生成.env文件(保留你的原有Kustomize配置)
如果你想继续用.env文件的方式,可以通过模板文件让ApplicationSet自动填充变量:
- 在代码仓库中创建
.env.tpl模板文件:
PULL_REQUEST_NUMBER={{number}} GIT_SHA={{head_sha}}
- 修改ApplicationSet配置,添加
fileReplacements把模板转换成实际的.env文件:
apiVersion: argoproj.io/v1alpha1 kind: ApplicationSet metadata: name: pr-app-set spec: generators: - pullRequest: github: owner: 你的组织名 repo: 你的仓库名 tokenRef: secretName: github-token key: token template: metadata: name: "pr-{{number}}-app" spec: project: default source: repoURL: https://github.com/你的组织名/你的仓库名.git targetRevision: "{{head_sha}}" path: ./你的Kustomize配置目录路径 fileReplacements: - sourcePath: .env.tpl targetPath: .env # 将模板文件替换为填充了变量的.env destination: server: https://kubernetes.default.svc namespace: "pr-{{number}}"
你的原有kustomization.yaml和.env的配置可以保留,Kustomize会自动读取生成好的.env文件,把变量注入ConfigMap。
注意事项
{{number}}和{{head_sha}}是Pull Request Generator内置的变量,无需额外配置即可直接使用。- 确保GitHub token拥有读取PR的权限,Secret配置正确。
- 使用独立Namespace部署每个PR的应用,能避免不同PR之间的资源冲突。
内容的提问来源于stack exchange,提问作者Adrian I
相关产品推荐
相关产品推荐

