【问题标题】:Using authorized_key module in a playbook to set up SSH key for new users在 playbook 中使用 authorized_key 模块为新用户设置 SSH 密钥
【发布时间】:2016-04-19 15:20:17
【问题描述】:

场景:

根据 hosts 文件的 [clients] 部分执行以下操作:

  1. 检查用户“foo”的SSH登录是否失败,如果失败
  2. 使用 authorized_key 模块为用户“foo”添加 SSH 密钥
  3. 假设远程机器上已经存在用户“foo”并且已经在本地(ansible)主机上创建了 SSH 公钥

我知道 this solution 使用 Ansible 命令行,但我希望能够将其放入剧本中。可以让脚本与用户输入密码(包括 sudo)交互。

现在我想出了如何使用 3-rd 方角色 GROG.authorized-key 来做我想做的事,但它仍然需要我使用 -K 开关运行剧本。 Ansible 中是否有一些东西(除了命令行开关)只会在需要时提示输入密码?

- hosts: clients
  vars:
    authorized_key_list:
      - name: pdo
        authorized_keys:
         - key: "{{ lookup('file', '/home/pdo/.ssh/id_rsa.pub') }}"
           state: present
  roles:
    - { role: GROG.authorized-key }

【问题讨论】:

  • authorized_key 没有密码参数。密码应该有什么用?也许我可以帮助你。
  • 我需要提示用户输入密码,这样“authorized_key”才能完成工作。我也不想使用 ask-pass 作为命令行参数
  • 好的,所以您需要用户或 sudo 权限?试试 become 和 become_user 选项。
  • 如果我“成为”它会提示我输入 root 密码吗?看起来我被命令行“ask-pass”和“ask-become-pass”开关卡住了,我想避免这种情况

标签: python ssh ansible ansible-playbook authorized-keys


【解决方案1】:

我认为根据您的 cmets 这应该可行:

- hosts: clients
  become: true
  tasks: 
  - name: Add authorized_key to pdo user on the remote client machine(s)
    authorized_key: user=foo key="{{ lookup('file', '/home/pdo/.ssh/id_rsa.pub') }}"

使用 -K 调用它以获得成为密码的问题。这将在远程机器上创建一个 sudo 命令。这就是你需要的,不是吗?

【讨论】:

  • 这失败了,因为我的远程用户没有设置为 sudoer。我正在使用不需要 sudo 权限的 GROG.authorized-key 角色(请参阅更新)
【解决方案2】:

特别感谢 GROG 帮助我了解我做错了什么。

基本上,我在以非 root 用户身份运行 Ansible playbook 时尝试做 root 工作。我最终创建了以下 bootstrap.yml 并使用以下命令运行它:

ansible-playbook ./bootstrap.yml -u root -k

这将使用 root 密码提示以 root 身份运行我的 playbook,并且能够创建用户并建立 sudo 和无密码访问

---
# file: bootstrap.yml
# Execute once as root user to create a public key and install it to your client machine(s) using the following command
# ansible-playbook ./auth-client.yml -u root -k

# This requires you to install GROG.management-user role from the Ansible Galaxy using this command:
# ansible-galaxy install GROG.management-user

# Add pdo user on remote machines
- hosts: all
  tasks:
  - name: Add remote users
    user: name=pdo group=users

# Generate SSK keys at the localhost for pde user
- hosts: localhost
  tasks:
  - name: Provision local pdo user
    user: name=pdo generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa

# Install public key into remote machine    
- hosts: all
  vars:
    authorized_key_list:
      - name: pdo
        authorized_keys:
         - key: "{{ lookup('file', '/home/pdo/.ssh/id_rsa.pub') }}"
           state: present
  roles:
    - { role: GROG.authorized-key }

# Add sudo privileges for pdo user
- hosts: all
  roles:
  - { role: GROG.sudo, become: yes }

【讨论】:

    猜你喜欢
    • 2020-02-03
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 2016-03-03
    • 2017-11-27
    • 2016-09-14
    • 2020-01-15
    • 2022-09-23
    相关资源
    最近更新 更多