我有一个kubernetes秘密以secret的形式显示。J2文件,该文件具有密码密钥。假定这个密码密钥的值来自dev.yml文件中存在的可靠库加密字符串。dev.yml如下所示:-
dev_db_password: !vault |
$ANSIBLE_VAULT;1.1;AES256
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
我正在通过"dev"作为运行时参数"namespace=dev"我的剧本。secret的stringData。J2是这样的:-
stringData:
consoleadminpassword: "{{'{{'}} {{ namespace + '_console_password' }} {{'}}'}}"
consolenonadminpassword: "{{'{{'}} {{ namespace + '_console_password' }} {{'}}'}}"
dbpassword: "{{'{{'}} {{ namespace + '_console_password' }} {{'}}'}}"
当我模板的秘密。J2要保密。, stringData的输出结果如下所示:-
stringData:
consoleadminpassword: "{{ dev_console_password }}"
consolenonadminpassword: "{{ dev_console_password }}"
dbpassword: "{{ dev_db_password }}"
现在我想让它进一步计算"dev_db_password"设置"dbpassword";当可见模板为秘密时,从dev.yml解密值的密钥。J2到secret.yml。是否有一种方法可以通过修改dbpassword: "{{'{{'}} {{ namespace + '_db_password' }} {{'}}'}}"
在同一行中实现这一点?
Q:">求dev_db_password…而可见模板secret.j2。是否有一种方法可以通过修改dbpassword:…?,
:是的。有。试试lookuppluginvars。参见ansible-doc -t lookup vars
dbpassword: "{{'{{'}} {{ lookup('vars', namespace + '_db_password') }} {{'}}'}}"
例如,模板
shell> cat secret.j2
stringData:
consoleadminpassword: "{{'{{'}} {{ lookup('vars', namespace + '_console_password') }} {{'}}'}}"
consolenonadminpassword: "{{'{{'}} {{ lookup('vars', namespace + '_console_password') }} {{'}}'}}"
dbpassword: "{{'{{'}} {{ lookup('vars', namespace + '_db_password') }} {{'}}'}}"
和剧本
- hosts: localhost
tasks:
- template:
src: secret.j2
dest: secret.yml
vars:
namespace: dev
dev_console_password: passwd_console
dev_db_password: passwd_db
为
shell> cat secret.yml
stringData:
consoleadminpassword: "{{ passwd_console }}"
consolenonadminpassword: "{{ passwd_console }}"
dbpassword: "{{ passwd_db }}"
如果您不需要字典中变量(密码)的下一次求值,请使用下面的模板
shell> cat secret.j2
stringData:
consoleadminpassword: {{ lookup('vars', namespace + '_console_password') }}
consolenonadminpassword: {{ lookup('vars', namespace + '_console_password') }}
dbpassword: {{ lookup('vars', namespace + '_db_password') }}
会给
shell> cat secret.yml
stringData:
consoleadminpassword: passwd_console
consolenonadminpassword: passwd_console
dbpassword: passwd_db
如果您将密码放入加密文件
shell> cat dev.yml
dev_console_password: passwd_console
dev_db_password: passwd_db
shell> ansible-vault encrypt dev.yml
Encryption successful
shell> cat dev.yml
$ANSIBLE_VAULT;1.1;AES256
30663636653963333864346339303034356463356234383035363561356365376130396465323736
...
剧本将给出相同的结果
- hosts: localhost
vars:
namespace: dev
tasks:
- include_vars: "{{ namespace }}.yml"
- template:
src: secret.j2
dest: secret.yml