首页 > 解决方案 > 使用 set_fact 结果设置 Ansible 变量

问题描述

我在 RHEL7 上运行 ansible 2.9.18。

我正在使用 hvac 从 Hashicorp 保险库中检索用户名和密码。

  vars:
    - creds: "{{ lookup('hashi_vault', 'secret=tst2/data/cisco token= url=http://10.80.23.81:8200') }}"

  tasks:
    - name: set Cisco creds
      set_fact:
        cisco: "{{ creds['data'] }}"

    - name: Get nxos facts
      nxos_command:
        username: "{{ cisco['username'] }}"
        password: "{{ cisco['password'] }}"
        commands: show ver
        timeout: 30
      register: ver_out
    - debug: msg="{{ ver_out.stdout }}"

但是用户名和密码已被弃用,我试图弄清楚如何将用户名、密码作为“提供者”变量传递。而且这段代码不起作用:

vars:
    asa_api:
      - creds: "{{ lookup('hashi_vault', 'secret=tst2/data/cisco token= url=http://10.80.23.81:8200') }}"
        set_fact:
          cisco: "{{ creds['data'] }}"
        username: "{{ cisco['username'] }}"
        password: "{{ cisco['password'] }}"

  tasks:
      - name: show run
        asa_command:
          commands: show run
          provider: "{{ asa_api }}"
        register: run
        become: yes
        tags:
          - show_run

我无法弄清楚使这项工作的语法如何。我将不胜感激任何帮助。

谢谢,史蒂夫

标签: ansible

解决方案


免责声明:这是一个通用的答案。我没有任何网络设备可以对此进行全面测试,因此您可能需要在阅读文档后稍作调整


你采取了错误的方式。您根本不需要set_fact,您尝试使用的两种方法(用户/密码或provider字典)实际上都已弃用。Ansible 将您的网络设备视为任何主机,并将使用您配置的可用用户和密码(如果存在)。

在以下示例中,我假设您的剧本仅针对网络设备,并且存储在您的保管库中的登录名/密码在所有设备上都是相同的。

- name: Untested network device connection configuration demo
  hosts: my_network_device_group

  vars:
    # This indicates which connection plugin to use. Default is ssh
    # An other possible value is httpapi. See above documentation link
    ansible_connection: network_cli
    
    vault_secret: tst2/data/cisco
    vault_token: verysecret
    vault_url: http://10.80.23.81:8200
    vault_options: "secret={{ vault_secret }} token={{ vault_token }} url={{ vault_url }}"

    creds: "{{ lookup('hashi_vault', vault_options).data }}"
    
    # These are the user and pass used for connection.
    ansible_user: "{{ creds.username }}"
    ansible_password: "{{ creds.password }}"

  tasks:
    - name: Get nxos version
      nxos_command:
        commands: show ver
        timeout: 30
      register: ver_cmd
   
    - name: show version
      debug:
        msg: "NXOS version on {{ inventory_hostname }} is {{ ver_cmd.stdout }}"

    - name: An other task to play on targets
      debug:
        msg: "Task played on {{ inventory_hostname }}"

vars您可以将此信息存储在所有主机或特定组(甚至是每个主机)的清单中,而不是在播放级别。如果您想使用该功能,请参阅如何组织您的组和主机变量。


推荐阅读