gpt4 book ai didi

ansible - 如何在 Ansible 中创建默认值 'null'

转载 作者:行者123 更新时间:2023-12-02 16:58:18 27 4
gpt4 key购买 nike

我希望“lucy”遵循用户模块创建者的默认行为,即创建并使用与用户名“lucy”匹配的组。然而,对于“弗兰克”,我希望主要群体是现有的群体; gid 1003。所以我的哈希看起来像这样:

lucy:
comment: dog
frank:
comment: cat
group: 1003

我的任务如下所示:

- name: Set up local unix user accounts
user:
name: "{{ item.key }}"
comment: "{{ item.value.comment }}"
group: "{{ item.value.group | default(undef) }}"
loop: "{{ users|dict2items }}"

这不起作用,因为 undef 未被识别。我也想不到别的什么了。 'null'、'None' 等都失败。 '' 创建一个空字符串,这也是不正确的。我不知道该怎么做。有什么想法吗?

最佳答案

default(omit)就是您正在寻找的。例如,

- name: Set up local Unix user accounts
user:
name: "{{ item.key }}"
comment: "{{ item.value.comment }}"
group: "{{ item.value.group | default(omit) }}"
loop: "{{ users|dict2items }}"
<小时/>

评论

Comment by Lucas Basquerotto: "... omit only works correctly when used directly in a module, it won't work in a set_fact ..."

答:你错了。例如,default(omit)set_fact 和模块中都有效。列表中的第一项默认为 false,结果为 “VARIABLE IS NOT DEFINED!”。第二项默认为省略。省略参数get_checksum默认为 true,结果中包含校验和

shell> cat pb.yml
- hosts: localhost
tasks:
- set_fact:
test:
- "{{ gchk|default(false) }}"
- "{{ gchk|default(omit) }}"
- stat:
path: /etc/passwd
get_checksum: "{{ item }}"
loop: "{{ test }}"
register: result
- debug:
var: item.stat.checksum
loop: "{{ result.results }}"

给出

shell> ansible-playbook pb.yml | grep item.stat.checksum
item.stat.checksum: VARIABLE IS NOT DEFINED!
item.stat.checksum: 7c73e9f589ca1f0a1372aa4cd6944feec459c4a8

除此之外,default(omit) 在某些表达式中也能按预期工作。例如

    - debug:
msg: "{{ {'a': item}|combine({'b': true}) }}"
loop: "{{ test }}"

给出

  msg:
a: false
b: true

msg:
b: true

查看没有默认值的结果

shell> ansible-playbook pb.yml -e "gchk={{ true|bool }}"
<小时/>

It does not work when passing vars to a module (a template in my case ...). When using omit, the template gets the value of the placeholder instead.

答:当然,在这个用例中它不起作用。例如,

shell> cat pb.yml
- hosts: localhost
tasks:
- debug:
msg: |
{{ var1 }}
{{ var2 }}
vars:
var1: "{{ foo }}"
var2: "{{ bar|default(omit) }}"

给出

shell> ansible-playbook pb.yml -e foo=123
...
msg: |-
123
__omit_place_holder__73431d735cecaedbd9c4386e2ebc77ded8eaee51

目标是省略模块中的参数。问题说:我能想到。 'null'、'None' 等都失败。 '' 创建一个空字符串,这也是不正确的。我不知道该怎么做。有什么想法吗? 这不是您的用例。也许标题有误导性?如果您想使用 null,请将默认值设置为 None。也许,这会达到你想要的效果。

      vars:
var1: "{{ foo }}"
var2: "{{ bar|default(None) }}"

关于ansible - 如何在 Ansible 中创建默认值 'null',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54030680/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com