代码之家  ›  专栏  ›  技术社区  ›  Silveri

Ansible playbook,在主机之间生成和共享变量

  •  4
  • Silveri  · 技术社区  · 7 年前

    我的Ansible playbook部署到数据库和Web服务器,我需要在它们之间使用一些共享变量。这个 answer 从这个 question 几乎满足了我的需求:

    ---
    - 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}}
    

    ---
    - 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}}
    

    上面的示例不起作用,因为密码现在已重新生成,并且对于中的每个主机都完全不同 all 主机(除非您同时对db和web服务器使用相同的机器/主机名)。

    理想情况下,我不希望有人必须记住在命令行上使用 --extra-vars ,它应该由剧本生成和处理。

    2 回复  |  直到 7 年前
        1
  •  4
  •   Konstantin Suvorov    7 年前

    您可能希望尝试在本地主机上生成pass,然后将其复制到其他每台主机:

    ---
    - 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}}
    
        2
  •  0
  •   boomskats    5 年前

    我知道这是一个老问题,但我选择了另一种方法,将这里提供的两个答案和 this issue 认为 它有点优雅。按2.8.4测试。

    这是在我的环境中可行的解决方案,我希望在我的所有主机上都有一个通用的时间戳备份目录,以便以后恢复:

    ---
    tasks:
      - name: Set local fact for the universal backup string
        set_fact:
          thisHostTimestamp: "{{ ansible_date_time.iso8601 }}"
        delegate_to: localhost
        delegate_facts: true
    
      - name: Distribute backup datestring to all hosts in group
         set_fact:
           backupsTimeString: "{{ hostvars['localhost']['thisHostTimestamp'] }}"
    

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