首页 > 解决方案 > 无法在 Ansible 中使用额外变量在字符串列表中传递句子

问题描述

背景:

我有一个 Ansible 实用程序,它将extra-vars从用户那里获取新评论并将它们添加到/etc/motd评论部分。这些注释首先以数组的形式存储在本地事实文件中。然后我的代码会遍历它并将每个注释写在一个新行中。但是,这仅适用于单个单词的评论,而不适用于整个句子。

输入格式:

/opt/companyname/ansible/bin/ansible-pull -U /remote/osreleases/git-repo/xxx-ansible -i "localhost," -C beta -d /u/subburat/xxx-ansible push-full.yml -f --extra-vars '{"common_motd_qsc_add_comment": ["comment3","comment4"]}' -t common_motd_qsc

主要的.yml

- name: Add a new comment if it does not exist
  set_fact:
    common_motd_qsc_comments_array: "{{ common_motd_qsc_comments_array | union([t_new_entry]) }}"
  loop: "{{ common_motd_qsc_add_comment }}"
  when:
    - t_new_entry not in common_motd_qsc_comments_array
    - t_new_entry|length > 0
  vars:
    t_new_entry: "{{ item | trim }}"

- name: Save comments to snps.fact file
  ini_file:
    dest: "/etc/ansible/facts.d/snps.fact"
    section: 'motd'  # [header]
    option: 'common_motd_qsc_comment_array'  # key
    value: "{{ common_motd_qsc_comments_array }}"  # value

- name: Create /etc/motd
  template:
    src: "{{ role_path }}/templates/motd"
    dest: "{{ common_motd_qsc_os_motd_file }}"
    owner: root
    group: root
    mode: 0644

/etc/motd运行输入命令后的文件(单字注释)。请注意,comment3 和 commen4 已添加到注释部分。

  Linux 3.10.0-1127.10.1.el7.x86_64 x86_64
  OS:        CentOS7.3
  Hostname:  host001 (xxxx)
  Location:  Cagexxx
  CPU:       16  x 2599 MHz, Intel(R) Xeon(R) (2 socket, 8 core, No HT)
  Memory:    126 GB RAM, 126 GB Swap
  QSC:       QSC-S
  Comments:
            Warning:  This machine binding LDAP instead of NIS
            comment3
            comment4
  Note: Please do NOT edit this file directly. Use ansible utility to add or delete comment(s).

当我运行相同的输入但这次尝试添加更长的评论(句子)时,它会给我一个错误。

输入(句子):

/opt/companyname/ansible/bin/ansible-pull -U /remote/osreleases/git-repo/xxx-ansible -i "localhost," -C beta -d /u/subburat/xxx-ansible push-full.yml -f --extra-vars '{"common_motd_qsc_add_comment": ["This is a long comment"]}' -t common_motd_qsc

错误:

Usage: ansible <host-pattern> [options]
ERROR! Ext
Define anraneous opd run a sitions or angle task rguments
'playbook' against a set of hosts
ERROR! the playbook: ** could not be found

这意味着句子“This is a long comment”中的第二个单词“is”正在引起麻烦。非常感谢您对此的任何帮助。谢谢!

标签: ansible

解决方案


我解决了这个问题。问题在于我输入中的引号。无需更改代码。

注意: 如果输入是一个句子(带空格),请确保注意引号。单引号 (') 中有一个双引号 (")。

/opt/companyname/ansible/bin/ansible-pull -U /remote/osreleases/git-repo/xxx-ansible -i "localhost," -C beta -d /u/subburat/xxx-ansible push-full.yml -f --extra-vars='{"common_motd_qsc_add_comment": ['"This is a long sentence with spaces"',"comment5"]}' -t common_motd_qsc

推荐阅读