【问题标题】:Ansible: Change script value (.sh file) via yml playbookAnsible:通过 yml 剧本更改脚本值(.sh 文件)
【发布时间】:2022-01-23 09:10:42
【问题描述】:

例如,我的剧本的相关部分如下所示:

tasks:
  - name: test
    script: ../test.sh
    ...

对于我的 test.sh,有一行代码可以像这样执行 python 脚本:

python run.py --inputvar hello

有没有办法将 .sh 文件中的 inputvar 值从“hello”更改为 playbook 中的其他值?

编辑: 感谢@seshadri_c 对此的帮助。猜猜这个问题应该被标记在 shell 脚本下。

【问题讨论】:

  • 您可以使用 script 模块直接运行 Python 脚本,正如 documentation 上的示例之一所建议的那样。必须有一个 shell 脚本吗?
  • @seshadri_c 最好是标准化。

标签: shell ansible sh


【解决方案1】:

在 shell 脚本中解析参数的最简单方法是使用位置参数 - $1、$2 等。

给定一个test.sh 脚本:

#!/bin/bash

python run.py --inputvar $1

并将其运行为:

/bin/bash test.sh arg1

将$1 的值作为--inputvar arg1 传递给run.py。

同样的事情可以从 Ansible 任务中运行:

tasks:
  - name: test
    script: ../test.sh arg1

【讨论】:

    【解决方案2】:

    还有更多选择。

    1. 第一个可能是lineinfile,例如下面的任务是幂等的
        - lineinfile:
            path: test.sh
            regex: '^python run.py --inputvar (.*)$'
            line: 'python run.py --inputvar {{ my_var|default("hello") }}'
    

    给予

    TASK [lineinfile] *******************************************************
    ok: [localhost]
    

    如果你定义了变量my_var(见Variable precedence: Where should I put a variable?)

    my_var: hello world
    

    该任务将更改文件中的行。 (运行带有选项 --check --diff 的剧本)

    TASK [lineinfile] ********************************************************
    --- before: test.sh (content)
    +++ after: test.sh (content)
    @@ -1,3 +1,3 @@
     #!/usr/bin/sh
     
    -python run.py --inputvar hello
    +python run.py --inputvar hello world
    
    changed: [localhost]
    

    下一个选项可能是template,例如模板 test.sh.j2 和下面的任务给出相同的结果

    shell> cat test.sh.j2
    #!/usr/bin/sh
    
    python run.py --inputvar {{ my_var|default("hello") }}
    
        - template:
            src: test.sh.j2
            dest: test.sh
    

    【讨论】:

      猜你喜欢
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 2014-09-16
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多