使用已定义的参数规范验证传递给 ansible-playbook 的参数

Validates arguments passed to ansible-playbook with a defined argument specification

我们想要 运行 以下剧本与 yml 文件 - ansible-playbook install_os.yml

playbook install_os.yml 运行良好,但现在我们要添加参数验证 <machine name>,<machine IP>

如下:

ansible-playbook install_os.yml --limit RHEL01,73.22.3.44

从我的观点来看,两个参数都应该被识别为字符串(不验证有效 I​​P)并且在 <machine name><machine IP> 之间,我们应该设置 , 分隔符

那么,是否可以验证字符串?如果其中一个或两个未定义则退出?

您可以在特殊变量 ansible_limit 的帮助下访问 ansible-playbook 的参数中指定的限制。

从那时起,您可以 assert 根据您的业务需求选择 --limit 值。

例如:

- hosts: all
  gather_facts: no

  tasks:
    - assert: 
        that: 
          ## We have exactly one comma, separating two hosts
          - ansible_limit | split(',') | length == 2
          ## We have a string before the comma
          - (ansible_limit | split(',')).0 is string
          ## We have a non-empty string before the comma
          - (ansible_limit | split(',')).0 | length > 0
          ## We have a string after the comma
          - (ansible_limit | split(',')).1 is string
          ## We have a non-empty string after the comma
          - (ansible_limit | split(',')).1 | length > 0
          ## 'all', which has a wildcard meaning, 
          ## is not one of the two hosts separated by the comma
          - "'all' not in ansible_limit | split(',')"
          ## We do not have any character having a special meaning in the limit
          ## see: https://docs.ansible.com/ansible/latest/user_guide/intro_patterns.html#common-patterns
          - "'@' not in ansible_limit"
          - "':' not in ansible_limit"
          - "'!' not in ansible_limit"
          - "'&' not in ansible_limit"
          - "'*' not in ansible_limit"
      run_once: true

这可能会将其限制为您想要的用例。
这就是说,请注意 --limit is an existing flag with its own behaviour, so, based on what you are aiming for, you could also be better with an extra parameter passed in command line.