如果 Ansible 中另一个变量设置为 true,如何使一个变量成为必需的?

问题描述 投票:0回答:1

我试图在角色中指定参数规格,以便当变量

manage_pubkey == true
时,变量
pubkey
设置为非空字符串。 我在
官方文档
中找到了属性required_if,但不太明白它如何适合简单的
argument_spec.yml
。它是用来代替
required
吗?

下面的示例似乎是错误的,因为当

manage_pubkey == true
并且没有给出 pubkey 时它不会失败。

Ansible 版本:9

---
argument_specs:
  main:
    short_description: A role to manage stuff
    options:
      manage_key:
        type: "bool"
        required: true
        description: "bla bla"
      pubkey:
        type: "str"
        required_if: ('manage_key', true, ('add_pubkey'), False)
        description: SSH public key
ansible
1个回答
0
投票

您不能将

required_id
与顶级变量一起使用,但可以在子字典中使用,例如:

---
argument_specs:
  main:
    short_description: "Make drinks"
    options:
      make:
        type: dict
        required_if:
          - [type, coffee, [coffee_type]]
          - [type, chocolate, [chocolate_type]]
          - [type, tea, [tea_type]]
        options:
          type:
            choices:
            - coffee
            - tea
            - chocolate
          coffee_type:
            choices:
              - arabica
              - moka
              - robusta
          chocolate_type:
            choices:
              - dark
              - milk
              - white
              - ruby
          tea_type:
            choices:
              - black
              - green
              - herbal
              - white
              - oolong
              - rooibos

如果我不指定

tea_type
if
type: tea
:

则会出现错误
TASK [coffee : Validating arguments against arg spec 'main' - Make coffee] ***********************************************************************************************
fatal: [localhost]: FAILED! => changed=false 
  argument_errors:
  - 'type is tea but all of the following are missing: tea_type found in make'
  argument_spec_data:
    make:
      options:
        chocolate_type:
          choices:
          - dark
          - milk
          - white
          - ruby
        coffee_type:
          choices:
          - arabica
          - moka
          - robusta
        tea_type:
          choices:
          - black
          - green
          - herbal
          - white
          - oolong
          - rooibos
        type:
          choices:
          - coffee
          - tea
          - chocolate
      required_if:
      - - type
        - coffee
        - - coffee_type
      - - type
        - chocolate
        - - chocolate_type
      - - type
        - tea
        - - tea_type
      type: dict
  msg: |-
    Validation of arguments failed:
    type is tea but all of the following are missing: tea_type found in make
  validate_args_context:
    argument_spec_name: main
    name: coffee
    path: ./roles/coffee
    type: role
© www.soinside.com 2019 - 2024. All rights reserved.