summaryrefslogtreecommitdiffstats
path: root/ansible_collections/azure/azcollection/plugins/modules/azure_rm_adpassword.py
blob: 587d842b55ba31e18b5a184bab481896b1f8a011 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#!/usr/bin/python
#
# Copyright (c) 2020 Haiyuan Zhang, <haiyzhan@microsoft.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function

__metaclass__ = type


DOCUMENTATION = '''
---
module: azure_rm_adpassword

version_added: "0.2.0"

short_description: Manage application password

description:
    - Manage application password.

options:
    app_id:
        description:
            - The application ID.
        type: str
    service_principal_object_id:
        description:
            - The service principal object ID.
        type: str
    key_id:
        description:
            - The password key ID.
        type: str
    tenant:
        description:
            - The tenant ID.
        type: str
        required: True
    end_date:
        description:
            - Date or datemtime after which credentials expire.
            - Default value is one year after current time.
        type: str
    value:
        description:
            - The application password value.
            - Length greater than 18 characters.
        type: str
    app_object_id:
        description:
            - The application object ID.
        type: str
    state:
        description:
            - Assert the state of Active Dirctory Password.
            - Use C(present) to create or update a Password and use C(absent) to delete.
            - Update is not supported, if I(state=absent) and I(key_id=None), then all passwords of the application will be deleted.
        default: present
        choices:
            - absent
            - present
        type: str

extends_documentation_fragment:
    - azure.azcollection.azure

author:
    haiyuan_zhang (@haiyuazhang)
    Fred-sun (@Fred-sun)

'''

EXAMPLES = '''
- name: create ad password
  azure_rm_adpassword:
    app_id: "{{ app_id }}"
    state: present
    value: "$abc12345678"
    tenant: "{{ tenant_id }}"
'''

RETURN = '''
end_date:
    description:
        - Date or datemtime after which credentials expire.
        - Default value is one year after current time.
    type: str
    returned: always
    sample: "2021-06-28T06:00:32.637070+00:00"
key_id:
    description:
        - The password key ID
    type: str
    returned: always
    sample: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
start_date:
    description:
        - Date or datetime at which credentials become valid.
        - Default value is current time.
    type: str
    returned: always
    sample: "2020-06-28T06:00:32.637070+00:00"

'''

from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
import uuid
import datetime

try:
    from azure.graphrbac.models import GraphErrorException
    from azure.graphrbac.models import PasswordCredential
    from azure.graphrbac.models import ApplicationUpdateParameters
    from dateutil.relativedelta import relativedelta
except ImportError:
    # This is handled in azure_rm_common
    pass


class AzureRMADPassword(AzureRMModuleBase):
    def __init__(self):

        self.module_arg_spec = dict(
            app_id=dict(type='str'),
            service_principal_object_id=dict(type='str'),
            app_object_id=dict(type='str'),
            key_id=dict(type='str'),
            tenant=dict(type='str', required=True),
            value=dict(type='str'),
            end_date=dict(type='str'),
            state=dict(type='str', default='present', choices=['present', 'absent']),
        )

        self.state = None
        self.tenant = None
        self.app_id = None
        self.service_principal_object_id = None
        self.app_object_id = None
        self.key_id = None
        self.value = None
        self.end_date = None
        self.results = dict(changed=False)

        self.client = None

        super(AzureRMADPassword, self).__init__(derived_arg_spec=self.module_arg_spec,
                                                supports_check_mode=False,
                                                supports_tags=False,
                                                is_ad_resource=True)

    def exec_module(self, **kwargs):
        for key in list(self.module_arg_spec.keys()):
            setattr(self, key, kwargs[key])

        self.client = self.get_graphrbac_client(self.tenant)
        self.resolve_app_obj_id()
        passwords = self.get_all_passwords()

        if self.state == 'present':
            if self.key_id and self.key_exists(passwords):
                self.update(passwords)
            else:
                self.create_password(passwords)
        else:
            if self.key_id is None:
                self.delete_all_passwords(passwords)
            else:
                self.delete_password(passwords)

        return self.results

    def key_exists(self, old_passwords):
        for pd in old_passwords:
            if pd.key_id == self.key_id:
                return True
        return False

    def resolve_app_obj_id(self):
        try:
            if self.app_object_id is not None:
                return
            elif self.app_id or self.service_principal_object_id:
                if not self.app_id:
                    sp = self.client.service_principals.get(self.service_principal_object_id)
                    self.app_id = sp.app_id
                if not self.app_id:
                    self.fail("can't resolve app via service principal object id {0}".format(self.service_principal_object_id))

                result = list(self.client.applications.list(filter="appId eq '{0}'".format(self.app_id)))
                if result:
                    self.app_object_id = result[0].object_id
                else:
                    self.fail("can't resolve app via app id {0}".format(self.app_id))
            else:
                self.fail("one of the [app_id, app_object_id, service_principal_id] must be set")

        except GraphErrorException as ge:
            self.fail("error in resolve app_object_id {0}".format(str(ge)))

    def get_all_passwords(self):

        try:
            return list(self.client.applications.list_password_credentials(self.app_object_id))
        except GraphErrorException as ge:
            self.fail("failed to fetch passwords for app {0}: {1}".format(self.app_object_id, str(ge)))

    def delete_all_passwords(self, old_passwords):

        if len(old_passwords) == 0:
            self.results['changed'] = False
            return
        try:
            self.client.applications.patch(self.app_object_id, ApplicationUpdateParameters(password_credentials=[]))
            self.results['changed'] = True
        except GraphErrorException as ge:
            self.fail("fail to purge all passwords for app: {0} - {1}".format(self.app_object_id, str(ge)))

    def delete_password(self, old_passwords):
        if not self.key_exists(old_passwords):
            self.results['changed'] = False
            return

        num_of_passwords_before_delete = len(old_passwords)

        for pd in old_passwords:
            if pd.key_id == self.key_id:
                old_passwords.remove(pd)
                break
        try:
            self.client.applications.patch(self.app_object_id, ApplicationUpdateParameters(password_credentials=old_passwords))
            num_of_passwords_after_delete = len(self.get_all_passwords())
            if num_of_passwords_after_delete != num_of_passwords_before_delete:
                self.results['changed'] = True

        except GraphErrorException as ge:
            self.fail("failed to delete password with key id {0} - {1}".format(self.app_id, str(ge)))

    def create_password(self, old_passwords):

        def gen_guid():
            return uuid.uuid4()

        if self.value is None:
            self.fail("when creating a new password, module parameter value can't be None")

        start_date = datetime.datetime.now(datetime.timezone.utc)
        end_date = self.end_date or start_date + relativedelta(years=1)
        value = self.value
        key_id = self.key_id or str(gen_guid())

        new_password = PasswordCredential(start_date=start_date, end_date=end_date, key_id=key_id,
                                          value=value, custom_key_identifier=None)
        old_passwords.append(new_password)

        try:
            client = self.get_graphrbac_client(self.tenant)
            app_patch_parameters = ApplicationUpdateParameters(password_credentials=old_passwords)
            client.applications.patch(self.app_object_id, app_patch_parameters)

            new_passwords = self.get_all_passwords()
            for pd in new_passwords:
                if pd.key_id == key_id:
                    self.results['changed'] = True
                    self.results.update(self.to_dict(pd))
        except GraphErrorException as ge:
            self.fail("failed to create new password: {0}".format(str(ge)))

    def update_password(self, old_passwords):
        self.fail("update existing password is not supported")

    def to_dict(self, pd):
        return dict(
            end_date=pd.end_date,
            start_date=pd.start_date,
            key_id=pd.key_id
        )


def main():
    AzureRMADPassword()


if __name__ == '__main__':
    main()