我已部署 Azure Linux VM 并安装了 AADSSHLoginForLinux VM 扩展。 这允许我使用我的 Azure 凭据登录到 VM,并允许我使用 EntraID (Active Directory) 组为我的团队配置基于角色的访问。任何团队成员都可以使用以下命令登录虚拟机,而无需弄乱 SSH 密钥等,并且他们将使用 azure-cli 根据他们所属的 EntraID 组获得适当的访问权限(sudo 或普通用户) ssh 包装器:
az ssh vm --ip 1.2.3.4
(假设他们之前在某个时刻运行过
as login
。)
现在我想使用它作为 Ansible 的
ssh
命令,它将自动允许管理员安全组中的任何人部署 playbook。
az ssh vm
将传递 --
之后提供的 ssh 参数。
例如:
az ssh vm --ip 1.2.3.4 -- -p 23
因此应该可以将
az ssh vm
包装起来,以便 Ansible 可以使用它。
我找到了 Ansible 的 ssh_executable 选项,但这需要一个命令,而不是带参数的命令,所以我不能简单地将其设置为
az ssh vm ...
。
因此,需要一个包装脚本。
我还确定 Microsoft 不提供
scp
的等效包装器,因此需要解决这个问题。
如何将所有部分放在一起,以便使用我的 Azure 凭据和
az ssh
轻松部署 Ansible playbook?
第一步是创建一个 SSH 包装器,它将拦截来自 Ansible 的 SSH 参数并将它们传递给
az ssh
。
这篇博客文章介绍了如何为 GCP IAP 执行此操作。我已对其进行了调整以使其与
az ssh
: 一起使用
我正在使用以下包装器,改编自上面的博客文章:
#!/bin/bash
# ssh-wrapper.sh
#
# SSH Wrapper for az ssh
#
# We are using `az ssh vm --ip 1.2.3.4` to authenticate to VMs with
# Azure Role Based Athentication. However, Ansible doesn't directly
# support this.
#
# `az ssh vm` accepts additional SSH arguments, so this wrapper takes
# arguments from Ansible, and passes them onto `az ssh vm`.
# Wrapper adapted from here:
# https://blg.robot-house.us/posts/ansible-and-iap/
# Get last two arguments
host="${*: -2: 1}"
cmd="${*: -1: 1}"
# Filter out hard-coded Ansible SSH options.
# At least one of these seems to break az ssh, but I haven't figured out which.
# But it seems to work if you filter them all out as described in the blog linked above.
# This may cause problems if you need to pass your own SSH arguments,
# but for our use case it's OK.
# Only accept the options starting with '--'
declare -a opts
for s_arg in "${@: 1: $# -2}" ; do
if [[ "${s_arg}" == --* ]] ; then
opts+=("${s_arg}")
fi
done
exec az ssh vm --ip "${host}" -- "${opts[@]}" "${cmd}"
将此脚本另存为
ssh-wrapper.sh
,与您的 Ansible playbook 位于同一目录中。
现在,我们需要配置剧本以使用包装器。我们还需要将 Ansible 配置为使用
piped
传输,而不是 scp
或 sftp
。这将通过 SSH 传输文件,因此不需要 scp
和 sftp
。
你的剧本的开头应该是这样的:
---
- name: Example
hosts: all
vars:
# Need piped transfer because az ssh vm doesn't support scp or sftp
ansible_ssh_transfer_method: piped
ansible_ssh_executable: ./ssh-wrapper.sh
tasks:
- name: Test
ansible.builtin.command: pwd
假设您之前运行过
az login
,并且能够使用 az ssh login --ip 1.2.3.4
登录虚拟机,您应该能够简单地运行
Ansible 剧本如下:
ansible-playbook playbook.yml -i 1.2.3.4,