如何在 ansible 角色中使用 var

如何在 ansible 角色中使用 var

我想创建一个 ansible 角色来使用 ssh_keys 添加用户

├── ansible.cfg
├── hosts
├── playbooks
│   └── add_user.yml
└── roles
    └── add-user
        ├── files
        │   ├── ansible.pub
        │   ├── dhirendra.pub
        │   ├── nitigyas.pub
        │   └── vinayaks.pub
        ├── tasks
        │   └── main.yml
        └── vars
            └── main.yml

task/main.yml 文件是:

---
- name: AddUser in the server
  user: 
   name: ansible
   password: $6$sHQAZJ32E$ujHauabN7ZTbOQ/zhT5899EIaFErOecXYvTEyhekexy4dydsAXTGdUpaB8M4fQf2UGpZgX/Zg2Uv6areeuv/r0
   comment: Ansible Configuration Mgmt
   shell: /bin/bash

- name: Add SSH key to users home direcotory
  authorized_key: 
   user: "{{ item.name }}"
   key: "{{ item.file }}"
   state: present
  with_items: 
   - ssh_vars
...

vars/main.yml 文件是:

---
ssh_vars:    
 - { name: "ansible" , file: 'ansible.pub' }

当我运行这个角色时出现以下错误

PLAY [backend1.greengst.com] *************************************************************************************************************

TASK [add-user : AddUser in the server] **************************************************************************************************
ok: [backend1.greengst.com]

TASK [add-user : Add SSH key to users home direcotory] ***********************************************************************************
fatal: [backend1.greengst.com]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'ansible.vars.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'name'\n\nThe error appears to have been in '/etc/ansible/roles/add-user/tasks/main.yml': line 9, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Add SSH key to users home direcotory\n  ^ here\n"}
Debugger invoked

答案1

问题在于您使用的方式with_items:裸变量已经很长时间不受支持了。

像这样纠正你的循环:with_items: "{{ ssh_vars }}"

相关内容