gpt4 book ai didi

ansible - 在 Ansible 中,如何在一个任务中导出环境变量以便它可以被另一个任务使用?

转载 作者:行者123 更新时间:2023-12-04 03:19:55 25 4
gpt4 key购买 nike

假设我有以下文件

foo.txt
Hello world=1
Hello world=2
...
Hello world=N

我想使用 Ansible 插入另一个 Hello world 行,就像这样

foo.txt
Hello world=1
Hello world=2
...
Hello world=N
Hello world=N+1

IOW,我不知道有多少 Hello world 行,我需要通过脚本找出并获取 N 的值。

在 Ansible 中,假设我有以下 shell 任务

- name: Find the last Hello world in foo.txt, and get the value of N
shell: >
# Get last Hello world line in foo.txt. I want to export this as an
# environment variable
LAST_HW_LINE=`awk '/Hello world/ {aline=$0} END{print aline}' "foo.txt"`
# Get left side of equation
IFS='=' read -ra LS <<< "$LAST_HW_LINE"
# Get the value of N
NUM=${LS##*\.}
# Increment by 1. I want to export this as an environment variable
NUM=$((NUM+1))

我希望能够随后做到这一点

- name: Add the next Hello world line
lineinfile:
dest: foo.txt
insertafter: "{{ lookup('env', 'LAST_HW_LINE') }}"
line: "Hello world={{ lookup('env', 'NUM') }}"

也许有比使用环境变量更好的方法来做到这一点?

最佳答案

Register Variables

- shell: /usr/bin/foo
register: foo_result

Registering stdout as ansible variables

- debug: msg="{{ hello.stdout }}"    
- debug: msg="{{ hello.stderr }}"

Including task with variables :

tasks:
- include: wordpress.yml wp_user=timmy

Including role with variables

- hosts: webservers
roles:
- common
- { role: foo_app_instance, dir: '/opt/a', app_port: 5000 }

针对您的情况:

- name: so question 39041208
hosts: '{{ target | default("all") }}'
tasks:
- name: Find the last Hello world in foo.txt, and get the value of N
# shell: awk '/Hello world/ {aline=$0} END{print aline}' "/home/ak/ansible/stackoverflow/q39041208.txt"
shell: awk '/Hello world/ {aline=$0} END{print NR}' "/home/ak/ansible/stackoverflow/q39041208.txt"
register: last_line
ignore_errors: true
- name: debug
debug: msg="last line {{ last_line.stdout }}"
- name: debug next number
debug: msg="next num {{ last_line.stdout | int + 1 }}"
- name: Add the next Hello world line
lineinfile:
dest: /home/ak/ansible/stackoverflow/q39041208.txt
insertafter: "{{ last_line.stdout }}"
line: "Hello world={{ last_line.stdout | int + 1 }}"

关于ansible - 在 Ansible 中,如何在一个任务中导出环境变量以便它可以被另一个任务使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39041208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com