Ansible playbook传递参数时出错

74次阅读
没有评论

问题描述

正在尝试创建一个playbook,在本地主机上执行一个带有两个参数(name和password)的python3脚本。然而,当他尝试使用以下命令执行playbook时,出现了错误消息:

ansible -b --become-user=ras createdeploy.yaml --extra-vars "user=ras pass=ras"

错误消息如下:

[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'ERROR! Invalid variable name in vars specified for Play: 'pass' is not a valid variable nameThe error appears to have been in '/home/ras/createdeploy.yaml': line 3, column 5, but maybe elsewhere in the file depending on the exact syntax problem.The offending line appears to be:  vars:    user: "{{ user }}"    ^ hereWe could be wrong, but this one looks like it might be an issue withmissing quotes.  Always quote template expression brackets when theystart a value. For instance:    with_items:      - {{ foo }}Should be written as:    with_items:      - "{{ foo }}"

以下是.yaml文件的内容:

- hosts: all
  vars:
    user: "{{ user }}"
    pass: "{{ pass }}"
  tasks:
    - name: Stop services
      shell: "bash stopservices.sh"
    - name: Edit real hosts file
      shell: "bash editrealmachinehosts.sh"
    - name: Create dirs and cloning
      command: python3 user pass

解决方案

请注意以下操作注意版本差异及修改前做好备份。

方案1

我建议您首先在playbook中设置一些默认值(如果您明确希望在那里使用变量,以减少交互/命令行参数)。例如:

- hosts: all
  vars:
    user: greatuser
    passa: greatpassword

其次,我相信pass是某个地方的保留字,尽管我在文档中找不到它。这就是为什么我将您的变量更改为passa的原因。最终版本的playbook应该如下所示:

- hosts: all
  vars:
    user: greatuser
    passa: greatpassword
  tasks:
    - name: Stop services
      shell: "bash stopservices.sh"
    - name: Edit real hosts file
      shell: "bash editrealmachinehosts.sh"
    - name: Create dirs and cloning
      command: python3 {{ user }} {{ passa }}

请注意,在第三个任务中引用用户名和密码变量的方式 – 使用{{ variable }}而不是variable
使用以下命令执行playbook:

ansible-playbook createdeploy.yaml --extra-vars "user=ras passa=ras" -b --become-user=ras

由于您的目标主机实际上是localhost(如果我理解您的意思正确),并且您没有显示您的清单文件,我建议您可能需要将-c local添加到ansible-playbook命令的参数列表中。

方案2

pass是Python中的保留字。
另一种方法是将pass更改为其他名称,以避免与Python中的保留字冲突。例如,将其更改为passa

- hosts: all
  vars:
    user: "{{ user }}"
    passa: "{{ pass }}"
  tasks:
    - name: Stop services
      shell: "bash stopservices.sh"
    - name: Edit real hosts file
      shell: "bash editrealmachinehosts.sh"
    - name: Create dirs and cloning
      command: python3 {{ user }} {{ passa }}

请注意,这里的变量引用方式与方案1中的相同。
执行playbook的命令如下:

ansible-playbook createdeploy.yaml --extra-vars "user=ras passa=ras" -b --become-user=ras

请根据您的实际情况选择适合您的解决方案。

正文完