我正在使用Ansible来读取配置,该配置可以是JSON或YAML,并从文件中的某些节点中提取值。
我知道我可以使用from_json
或from_yaml
在Ansible中处理它,但由于我不知道配置将采用哪种格式,因此我无法使其正常工作。< / p>
该文件是Kubernetes的Kubeconfig。以下示例:
在YAML
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: REDACTED
server: https://my-k8s-cluster.com
name: k8s-clstr-master
contexts:
- context:
cluster: k8s-clstr-master
namespace: kube-system
user: k8s-clstr-master-admin
name: k8s-clstr-master
current-context: k8s-clstr-master
kind: Config
preferences: {}
users:
- name: k8s-clstr-master-admin
user:
client-certificate-data: REDACTED
client-key-data: REDACTED
在JSON中
{
"kind": "Config",
"apiVersion": "v1",
"preferences": {},
"clusters": [
{
"name": "k8s-clstr-master",
"cluster": {
"server": "https://my-k8s-cluster.com",
"certificate-authority-data": "REDACTED"
}
}
],
"users": [
{
"name": "k8s-clstr-master-admin",
"user": {
"client-certificate-data": "REDACTED",
"client-key-data": "REDACTED"
}
}
],
"contexts": [
{
"name": "k8s-clstr-master",
"context": {
"cluster": "k8s-clstr-master",
"user": "k8s-clstr-master-admin",
"namespace": "kube-system"
}
}
],
"current-context": "k8s-clstr-master"
}
我正在使用Ansible:
vars:
kubeconfig: "{{ lookup('hashivault', '/kubeconfig/admin', 'config') }}"
tasks:
- name: Find cluster server name
shell: "echo {{ kubeconfig.clusters[0].cluster.server }}"
如果以JSON格式检索kubeconfig
,则我或许可以使用|from yaml
创建一个任务,然后添加ignore_errors: true
,但这感觉不是正确的做法。
对于我如何解决这个问题,任何人都有任何提示吗?
答案 0 :(得分:2)
Jinja2中有一些built-in tests。
如果你在{{...}}
表达式中有JSON字符串,Ansible模板工作的方式,它会自动转换为对象。因此,如果您从保险库中获取JSON,kubeconfig
将成为对象,否则它将成为字符串。
这是给你的食谱:
vars:
kubeconfig_raw: "{{ lookup('hashivault', '/kubeconfig/admin', 'config') }}"
kubeconfig: "{{ kubeconfig_raw if kubeconfig_raw is mapping else kubeconfig_raw | from_yaml }}"
tasks:
- name: Find cluster server name
shell: "echo {{ kubeconfig.clusters[0].cluster.server }}"
答案 1 :(得分:1)
如果您使用include_vars
任务,则提供的格式无关紧要。该任务接受两者。
---
- hosts: localhost
connection: local
tasks:
- include_vars:
file: config
name: kubeconfig
- debug: var=kubeconfig