在剧本的同一主机上为多个用户设置多个授权密钥

时间:2019-02-12 22:17:00

标签: loops ansible

我在远程主机上创建用户:

 - name: Add Existing Users to Server
  user:
    name: "{{ item }}"
    groups: admin, prog
    generate_ssh_key: yes
    ssh_key_bits: 2048
    ssh_key_file: .ssh/id_rsa
  register: result
  with_items:
    - user1
    - user2
    - user3
    - user4
    - user5
    - user6
    - user7
- debug:
    msg: "{{ result.results | map(attribute='ssh_public_key') | list }}"

这将创建所有用户及其目录。我可以从调试消息访问结果数组,它看起来像这样:

ok: [192.168.blah.blah] => {
    "msg": [
        "ssh-rsa blahblahblahblahblahblah ansible-generated on TEST",
        "ssh-rsa blahblahblahblahblahblah ansible-generated on TEST",
        "same thing for rest of users....."
    ]
}

问题是我不知道如何在以后的下一个任务中访问它。这是密钥生成任务:

- name: Set authorized keys for users
  authorized_key:
    user: "{{ item }}"
    state: present
    key: #Need to access that generated list here, but how? 
  with_items:
    - user1
    - user2
    - user3
    - user4
    - user5
    - user6
    - user7

这可能与ansible中的循环有关吗?

1 个答案:

答案 0 :(得分:0)

我想出了如何访问结果数组,循环遍历并设置键的方法:

以前的代码:

- name: Set authorized keys for users
authorized_key:
  user: "{{ item }}"
  state: present
  key: #Need to access that generated list here, but how? 
with_items:
  - user1
  - user2
  - user3
  - user4
  - user5
  - user6
  - user7

工作代码

- name: Set authorized keys for users
authorized_key:
  user: "{{ item.name }}" #Grabs the username from each object
  state: present
  key: "{{ item.ssh_public_key }}" #Grabs the ssh key from each object
loop: "{{ result.results | list }}" #Loops over the object array

这将为每个用户正确生成authorized_key文件。