Debian Codegraph @

ansible_collections/community/general/plugins/modules/bitbucket_pipeline_key_pair.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2019, Evgeniy Krysanov <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: bitbucket_pipeline_key_pair
11 short_description: Manages Bitbucket pipeline SSH key pair
12 description:
13 - Manages Bitbucket pipeline SSH key pair.
14 author:
15 - Evgeniy Krysanov (@catcombo)
16 extends_documentation_fragment:
17 - community.general._bitbucket
18 - community.general._attributes
19 attributes:
20 check_mode:
21 support: full
22 diff_mode:
23 support: none
24 options:
25 repository:
26 description:
27 - The repository name.
28 type: str
29 required: true
30 workspace:
31 description:
32 - The repository owner.
33 - B(Note:) O(ignore:username) used to be an alias of this option. Since community.general 6.0.0 it is an alias of O(user).
34 type: str
35 required: true
36 public_key:
37 description:
38 - The public key.
39 type: str
40 private_key:
41 description:
42 - The private key.
43 type: str
44 state:
45 description:
46 - Indicates desired state of the key pair.
47 type: str
48 required: true
49 choices: [absent, present]
50 notes:
51 - Check mode is supported.
52 """
53
54 EXAMPLES = r"""
55 - name: Create or update SSH key pair
56 community.general.bitbucket_pipeline_key_pair:
57 repository: 'bitbucket-repo'
58 workspace: bitbucket_workspace
59 public_key: '{{lookup("file", "bitbucket.pub") }}'
60 private_key: '{{lookup("file", "bitbucket") }}'
61 state: present
62
63 - name: Remove SSH key pair
64 community.general.bitbucket_pipeline_key_pair:
65 repository: bitbucket-repo
66 workspace: bitbucket_workspace
67 state: absent
68 """
69
70 RETURN = r""" # """
71
72 from ansible.module_utils.basic import AnsibleModule
73
74 from ansible_collections.community.general.plugins.module_utils._bitbucket import BitbucketHelper
75
76 error_messages = {
77 "invalid_params": "Account, repository or SSH key pair was not found",
78 "required_keys": "`public_key` and `private_key` are required when the `state` is `present`",
79 }
80
81 BITBUCKET_API_ENDPOINTS = {
82 "ssh-key-pair": f"{BitbucketHelper.BITBUCKET_API_URL}/2.0/repositories/{{workspace}}/{{repo_slug}}/pipelines_config/ssh/key_pair",
83 }
84
85
86 def get_existing_ssh_key_pair(module, bitbucket):
87 """
88 Retrieves an existing ssh key pair from repository
89 specified in module param `repository`
90
91 :param module: instance of the :class:`AnsibleModule`
92 :param bitbucket: instance of the :class:`BitbucketHelper`
93 :return: existing key pair or None if not found
94 :rtype: dict or None
95
96 Return example::
97
98 {
99 "public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ...2E8HAeT",
100 "type": "pipeline_ssh_key_pair"
101 }
102 """
103 api_url = BITBUCKET_API_ENDPOINTS["ssh-key-pair"].format(
104 workspace=module.params["workspace"],
105 repo_slug=module.params["repository"],
106 )
107
108 info, content = bitbucket.request(
109 api_url=api_url,
110 method="GET",
111 )
112
113 if info["status"] == 404:
114 # Account, repository or SSH key pair was not found.
115 return None
116
117 return content
118
119
120 def update_ssh_key_pair(module, bitbucket):
121 info, content = bitbucket.request(
122 api_url=BITBUCKET_API_ENDPOINTS["ssh-key-pair"].format(
123 workspace=module.params["workspace"],
124 repo_slug=module.params["repository"],
125 ),
126 method="PUT",
127 data={
128 "private_key": module.params["private_key"],
129 "public_key": module.params["public_key"],
130 },
131 )
132
133 if info["status"] == 404:
134 module.fail_json(msg=error_messages["invalid_params"])
135
136 if info["status"] != 200:
137 module.fail_json(msg=f"Failed to create or update pipeline ssh key pair : {info}")
138
139
140 def delete_ssh_key_pair(module, bitbucket):
141 info, content = bitbucket.request(
142 api_url=BITBUCKET_API_ENDPOINTS["ssh-key-pair"].format(
143 workspace=module.params["workspace"],
144 repo_slug=module.params["repository"],
145 ),
146 method="DELETE",
147 )
148
149 if info["status"] == 404:
150 module.fail_json(msg=error_messages["invalid_params"])
151
152 if info["status"] != 204:
153 module.fail_json(msg=f"Failed to delete pipeline ssh key pair: {info}")
154
155
156 def main():
157 argument_spec = BitbucketHelper.bitbucket_argument_spec()
158 argument_spec.update(
159 repository=dict(type="str", required=True),
160 workspace=dict(type="str", required=True),
161 public_key=dict(type="str"),
162 private_key=dict(type="str", no_log=True),
163 state=dict(type="str", choices=["present", "absent"], required=True),
164 )
165 module = AnsibleModule(
166 argument_spec=argument_spec,
167 supports_check_mode=True,
168 required_one_of=BitbucketHelper.bitbucket_required_one_of(),
169 required_together=BitbucketHelper.bitbucket_required_together(),
170 )
171
172 bitbucket = BitbucketHelper(module)
173
174 state = module.params["state"]
175 public_key = module.params["public_key"]
176 private_key = module.params["private_key"]
177
178 # Check parameters
179 if ((public_key is None) or (private_key is None)) and (state == "present"):
180 module.fail_json(msg=error_messages["required_keys"])
181
182 # Retrieve access token for authorized API requests
183 bitbucket.fetch_access_token()
184
185 # Retrieve existing ssh key
186 key_pair = get_existing_ssh_key_pair(module, bitbucket)
187 changed = False
188
189 # Create or update key pair
190 if (not key_pair or (key_pair.get("public_key") != public_key)) and (state == "present"):
191 if not module.check_mode:
192 update_ssh_key_pair(module, bitbucket)
193 changed = True
194
195 # Delete key pair
196 elif key_pair and (state == "absent"):
197 if not module.check_mode:
198 delete_ssh_key_pair(module, bitbucket)
199 changed = True
200
201 module.exit_json(changed=changed)
202
203
204 if __name__ == "__main__":
205 main()