| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright (c) 2019 Ansible Project |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
|
| 6 |
# Author: |
| 7 |
# - Matthew Davis <[email protected]> |
| 8 |
# on behalf of Telstra Corporation Limited |
| 9 |
# |
| 10 |
# Common functionality to be used by the modules: |
| 11 |
# - acm_certificate |
| 12 |
# - acm_certificate_info |
| 13 |
|
| 14 |
""" |
| 15 |
Common Amazon Certificate Manager facts shared between modules |
| 16 |
""" |
| 17 |
|
| 18 |
try: |
| 19 |
from botocore.exceptions import BotoCoreError |
| 20 |
from botocore.exceptions import ClientError |
| 21 |
except ImportError: |
| 22 |
pass |
| 23 |
|
| 24 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 25 |
from ansible.module_utils.common.text.converters import to_bytes |
| 26 |
|
| 27 |
from .botocore import is_boto3_error_code |
| 28 |
from .retries import AWSRetry |
| 29 |
from .tagging import ansible_dict_to_boto3_tag_list |
| 30 |
from .tagging import boto3_tag_list_to_ansible_dict |
| 31 |
|
| 32 |
|
| 33 |
def acm_catch_boto_exception(func): |
| 34 |
def runner(*args, **kwargs): |
| 35 |
module = kwargs.pop("module", None) |
| 36 |
error = kwargs.pop("error", None) |
| 37 |
ignore_error_codes = kwargs.pop("ignore_error_codes", []) |
| 38 |
|
| 39 |
try: |
| 40 |
return func(*args, **kwargs) |
| 41 |
except is_boto3_error_code(ignore_error_codes): |
| 42 |
return None |
| 43 |
except (BotoCoreError, ClientError) as e: # pylint: disable=duplicate-except |
| 44 |
if not module: |
| 45 |
raise |
| 46 |
module.fail_json_aws(e, msg=error) |
| 47 |
|
| 48 |
return runner |
| 49 |
|
| 50 |
|
| 51 |
class ACMServiceManager: |
| 52 |
"""Handles ACM Facts Services""" |
| 53 |
|
| 54 |
def __init__(self, module): |
| 55 |
self.module = module |
| 56 |
self.client = module.client("acm") |
| 57 |
|
| 58 |
@acm_catch_boto_exception |
| 59 |
@AWSRetry.jittered_backoff(delay=5, catch_extra_error_codes=["RequestInProgressException"]) |
| 60 |
def delete_certificate_with_backoff(self, arn): |
| 61 |
self.client.delete_certificate(CertificateArn=arn) |
| 62 |
|
| 63 |
@acm_catch_boto_exception |
| 64 |
@AWSRetry.jittered_backoff(delay=5, catch_extra_error_codes=["RequestInProgressException"]) |
| 65 |
def list_certificates_with_backoff(self, statuses=None): |
| 66 |
paginator = self.client.get_paginator("list_certificates") |
| 67 |
# `list_certificates` requires explicit key type filter, or it returns only RSA_2048 certificates |
| 68 |
kwargs = { |
| 69 |
"Includes": { |
| 70 |
"keyTypes": [ |
| 71 |
"RSA_1024", |
| 72 |
"RSA_2048", |
| 73 |
"RSA_3072", |
| 74 |
"RSA_4096", |
| 75 |
"EC_prime256v1", |
| 76 |
"EC_secp384r1", |
| 77 |
"EC_secp521r1", |
| 78 |
], |
| 79 |
}, |
| 80 |
} |
| 81 |
if statuses: |
| 82 |
kwargs["CertificateStatuses"] = statuses |
| 83 |
return paginator.paginate(**kwargs).build_full_result()["CertificateSummaryList"] |
| 84 |
|
| 85 |
@acm_catch_boto_exception |
| 86 |
@AWSRetry.jittered_backoff( |
| 87 |
delay=5, catch_extra_error_codes=["RequestInProgressException", "ResourceNotFoundException"] |
| 88 |
) |
| 89 |
def get_certificate_with_backoff(self, certificate_arn): |
| 90 |
response = self.client.get_certificate(CertificateArn=certificate_arn) |
| 91 |
# strip out response metadata |
| 92 |
return {"Certificate": response["Certificate"], "CertificateChain": response["CertificateChain"]} |
| 93 |
|
| 94 |
@acm_catch_boto_exception |
| 95 |
@AWSRetry.jittered_backoff( |
| 96 |
delay=5, catch_extra_error_codes=["RequestInProgressException", "ResourceNotFoundException"] |
| 97 |
) |
| 98 |
def describe_certificate_with_backoff(self, certificate_arn): |
| 99 |
return self.client.describe_certificate(CertificateArn=certificate_arn)["Certificate"] |
| 100 |
|
| 101 |
@acm_catch_boto_exception |
| 102 |
@AWSRetry.jittered_backoff( |
| 103 |
delay=5, catch_extra_error_codes=["RequestInProgressException", "ResourceNotFoundException"] |
| 104 |
) |
| 105 |
def list_certificate_tags_with_backoff(self, certificate_arn): |
| 106 |
return self.client.list_tags_for_certificate(CertificateArn=certificate_arn)["Tags"] |
| 107 |
|
| 108 |
@acm_catch_boto_exception |
| 109 |
@AWSRetry.jittered_backoff(delay=5, catch_extra_error_codes=["RequestInProgressException"]) |
| 110 |
def import_certificate_with_backoff(self, certificate, private_key, certificate_chain, arn): |
| 111 |
params = {"Certificate": to_bytes(certificate), "PrivateKey": to_bytes(private_key)} |
| 112 |
if arn: |
| 113 |
params["CertificateArn"] = arn |
| 114 |
if certificate_chain: |
| 115 |
params["CertificateChain"] = certificate_chain |
| 116 |
|
| 117 |
return self.client.import_certificate(**params)["CertificateArn"] |
| 118 |
|
| 119 |
# Tags are a normal Ansible style dict |
| 120 |
# {'Key':'Value'} |
| 121 |
@AWSRetry.jittered_backoff( |
| 122 |
delay=5, catch_extra_error_codes=["RequestInProgressException", "ResourceNotFoundException"] |
| 123 |
) |
| 124 |
def tag_certificate_with_backoff(self, arn, tags): |
| 125 |
aws_tags = ansible_dict_to_boto3_tag_list(tags) |
| 126 |
self.client.add_tags_to_certificate(CertificateArn=arn, Tags=aws_tags) |
| 127 |
|
| 128 |
def _match_tags(self, ref_tags, cert_tags): |
| 129 |
if ref_tags is None: |
| 130 |
return True |
| 131 |
try: |
| 132 |
return all(k in cert_tags for k in ref_tags) and all(cert_tags.get(k) == ref_tags[k] for k in ref_tags) |
| 133 |
except (TypeError, AttributeError) as e: |
| 134 |
self.module.fail_json_aws(e, msg="ACM tag filtering err") |
| 135 |
|
| 136 |
def delete_certificate(self, *args, arn=None): |
| 137 |
# hacking for backward compatibility |
| 138 |
if arn is None: |
| 139 |
if len(args) < 3: |
| 140 |
self.module.fail_json(msg="Missing required certificate arn to delete.") |
| 141 |
arn = args[2] |
| 142 |
error = f"Couldn't delete certificate {arn}" |
| 143 |
self.delete_certificate_with_backoff(arn, module=self.module, error=error) |
| 144 |
|
| 145 |
def get_certificates(self, *args, domain_name=None, statuses=None, arn=None, only_tags=None, **kwargs): |
| 146 |
""" |
| 147 |
Returns a list of certificates |
| 148 |
if domain_name is specified, returns only certificates with that domain |
| 149 |
if an ARN is specified, returns only that certificate |
| 150 |
only_tags is a dict, e.g. {'key':'value'}. If specified this function will return |
| 151 |
only certificates which contain all those tags (key exists, value matches). |
| 152 |
""" |
| 153 |
all_certificates = self.list_certificates_with_backoff( |
| 154 |
statuses=statuses, module=self.module, error="Couldn't obtain certificates" |
| 155 |
) |
| 156 |
|
| 157 |
def _filter_certificate(cert): |
| 158 |
if domain_name and cert["DomainName"] != domain_name: |
| 159 |
return False |
| 160 |
if arn and cert["CertificateArn"] != arn: |
| 161 |
return False |
| 162 |
return True |
| 163 |
|
| 164 |
certificates = list(filter(_filter_certificate, all_certificates)) |
| 165 |
|
| 166 |
results = [] |
| 167 |
for certificate in certificates: |
| 168 |
cert_data = self.describe_certificate_with_backoff( |
| 169 |
certificate["CertificateArn"], |
| 170 |
module=self.module, |
| 171 |
error=f"Couldn't obtain certificate metadata for domain {certificate['DomainName']}", |
| 172 |
ignore_error_codes=["ResourceNotFoundException"], |
| 173 |
) |
| 174 |
if cert_data is None: |
| 175 |
continue |
| 176 |
|
| 177 |
# in some states, ACM resources do not have a corresponding cert |
| 178 |
if cert_data["Status"] not in ("PENDING_VALIDATION", "VALIDATION_TIMED_OUT", "FAILED"): |
| 179 |
cert_info = self.get_certificate_with_backoff( |
| 180 |
certificate["CertificateArn"], |
| 181 |
module=self.module, |
| 182 |
error=f"Couldn't obtain certificate data for domain {certificate['DomainName']}", |
| 183 |
ignore_error_codes=["ResourceNotFoundException"], |
| 184 |
) |
| 185 |
if cert_info is None: |
| 186 |
continue |
| 187 |
cert_data.update(cert_info) |
| 188 |
|
| 189 |
cert_data = camel_dict_to_snake_dict(cert_data) |
| 190 |
tags = self.list_certificate_tags_with_backoff( |
| 191 |
certificate["CertificateArn"], |
| 192 |
module=self.module, |
| 193 |
error=f"Couldn't obtain tags for domain {certificate['DomainName']}", |
| 194 |
ignore_error_codes=["ResourceNotFoundException"], |
| 195 |
) |
| 196 |
if tags is None: |
| 197 |
continue |
| 198 |
|
| 199 |
tags = boto3_tag_list_to_ansible_dict(tags) |
| 200 |
if not self._match_tags(only_tags, tags): |
| 201 |
continue |
| 202 |
cert_data["tags"] = tags |
| 203 |
results.append(cert_data) |
| 204 |
return results |
| 205 |
|
| 206 |
def get_domain_of_cert(self, arn, **kwargs): |
| 207 |
""" |
| 208 |
returns the domain name of a certificate (encoded in the public cert) |
| 209 |
for a given ARN A cert with that ARN must already exist |
| 210 |
""" |
| 211 |
if arn is None: |
| 212 |
self.module.fail_json(msg="Internal error with ACM domain fetching, no certificate ARN specified") |
| 213 |
error = f"Couldn't obtain certificate data for arn {arn}" |
| 214 |
cert_data = self.describe_certificate_with_backoff(certificate_arn=arn, module=self.module, error=error) |
| 215 |
return cert_data["DomainName"] |
| 216 |
|
| 217 |
def import_certificate(self, *args, certificate, private_key, arn=None, certificate_chain=None, tags=None): |
| 218 |
original_arn = arn |
| 219 |
|
| 220 |
# upload cert |
| 221 |
params = { |
| 222 |
"certificate": certificate, |
| 223 |
"private_key": private_key, |
| 224 |
"certificate_chain": certificate_chain, |
| 225 |
"arn": arn, |
| 226 |
"module": self.module, |
| 227 |
"error": "Couldn't upload new certificate", |
| 228 |
} |
| 229 |
arn = self.import_certificate_with_backoff(**params) |
| 230 |
if original_arn and (arn != original_arn): |
| 231 |
# I'm not sure whether the API guarentees that the ARN will not change |
| 232 |
# I'm failing just in case. |
| 233 |
# If I'm wrong, I'll catch it in the integration tests. |
| 234 |
self.module.fail_json(msg=f"ARN changed with ACM update, from {original_arn} to {arn}") |
| 235 |
|
| 236 |
# tag that cert |
| 237 |
try: |
| 238 |
self.tag_certificate_with_backoff(arn, tags) |
| 239 |
except (BotoCoreError, ClientError) as e: |
| 240 |
try: |
| 241 |
self.delete_certificate_with_backoff(arn) |
| 242 |
except (BotoCoreError, ClientError): |
| 243 |
self.module.warn( |
| 244 |
f"Certificate {arn} exists, and is not tagged. So Ansible will not see it on the next run." |
| 245 |
) |
| 246 |
self.module.fail_json_aws(e, msg=f"Couldn't tag certificate {arn}, couldn't delete it either") |
| 247 |
self.module.fail_json_aws(e, msg=f"Couldn't tag certificate {arn}") |
| 248 |
|
| 249 |
return arn |