【问题标题】:How to concatenate string in YAML?如何在 YAML 中连接字符串?
【发布时间】:2014-03-12 11:00:50
【问题描述】:

我正在编写一个剧本,我需要在其中执行 mysql 查询并通过 以 json 格式输出。剧本代码工作正常,只是我想在字符串concatenate 部分中遇到错误。如果我传递示例 json 字符串,它工作正常。

- name: Execute php script with json parameter
  command:  php -f /path/to/php/test.php "{'colors':{'red','blue','yellow'}}"
  register: php_output

output.stdout_lines 是我的剧本中已经设置的变量,其中包含{'red','blue','yellow'} 格式的输出。

- name: Execute php script with json parameter
  command:  php -f /path/to/php/test.php '{"stdout_lines": {{output.stdout_lines}} }'
  register: php_output

那么如何在 '{"stdout_lines": {{output.stdout_lines}} }' 中连接 output.stdout_lines 变量?任何建议

【问题讨论】:

  • 当你在 Ansible 任务上传递一个数组时,它将为数组上的每个条目执行一次。它不会像您假设的那样在执行期间连接值。看看docs.ansible.com/playbooks_loops.html

标签: yaml ansible ansible-playbook


【解决方案1】:

stdout_lines 是为了方便而创建的。过去我们只有stdout。我认为这就是你想要的:

command:  php -f /path/to/php/test.php '{"stdout_lines": {{output.stdout}} }'

如果你想真正连接自己,说因为你有自己的字符串列表,那么你可以使用 Jinja2 内置过滤器join

- hosts: localhost
  gather_facts: False
  tags: so9
  vars:
    - str_list: ['Hello', 'world', '!', ]
  tasks:
    - debug: msg="orig list={{ str_list }}"
    - debug: msg="concated = {{ str_list | join(' ') }}"
    - set_fact: concated_str="{{ str_list | join(' ') }}"
    - debug: msg="assigned to a variable concated_str = {{ concated_str }}"

【讨论】:

    【解决方案2】:

    这样就可以了

      - name: Generate JSON output based on template
        template: src=colors.json.j2 dest=/tmp/colors.json
        with_items: colors
    

    它会生成一个类似

    的文件
    {'colors':
        {
            'blue',
            'red',
            'green',
            }
    }
    

    【讨论】:

      【解决方案3】:

      像这样试试。

        vars:
      - img_path: "/var/lib/libvirt/images/{{ instance_name }}-disk2.img"
      

      实例名称是另一个变量

      【讨论】:

        【解决方案4】:

        to_json 过滤器是您想要的。

        Ansible 不将变量存储为 JSON 字符串,而是将它们存储为 Python 对象。当你调试时,例如使用-vvv,Ansible 将这些 Python 对象显示为 JSON 字符串,但这是为了您的方便。

        生成所需的命令:

        - name: Execute php script with json parameter
          vars:
            # define my desired object
            my_object:
              colors: "{{ output.stdout_lines }}"
            # my_object contains a dict with a single key 
            #  "colors" who's value is the list contained 
            #  in output.stdoutlines
          command: "php -f /path/to/php/test.php {{ my_object | to_json | quote }}"
          register: php_output
        

        to_json 获取存储在my_object 中的对象并输出一个 JSON 字符串。

        quote 自动处理 JSON 字符串可能需要的任何 shell 引用。例如如果我的 JSON 字符串包含双引号,quote 会将整个 JSON 字符串包含在单引号中。

        【讨论】:

          猜你喜欢
          • 2011-07-25
          • 2014-07-28
          • 1970-01-01
          • 1970-01-01
          • 2016-07-08
          • 2012-09-24
          • 2011-09-11
          • 2014-07-24
          • 2016-11-07
          相关资源
          最近更新 更多