使用复杂参数形式将自由形式的命令传递给 Ansible

Cha*_*ffy 9 ansible

我正在使用以编程方式生成的 Ansible 剧本。一般来说,因为 playbook 只是 YAML,所以这很简单。但是,当使用“简单”key=value形式时,剧本不是纯粹的shlexYAML——它们包含嵌入可解析形式的内容。

为了避免这种形式的歧义(该key=value配对是命令的参数还是 ansible 的参数?),并且只有一种格式可以解析和生成,我无条件地使用ansible 中示例演示的复杂 args 机制-示例存储库

这使用以下类型的语法:

action: module-name
args:
  key1: value1
  key2: value2
Run Code Online (Sandbox Code Playgroud)

......这很好。但是,当尝试将这种形式用于shellorcommand模块(其文档将实际命令描述为在名为 的参数中传递free_form)时,这不能很好地工作:

action: shell
args:
  free_form: echo hello_world >/tmp/something
  creates: /tmp/something
Run Code Online (Sandbox Code Playgroud)

调用时,它运行以下内容:

/bin/sh -c " free_form='echo hello_world >/tmp/something'  "
Run Code Online (Sandbox Code Playgroud)

......这不是我想要完成的。

使用纯 YAML 语法使用采用“自由格式”命令的 Ansible 模块的正确方法是什么?

Sno*_*all 5

简短的回答:不使用commandrawscript,或shell模块。编写您自己的模块,该模块接受该命令作为“正常”参数。

长答案:

在大多数情况下,您可以这样做:

- shell: echo hello_world > /tmp/something
  args:
    creates: /tmp/something
Run Code Online (Sandbox Code Playgroud)

但是,这在某些边缘情况下会失败:

- shell: echo hello_world > creates=something
  args:
    creates: creates=something  # The file is named "creates=something"
Run Code Online (Sandbox Code Playgroud)

我不知道处理此问题的一般方法,但特定于 bash 的解决方案是:

- shell: echo hello_world > "creates=something"
  args:
    creates: creates=something
Run Code Online (Sandbox Code Playgroud)