如何基于jenkins上的用户输入在ansible中设置变量值

时间:2018-08-13 13:28:35

标签: jenkins ansible

这是我的确切要求。

在詹金斯地区:

用户将选择环境参数:测试 DEV

在可播放的剧本中: 我需要根据所选的ENV类型运行sed命令。

- vars:
   environ1: "TEST"
   environ2: "PROD"

- command: sed -i "s/test.abc.com/"{{SITE_URL}}"/g" /home/ubuntu/mysql.sql
    when: '{{backup_from}}' == '{{environ1}}'

- command: sed -i "s/abc.com/"{{SITE_URL}}"/g" /home/ubuntu/mysql.sql
    when: '{{backup_from}}' == '{{environ2}}'

错误:

[0;31m     when: '{{backup_from}}' == '{{environ}}'[0m
[0;31m                             ^ here[0m
[0;31mWe could be wrong, but this one looks like it might be an issue with[0m
[0;31mmissing quotes.  Always quote template expression brackets when they[0m
[0;31mstart a value. For instance:[0m
[0;31m[0m
[0;31m    with_items:[0m
[0;31m      - {{ foo }}[0m
[0;31m[0m
[0;31mShould be written as:[0m
[0;31m[0m
[0;31m    with_items:[0m
[0;31m      - "{{ foo }}"[0m
[0;31m[0m
Connection to 18.221.160.190 closed.
Build step 'Execute shell' marked build as failure
Finished: FAILURE

2 个答案:

答案 0 :(得分:0)

引号和缩进有多个问题:

  • 如果在YAML中用引号引起一个参数,则必须将整个YAML值都用引号引起(这就是错误的原因)
  • when应该在任务缩进级别上
  • when的参数应该是Jinja2表达式,不需要在内部使用大括号(尽管它可以在警告的情况下使用)
  • 您不能在command的参数中嵌套双引号
  • 除了整个YAML值以大括号开头的情况外,无需在Jinja2表达式{​​{1}}周围使用引号
{{ ... }}

您也可以考虑将其编写为单个任务(如果可能只有两个环境值):

tasks:
  - command: sed -i "s/test.abc.com/{{SITE_URL}}/g" /home/ubuntu/mysql.sql
    when: backup_from == environ1

  - command: sed -i "s/abc.com/{{SITE_URL}}/g" /home/ubuntu/mysql.sql
    when: backup_from == environ2

答案 1 :(得分:-1)

我认为整个命令必须不带引号,请尝试:

- vars:
   environ1: "TEST"
   environ2: "PROD"

- command: sed -i "s/test.abc.com/"{{SITE_URL}}"/g" /home/ubuntu/mysql.sql
    when: backup_from == environ1

- command: sed -i "s/abc.com/"{{SITE_URL}}"/g" /home/ubuntu/mysql.sql
    when: backup_from == environ2