简体   繁体   English

Ansible剧本,在主机之间生成并共享变量

[英]Ansible playbook that generates and shares variable between hosts

My Ansible playbook deploys to both database and webservers and I need to use some shared variables between them. 我的Ansible剧本同时部署到数据库服务器和Web服务器,我需要在它们之间使用一些共享变量。 The answer from this question almost gives me what I need: 这个问题答案几乎可以满足我的需求:

---
- hosts: all
  tasks:
  - set_fact: my_global_var='hello'

- hosts: db
  tasks:
  - debug: msg={{my_global_var}}

- hosts: web
  tasks:
  - debug: msg={{my_global_var}}

However, in my case the variable is a password that is generated randomly by the playbook on each run and then has to be shared: 但是,在我的情况下,变量是密码,该密码由剧本在每次运行时随机生成,然后必须共享:

---
- hosts: all
  tasks:
  - name: Generate new password
    shell: "tr -dc _[:alnum:] < /dev/urandom | head -c${1:-20}"
    register: new_password    
  - name: Set password as fact
    set_fact:
      my_global_var: "{{ new_password.stdout }}"

- hosts: db
  tasks:
  - debug: msg={{my_global_var}}

- hosts: web
  tasks:
  - debug: msg={{my_global_var}}

This above example doesn't work as the password is now re-generated and completely different for each host in the all hosts (unless you coincidentally use the same machine/hostname for your db and web servers). 上面的示例不起作用,因为现在重新生成了密码,并且all主机中的每个主机的密码都完全不同(除非您为数据库服务器和Web服务器巧合地使用相同的机器/主机名)。

Ideally I don't want someone to have to remember to pass a good random password in on the command-line using --extra-vars , it should be generated and handled by the playbook. 理想情况下,我不希望有人记住使用--extra-vars在命令行中传递良好的随机密码,该密码应该由剧本生成和处理。

Is there any suggested mechanism in Ansible for creating variables within a playbook and having it accessible to all hosts within that playbook? Ansible中是否有任何建议的机制可用于在剧本中创建变量并使该剧本中的所有主机访问它?

You may want to try to generate pass on localhost and then copy it to every other host: 您可能想要尝试在本地主机上生成传递,然后将其复制到其他每个主机:

---
- hosts: localhost
  tasks:
  - name: Generate new password
    shell: "tr -dc _[:alnum:] < /dev/urandom | head -c${1:-20}"
    register: new_password    

- hosts: all
  tasks:
  - name: Set password as fact
    set_fact:
      my_global_var: "{{ hostvars['localhost'].new_password.stdout }}"

- hosts: db
  tasks:
  - debug: msg={{my_global_var}}

- hosts: web
  tasks:
  - debug: msg={{my_global_var}}

Just set the run_once flag on your tasks: 只需在您的任务上设置run_once标志:

- hosts: all
  tasks:
  - name: Generate new password
    shell: "tr -dc _[:alnum:] < /dev/urandom | head -c${1:-20}"
    run_once: True
    register: new_password

  - name: Set password as fact
    set_fact:
      my_global_var: "{{ new_password.stdout }}"

Then this password will only be generated once 那么此密码只会生成一次

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

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