简体   繁体   English

在 shell 脚本中使用多行变量进行 Ansible

[英]Ansible with multiline variables in shell script

This might seems weird, But I'm trying to create 2 shell scripts, one with variables which I can source, and another, with a function to run.这可能看起来很奇怪,但我正在尝试创建 2 个 shell 脚本,一个带有我可以获取的变量,另一个带有要运行的函数。

core.vars核心变量

#/bin/bash
# list of playbooks to source

# Core db initialization playbooks

core_db_init_play_books=$(cat <<EOL
../ansible/test.yaml -e "val1=hi val2=by"
../ansible/provision.yml --skip-tags "postgresql-slave,log-es"
../ansible/postgresql-data-update.yml
../ansible/es-mapping.yml --extra-vars "indices_name=all ansible_tag=run_all_index_and_mapping"
../ansible/cassandra-deploy.yml -e "cassandra_jar_path=$ansible_path/ansible cassandra_deploy_path=/home/{{ansible_ssh_user}}" -v
EOL
)

install_script.sh安装脚本.sh

#!/bin/bash

## Ansible Runner
function ansible_runner() {
    playbooks=$1
    local IFS=$'\n' # seperate playbooks by newline
    for playbook in ${playbooks}; do
        ansible-playbook -i ../ansible/inventory/env ${playbook}
    done
}
source core.vars
ansible_runner core_db_init_play_books

But when you execute the install script, ansible will complain for files with extra-args但是当你执行安装脚本时,ansible 会抱怨带有 extra-args 的文件

playbook not found ../ansible/provision.yml --skip-tags "postgresql-slave,log-es"

Think, it has something to do with the way I pass the file.想想,这和我传递文件的方式有关。 Couldn't figure it out though.却想不通。 Great minds please ... :)伟大的头脑请... :)

Would you try the following:你会尝试以下方法吗:

install_script.sh安装脚本.sh

#!/bin/bash

## Ansible Runner
ansible_runner() {
    while IFS= read -r line; do
        declare -a playbook="($line)"   # split $line into tokens
        ansible-playbook -i ../ansible/inventory/env "${playbook[@]}"
    done <<< "$1"
}
source core.vars
ansible_runner "$core_db_init_play_books"

Now the option lines are properly split into an array of tokens with the declare statement.现在选项行被正确地拆分为带有declare语句的标记数组。

The problem is with IFS .问题出在IFS You need the spaces when you don't want ../ansible/provision.yml --skip-tags "postgresql-slave,log-es" to be one long filename.当您不希望../ansible/provision.yml --skip-tags "postgresql-slave,log-es"成为一个长文件名时,您需要空格。
Processing the variable by line and having spaces becomes hard with a for-loop .使用for-loop逐行处理变量并for-loop空格变得困难。
Try this:尝试这个:

function ansible_runner() {
    while IFS= read -r playbook; do
        echo ansible-playbook -i ../ansible/inventory/env ${playbook}
    done <<< "$1"
}
ansible_runner "${core_db_init_play_books}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM