Dav*_*ick 5 dictionary ansible
我想从Ansible的字典中删除一个密钥.
例如,我想这样:
- debug: var=dict2
vars:
dict:
a: 1
b: 2
c: 3
dict2: "{{ dict | filter_to_remove_key('a') }}"
Run Code Online (Sandbox Code Playgroud)
要打印这个:
ok: [localhost] => {
"dict2": {
"b": 2,
"c": 3
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,字典是从json文件加载的,我将它发布到Grafana REST API.我想允许在文件中保存"id"键并在POST之前删除密钥.
这更接近我删除的实际用途:
- name: Install Dashboards
uri:
url: "{{ grafana_api_url }}/dashboards/db"
method: POST
headers:
Authorization: Bearer {{ grafana_api_token }}
body:
overwrite: true
dashboard:
"{{ lookup('file', item) | from_json | removekey('id') }}"
body_format: json with_fileglob:
- "dashboards/*.json"
- "../../../dashboards/*.json"
Run Code Online (Sandbox Code Playgroud)
- set_fact:
dict:
a: 1
b: 2
c: 3
- debug:
var: dict
- debug:
msg: "{{ dict | combine({ 'a': omit }) }}"
Run Code Online (Sandbox Code Playgroud)
TASK [test : set_fact]
ok: [server]
TASK [test: debug]
ok: [server] => {
"dict": {
"a": 1,
"b": 2,
"c": 3
}
}
TASK [test : debug]
ok: [server] => {
"msg": {
"b": 2,
"c": 3
}
}
Run Code Online (Sandbox Code Playgroud)
- set_fact:
dict:
a: 1
b: 2
c: 3
dict2: {}
- set_fact:
dict2: "{{dict2 |combine({item.key: item.value})}}"
when: "{{item.key not in ['a']}}"
with_dict: "{{dict}}"
- debug: var=dict2
Run Code Online (Sandbox Code Playgroud)
或者创建一个过滤插件并使用它.
小智 6
- debug: var=dict2
vars:
dict:
a: 1
b: 2
c: 3
dict2: '{{ dict | dict2items | rejectattr("key", "eq", "a") | list | items2dict }}'
#dict2: '{{ dict | dict2items | rejectattr("key", "match", "^(a|b)$") | list | items2dict }}'
Run Code Online (Sandbox Code Playgroud)
输出:
ok: [localhost] => {
"dict2": {
"b": 2,
"c": 3
}
}
Run Code Online (Sandbox Code Playgroud)
这是一种受 John Mazzitelli 的文章启发的方法,可以内联使用set_fact,无需执行其他任务等:
tasks:
- debug: var=dict2
vars:
dict:
a: 1
b: 2
c: 3
# It is important that there be NO WHITESPACE outside of `{% ... %}` and `{{ ... }}`
# or else the var will be converted to a string. The copy() step optionally prevents
# modifying the original. If you don't care, then: "{% set removed=dict.pop('a') %}{{dict}}"
dict2: "{% set copy=dict.copy() %}{% set removed=copy.pop('a') %}{{ copy }}"
Run Code Online (Sandbox Code Playgroud)
TASK [debug] ***********
ok: [localhost] => {
"dict2": {
"b": 2,
"c": 3
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5737 次 |
| 最近记录: |