【问题标题】:Ansible - when conditionAnsible - 当条件
【发布时间】:2021-12-16 20:05:52
【问题描述】:

我对 ansible 非常陌生。我在条件需要帮助。

请帮助纠正以下剧本。在哪里接受输入并在 url 中显示输出。

    - hosts: all
      gather_facts: False
      vars_prompt:
      - name: "region"
        prompt: "Which region"
      tasks:
      - name: url_name
        set_fact:
          - url: "google.com"
            when: {{ region }} == "IN"
          - url: "facebook.com"
            when: {{ region }} == "UK"
          - url: "stackoverflow"
            when: {{ region }} == "US"
          - url: "LinkedIn"
            when: {{ region }} == "AZ"
      - debug:
          msg: url

【问题讨论】:

  • 您好,欢迎来到这里。有一些明显的缩进和语法问题。请熟悉conditionals,以及相应模块的文档。
  • 整个任务只能使用when (-> set_fact)。 \ 因此,您的 sn-p 将不起作用。 @Frenchy 展示了一个很好的解决方案如何处理您的案件。

标签: ansible ansible-2.x ansible-template


【解决方案1】:

我建议您创建一个字典并将区域用作索引,而不是全部输入:

- hosts: localhost
  gather_facts: False
  vars:
    regions:
      IN: google.com
      US: stackoverflow        
      AZ: LinkedIn        
      UK: facebook.com 
                  
  vars_prompt:
  - name: "region"
        prompt: "Which region in {{ regions.keys() }}"
        private: no  #to hide the answer typed set yes   
  tasks:
    - debug:
        msg: "{{regions}}" 

    - name: url_name
      set_fact:
        url: "{{ regions[region] }}"

    - debug:
        var: url

一些有趣的修复: 如果您添加过滤器上限,您可以接受较低或较高的答案:

  set_fact:
    url: "{{ regions[region|upper] }}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多