| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
from __future__ import (absolute_import, division, print_function) |
| 6 |
__metaclass__ = type |
| 7 |
|
| 8 |
DOCUMENTATION = """ |
| 9 |
--- |
| 10 |
name: azure_keyvault_secret |
| 11 |
author: |
| 12 |
- Hai Cao (@tk5eq) <[email protected]> |
| 13 |
- Marcin Slowikowski (@msl0) |
| 14 |
version_added: '1.12.0' |
| 15 |
requirements: |
| 16 |
- requests |
| 17 |
- azure |
| 18 |
short_description: Read secret from Azure Key Vault. |
| 19 |
description: |
| 20 |
- This lookup returns the content of secret saved in Azure Key Vault. |
| 21 |
- When ansible host is MSI enabled Azure VM, user don't need provide any credential to access to Azure Key Vault. |
| 22 |
options: |
| 23 |
_terms: |
| 24 |
description: Secret name, version can be included like secret_name/secret_version. |
| 25 |
required: True |
| 26 |
vault_url: |
| 27 |
description: Url of Azure Key Vault. |
| 28 |
required: True |
| 29 |
tenant: |
| 30 |
aliases: |
| 31 |
- tenant_id |
| 32 |
use_msi: |
| 33 |
description: |
| 34 |
- MSI token autodiscover. |
| 35 |
- The default is to try MSI authentication first, then use auth_source, You can disable MSI entirely |
| 36 |
by setting this to False. |
| 37 |
default: true |
| 38 |
use_cli: |
| 39 |
description: |
| 40 |
- When I(use_cli=True), get the 'az login' credential authentication, default if false. |
| 41 |
- Deprecated, please use I(auth_source=cli) instead. |
| 42 |
cloud_type: |
| 43 |
description: Specify which cloud, such as C(azure), C(usgovcloudapi). |
| 44 |
notes: |
| 45 |
- If version is not provided, this plugin will return the latest version of the secret. |
| 46 |
- If ansible is running on Azure Virtual Machine with MSI enabled, client_id, secret and tenant are not required. |
| 47 |
- For enabling MSI on Azure VM, please refer to this doc https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/ |
| 48 |
- After enabling MSI on Azure VM, remember to grant access of the Key Vault to the VM by adding a new Acess Policy in Azure Portal. |
| 49 |
- If multiple managed identities are assigned to the VM, set I(client_id) to select the correct user-assigned identity when using MSI. |
| 50 |
- If MSI is not enabled on ansible host, it's required to provide a valid service principal which has access to the key vault. |
| 51 |
- To authenticate via service principal, pass client_id, secret and tenant or set environment variables |
| 52 |
AZURE_CLIENT_ID, AZURE_CLIENT_SECRET and AZURE_TENANT_ID. |
| 53 |
- Authentication via C(az login) is also supported. Set I(use_cli=true) when using Azure CLI. |
| 54 |
- To use a plugin from a collection, please reference the full namespace, collection name, and lookup plugin name that you want to use. |
| 55 |
|
| 56 |
extends_documentation_fragment: |
| 57 |
- azure.azcollection.azure_plugin |
| 58 |
""" |
| 59 |
|
| 60 |
EXAMPLE = """ |
| 61 |
- name: Look up secret when azure cli login |
| 62 |
debug: |
| 63 |
msg: msg: "{{ lookup('azure.azcollection.azure_keyvault_secret', 'testsecret', vault_url=key_vault_uri, use_cli=true)}}" |
| 64 |
|
| 65 |
- name: Look up secret with cloud type |
| 66 |
debug: |
| 67 |
msg: msg: "{{ lookup('azure.azcollection.azure_keyvault_secret', 'testsecret', cloud_type='usgovcloudapi', vault_url=key_vault_uri)}}" |
| 68 |
|
| 69 |
- name: Look up secret when ansible host is MSI enabled Azure VM |
| 70 |
debug: |
| 71 |
msg: "the value of this secret is {{ |
| 72 |
lookup( |
| 73 |
'azure.azcollection.azure_keyvault_secret', |
| 74 |
'testSecret/version', |
| 75 |
vault_url='https://yourvault.vault.azure.net' |
| 76 |
) |
| 77 |
}}" |
| 78 |
|
| 79 |
- name: Look up secret when ansible host is MSI with specific UAMI |
| 80 |
debug: |
| 81 |
msg: "the value of this secret is {{ |
| 82 |
lookup( |
| 83 |
'azure.azcollection.azure_keyvault_secret', |
| 84 |
'testSecret/version', |
| 85 |
vault_url='https://yourvault.vault.azure.net', |
| 86 |
client_id='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' |
| 87 |
) |
| 88 |
}}" |
| 89 |
|
| 90 |
- name: Look up secret when ansible host is general VM |
| 91 |
vars: |
| 92 |
url: 'https://yourvault.vault.azure.net' |
| 93 |
secretname: 'testSecret/version' |
| 94 |
client_id: '123456789' |
| 95 |
secret: 'abcdefg' |
| 96 |
tenant: 'uvwxyz' |
| 97 |
debug: |
| 98 |
msg: "the value of this secret is {{ |
| 99 |
lookup( |
| 100 |
'azure.azcollection.azure_keyvault_secret', |
| 101 |
secretname, |
| 102 |
vault_url=url, |
| 103 |
client_id=client_id, |
| 104 |
secret=secret, |
| 105 |
tenant=tenant, |
| 106 |
use_msi=False |
| 107 |
) |
| 108 |
}}" |
| 109 |
|
| 110 |
# Example below creates an Azure Virtual Machine with SSH public key from key vault using 'azure_keyvault_secret' lookup plugin. |
| 111 |
- name: Create Azure VM |
| 112 |
hosts: localhost |
| 113 |
connection: local |
| 114 |
no_log: True |
| 115 |
vars: |
| 116 |
resource_group: myResourceGroup |
| 117 |
vm_name: testvm |
| 118 |
location: eastus |
| 119 |
ssh_key: "{{ lookup('azure.azcollection.azure_keyvault_secret','myssh_key') }}" |
| 120 |
- name: Create VM |
| 121 |
azure_rm_virtualmachine: |
| 122 |
resource_group: "{{ resource_group }}" |
| 123 |
name: "{{ vm_name }}" |
| 124 |
vm_size: Standard_DS1_v2 |
| 125 |
admin_username: azureuser |
| 126 |
ssh_password_enabled: false |
| 127 |
ssh_public_keys: |
| 128 |
- path: /home/azureuser/.ssh/authorized_keys |
| 129 |
key_data: "{{ ssh_key }}" |
| 130 |
network_interfaces: "{{ vm_name }}" |
| 131 |
image: |
| 132 |
offer: 0001-com-ubuntu-server-focal |
| 133 |
publisher: Canonical |
| 134 |
sku: 20_04-lts |
| 135 |
version: latest |
| 136 |
""" |
| 137 |
|
| 138 |
RETURN = """ |
| 139 |
_raw: |
| 140 |
description: secret content string |
| 141 |
""" |
| 142 |
|
| 143 |
from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMAuth |
| 144 |
from ansible.errors import AnsibleError |
| 145 |
from ansible.plugins.lookup import LookupBase |
| 146 |
from ansible.utils.display import Display |
| 147 |
try: |
| 148 |
import logging |
| 149 |
import requests |
| 150 |
from azure.keyvault.secrets import SecretClient |
| 151 |
from azure.keyvault.secrets import SecretClient |
| 152 |
|
| 153 |
except ImportError: |
| 154 |
pass |
| 155 |
|
| 156 |
display = Display() |
| 157 |
|
| 158 |
TOKEN_ACQUIRED = False |
| 159 |
|
| 160 |
logger = logging.getLogger("azure.identity").setLevel(logging.ERROR) |
| 161 |
|
| 162 |
|
| 163 |
class LookupModule(LookupBase): |
| 164 |
def lookup_secret_non_msi(self, terms, vault_url, auth_source): |
| 165 |
|
| 166 |
client_id = self.get_option('client_id') |
| 167 |
secret = self.get_option('secret') |
| 168 |
tenant = self.get_option('tenant') |
| 169 |
|
| 170 |
|
| 171 |
if self.get_option('use_cli'): |
| 172 |
auth_source = 'cli' |
| 173 |
|
| 174 |
if auth_source == 'auto': |
| 175 |
if any(v is None for v in [client_id, secret, tenant]): |
| 176 |
auth_source = 'cli' |
| 177 |
|
| 178 |
auth_options = dict( |
| 179 |
auth_source=auth_source, |
| 180 |
client_id=client_id, |
| 181 |
secret=secret, |
| 182 |
tenant=tenant, |
| 183 |
is_ad_resource=True |
| 184 |
) |
| 185 |
|
| 186 |
azure_auth = AzureRMAuth(**auth_options) |
| 187 |
|
| 188 |
client = SecretClient(vault_url, azure_auth.azure_credential_track2) |
| 189 |
|
| 190 |
ret = [] |
| 191 |
for term in terms: |
| 192 |
try: |
| 193 |
secret_val = client.get_secret(term).value |
| 194 |
ret.append(secret_val) |
| 195 |
except Exception: |
| 196 |
raise AnsibleError('Failed to fetch secret ' + term + ' from ' + vault_url + '.') |
| 197 |
return ret |
| 198 |
|
| 199 |
def run(self, terms, variables, **kwargs): |
| 200 |
|
| 201 |
self.set_options(direct=kwargs) |
| 202 |
|
| 203 |
ret = [] |
| 204 |
|
| 205 |
auth_source = self.get_option('auth_source') |
| 206 |
vault_url = self.get_option('vault_url') |
| 207 |
client_id = self.get_option('client_id') |
| 208 |
use_msi = self.get_option('use_msi') |
| 209 |
TOKEN_ACQUIRED = False |
| 210 |
token = None |
| 211 |
|
| 212 |
token_params = { |
| 213 |
'api-version': '2018-02-01', |
| 214 |
'resource': 'https://vault.{0}.net'.format(self.get_option('cloud_type') or 'azure') |
| 215 |
} |
| 216 |
|
| 217 |
if client_id: |
| 218 |
token_params['client_id'] = client_id |
| 219 |
|
| 220 |
token_headers = { |
| 221 |
'Metadata': 'true' |
| 222 |
} |
| 223 |
|
| 224 |
if use_msi: |
| 225 |
try: |
| 226 |
token_res = requests.get('http://169.254.169.254/metadata/identity/oauth2/token', |
| 227 |
params=token_params, |
| 228 |
headers=token_headers, |
| 229 |
timeout=(3.05, 27)) |
| 230 |
if token_res.ok: |
| 231 |
token = token_res.json().get("access_token") |
| 232 |
if token is not None: |
| 233 |
TOKEN_ACQUIRED = True |
| 234 |
else: |
| 235 |
display.v('Successfully called MSI endpoint, but no token was available. Will use service principal if provided.') |
| 236 |
else: |
| 237 |
display.v("Unable to query MSI endpoint, Error Code %s. Will use service principal if provided" % token_res.status_code) |
| 238 |
except Exception: |
| 239 |
display.v('Unable to fetch MSI token. Will use service principal if provided.') |
| 240 |
|
| 241 |
if vault_url is None: |
| 242 |
raise AnsibleError('Failed to get valid vault url.') |
| 243 |
if TOKEN_ACQUIRED: |
| 244 |
secret_params = {'api-version': '2016-10-01'} |
| 245 |
secret_headers = {'Authorization': 'Bearer ' + token} |
| 246 |
for term in terms: |
| 247 |
try: |
| 248 |
secret_res = requests.get(vault_url + '/secrets/' + term, params=secret_params, headers=secret_headers) |
| 249 |
ret.append(secret_res.json()["value"]) |
| 250 |
except KeyError: |
| 251 |
raise AnsibleError('Failed to fetch secret ' + term + ' from ' + vault_url + '.') |
| 252 |
except Exception: |
| 253 |
raise AnsibleError('Failed to fetch secret ' + term + ' from ' + vault_url + ' via MSI endpoint.') |
| 254 |
return ret |
| 255 |
else: |
| 256 |
return self.lookup_secret_non_msi(terms, vault_url, auth_source) |