コード例 #1
0
 def __init__(self, module):
     self.rest = DigitalOceanHelper(module)
     self.module = module
     # Pop these values so we don't include them in the POST data
     self.module.params.pop("oauth_token")
     self.return_kubeconfig = self.module.params.pop("return_kubeconfig")
     self.cluster_id = None
コード例 #2
0
def core(module):
    snapshot_type = module.params['snapshot_type']

    rest = DigitalOceanHelper(module)

    base_url = 'snapshots?'
    snapshot = []

    if snapshot_type == 'by_id':
        base_url += "/{0}".format(module.params.get('snapshot_id'))
        response = rest.get(base_url)
        status_code = response.status_code

        if status_code != 200:
            module.fail_json(
                msg="Failed to fetch snapshot information due to error : %s" %
                response.json['message'])

        snapshot.extend(response.json["snapshot"])
    else:
        if snapshot_type == 'droplet':
            base_url += "resource_type=droplet&"
        elif snapshot_type == 'volume':
            base_url += "resource_type=volume&"

        snapshot = rest.get_paginated_data(base_url=base_url,
                                           data_key_name='snapshots')
    module.exit_json(changed=False, data=snapshot)
コード例 #3
0
 def __init__(self, module):
     self.rest = DigitalOceanHelper(module)
     self.module = module
     self.wait = self.module.params.pop("wait", True)
     self.wait_timeout = self.module.params.pop("wait_timeout", 120)
     self.unique_name = self.module.params.pop("unique_name", False)
     # pop the oauth token so we don't include it in the POST data
     self.module.params.pop("oauth_token")
     self.id = None
     self.name = None
     self.size = None
     self.status = None
     if self.module.params.get("project"):
         # only load for non-default project assignments
         self.projects = DigitalOceanProjects(module, self.rest)
     self.firewalls = self.get_firewalls()
     self.sleep_interval = self.module.params.pop("sleep_interval", 10)
     if self.wait:
         if self.sleep_interval > self.wait_timeout:
             self.module.fail_json(
                 msg="Sleep interval {0} should be less than {1}".format(
                     self.sleep_interval, self.wait_timeout))
         if self.sleep_interval <= 0:
             self.module.fail_json(
                 msg="Sleep interval {0} should be greater than zero".
                 format(self.sleep_interval))
class DOMonitoringAlertsInfo(object):
    def __init__(self, module):
        self.rest = DigitalOceanHelper(module)
        self.module = module
        # Pop these values so we don't include them in the POST data
        self.module.params.pop("oauth_token")

    def get_alerts(self):
        alerts = self.rest.get_paginated_data(base_url="monitoring/alerts?",
                                              data_key_name="policies")
        self.module.exit_json(
            changed=False,
            data=alerts,
        )

    def get_alert(self, uuid):
        alerts = self.rest.get_paginated_data(base_url="monitoring/alerts?",
                                              data_key_name="policies")
        for alert in alerts:
            alert_uuid = alert.get("uuid", None)
            if alert_uuid is not None:
                if alert_uuid == uuid:
                    self.module.exit_json(
                        changed=False,
                        data=alert,
                    )
            else:
                self.module.fail_json(
                    changed=False,
                    msg="Unexpected error; please file a bug: get_alert")
        self.module.exit_json(
            changed=False,
            data=[],
        )
コード例 #5
0
def run(module):
    rest = DigitalOceanHelper(module)

    if module.params["id"]:
        response = rest.get("projects/{0}".format(module.params["id"]))
        if response.status_code != 200:
            module.fail_json(
                msg="Failed to fetch 'projects' information due to error: %s" %
                response.json["message"])
    else:
        response = rest.get_paginated_data(base_url="projects?",
                                           data_key_name="projects")

    if module.params["id"]:
        data = [response.json["project"]]
    elif module.params["name"]:
        data = [d for d in response if d["name"] == module.params["name"]]
        if not data:
            module.fail_json(
                msg=
                "Failed to fetch 'projects' information due to error: Unable to find project with name %s"
                % module.params["name"])
    else:
        data = response

    module.exit_json(changed=False, data=data)
 def __init__(self, module):
     self.module = module
     self.rest = DigitalOceanHelper(module)
     # pop the oauth token so we don't include it in the POST data
     self.module.params.pop("oauth_token")
     self.id = None
     self.name = None
コード例 #7
0
def core(module):
    snapshot_type = module.params["snapshot_type"]

    rest = DigitalOceanHelper(module)

    base_url = "snapshots"
    snapshot = []

    if snapshot_type == "by_id":
        base_url += "/{0}".format(module.params.get("snapshot_id"))
        response = rest.get(base_url)
        status_code = response.status_code

        if status_code != 200:
            module.fail_json(
                msg="Failed to fetch snapshot information due to error : %s"
                % response.json["message"]
            )

        snapshot.extend(response.json["snapshots"])
    else:
        if snapshot_type == "droplet":
            base_url += "?resource_type=droplet&"
        elif snapshot_type == "volume":
            base_url += "?resource_type=volume&"
        else:
            base_url += "?"

        snapshot = rest.get_paginated_data(base_url=base_url, data_key_name="snapshots")
    module.exit_json(changed=False, data=snapshot)
コード例 #8
0
def core(module):
    domain_name = module.params.get('domain_name', None)
    rest = DigitalOceanHelper(module)
    domain_results = []

    if domain_name is not None:
        response = rest.get("domains/%s" % domain_name)
        status_code = response.status_code

        if status_code != 200:
            module.fail_json(msg="Failed to retrieve domain for DigitalOcean")

        resp_json = response.json
        domains = [resp_json['domain']]
    else:
        domains = rest.get_paginated_data(base_url="domains?",
                                          data_key_name='domains')

    for temp_domain in domains:
        temp_domain_dict = {
            "name": temp_domain['name'],
            "ttl": temp_domain['ttl'],
            "zone_file": temp_domain['zone_file'],
            "domain_records": list(),
        }

        base_url = "domains/%s/records?" % temp_domain['name']

        temp_domain_dict["domain_records"] = rest.get_paginated_data(
            base_url=base_url, data_key_name='domain_records')
        domain_results.append(temp_domain_dict)

    module.exit_json(changed=False, data=domain_results)
コード例 #9
0
 def __init__(self, module):
     self.rest = DigitalOceanHelper(module)
     self.module = module
     # pop the oauth token so we don't include it in the POST data
     self.module.params.pop("oauth_token")
     self.name = self.module.params.pop("name", "")
     self.members = self.module.params.pop("members", False)
コード例 #10
0
 def __init__(self, module):
     self.rest = DigitalOceanHelper(module)
     self.module = module
     self.wait = self.module.params.pop('wait', True)
     self.wait_timeout = self.module.params.pop('wait_timeout', 120)
     self.unique_name = self.module.params.pop('unique_name', False)
     # pop the oauth token so we don't include it in the POST data
     self.module.params.pop('oauth_token')
コード例 #11
0
def core(module):
    rest = DigitalOceanHelper(module)

    base_url = 'regions?'
    regions = rest.get_paginated_data(base_url=base_url,
                                      data_key_name='regions')

    module.exit_json(changed=False, data=regions)
def run(module):
    rest = DigitalOceanHelper(module)

    response = rest.get("customers/my/balance")
    if response.status_code != 200:
        module.fail_json(msg="Failed to fetch 'customers/my/balance' information due to error : %s" % response.json['message'])

    module.exit_json(changed=False, data=response.json)
コード例 #13
0
def core(module):
    rest = DigitalOceanHelper(module)

    response = rest.get('sizes')
    if response.status_code != 200:
        module.fail_json(msg="Failed to fetch 'sizes' information due to error : %s" % response.json['message'])

    module.exit_json(changed=False, data=response.json['sizes'])
コード例 #14
0
class DOVPCInfo(object):
    def __init__(self, module):
        self.rest = DigitalOceanHelper(module)
        self.module = module
        # pop the oauth token so we don't include it in the POST data
        self.module.params.pop("oauth_token")
        self.name = self.module.params.pop("name", "")
        self.members = self.module.params.pop("members", False)

    def get_by_name(self):
        page = 1
        while page is not None:
            response = self.rest.get("vpcs?page={0}".format(page))
            json_data = response.json
            if response.status_code == 200:
                for vpc in json_data["vpcs"]:
                    if vpc.get("name", None) == self.name:
                        return vpc
                if ("links" in json_data and "pages" in json_data["links"]
                        and "next" in json_data["links"]["pages"]):
                    page += 1
                else:
                    page = None
        return None

    def get(self):
        if self.module.check_mode:
            return self.module.exit_json(changed=False)

        if not self.members:
            base_url = "vpcs?"
            vpcs = self.rest.get_paginated_data(base_url=base_url,
                                                data_key_name="vpcs")
            self.module.exit_json(changed=False, data=vpcs)
        else:
            vpc = self.get_by_name()
            if vpc is not None:
                vpc_id = vpc.get("id", None)
                if vpc_id is not None:
                    response = self.rest.get("vpcs/{0}/members".format(vpc_id))
                    json = response.json
                    if response.status_code != 200:
                        self.module.fail_json(
                            msg="Failed to find VPC named {0}: {1}".format(
                                self.name, json["message"]))
                    else:
                        self.module.exit_json(changed=False, data=json)
                else:
                    self.module.fail_json(
                        changed=False,
                        msg="Unexpected error, please file a bug")
            else:
                self.module.fail_json(
                    changed=False,
                    msg="Could not find a VPC named {0}".format(self.name),
                )
コード例 #15
0
def core(module):
    state = module.params['state']
    name = module.params['name']

    rest = DigitalOceanHelper(module)

    results = dict(changed=False)

    response = rest.get('certificates')
    status_code = response.status_code
    resp_json = response.json

    if status_code != 200:
        module.fail_json(msg="Failed to retrieve certificates for DigitalOcean")

    if state == 'present':
        for cert in resp_json['certificates']:
            if cert['name'] == name:
                module.fail_json(msg="Certificate name %s already exists" % name)

        # Certificate does not exist, let us create it
        cert_data = dict(name=name,
                         private_key=module.params['private_key'],
                         leaf_certificate=module.params['leaf_certificate'])

        if module.params['certificate_chain'] is not None:
            cert_data.update(certificate_chain=module.params['certificate_chain'])

        response = rest.post("certificates", data=cert_data)
        status_code = response.status_code
        if status_code == 500:
            module.fail_json(msg="Failed to upload certificates as the certificates are malformed.")

        resp_json = response.json
        if status_code == 201:
            results.update(changed=True, response=resp_json)
        elif status_code == 422:
            results.update(changed=False, response=resp_json)

    elif state == 'absent':
        cert_id_del = None
        for cert in resp_json['certificates']:
            if cert['name'] == name:
                cert_id_del = cert['id']

        if cert_id_del is not None:
            url = "certificates/{0}".format(cert_id_del)
            response = rest.delete(url)
            if response.status_code == 204:
                results.update(changed=True)
            else:
                results.update(changed=False)
        else:
            module.fail_json(msg="Failed to find certificate %s" % name)

    module.exit_json(**results)
コード例 #16
0
def core(module):
    rest = DigitalOceanHelper(module)

    response = rest.get("account/keys")
    status_code = response.status_code
    json = response.json
    if status_code == 200:
        module.exit_json(changed=False, ansible_facts=json)
    else:
        module.fail_json(msg='Error fetching facts [{0}: {1}]'.format(
            status_code, response.json['message']))
コード例 #17
0
 def __init__(self, module):
     self.rest = DigitalOceanHelper(module)
     self.module = module
     self.id = None
     self.name = self.module.params.get("name")
     self.region = self.module.params.get("region")
     self.updates = []
     # Pop these values so we don't include them in the POST data
     self.module.params.pop("oauth_token")
     self.wait = self.module.params.pop("wait", True)
     self.wait_timeout = self.module.params.pop("wait_timeout", 600)
コード例 #18
0
 def __init__(self, module):
     self.rest = DigitalOceanHelper(module)
     self.module = module
     # pop the oauth token so we don't include it in the POST data
     self.module.params.pop("oauth_token")
     self.name = module.params.get("name", None)
     self.description = module.params.get("description", None)
     self.default = module.params.get("default", False)
     self.region = module.params.get("region", None)
     self.ip_range = module.params.get("ip_range", None)
     self.vpc_id = module.params.get("vpc_id", None)
コード例 #19
0
 def __init__(self, module):
     self.rest = DigitalOceanHelper(module)
     self.module = module
     # pop the oauth token so we don't include it in the POST data
     self.module.params.pop("oauth_token")
     self.id = None
     self.name = None
     self.purpose = None
     self.description = None
     self.environment = None
     self.is_default = None
コード例 #20
0
 def __init__(self, module):
     self.rest = DigitalOceanHelper(module)
     self.module = module
     self.wait = self.module.params.pop("wait", True)
     self.wait_timeout = self.module.params.pop("wait_timeout", 120)
     self.unique_name = self.module.params.pop("unique_name", False)
     # pop the oauth token so we don't include it in the POST data
     self.module.params.pop("oauth_token")
     self.id = None
     self.name = None
     self.size = None
     self.status = None
コード例 #21
0
 def __init__(self, module):
     self.rest = DigitalOceanHelper(module)
     self.module = module
     self.wait = self.module.params.pop("wait", True)
     self.wait_timeout = self.module.params.pop("wait_timeout", 120)
     # pop the oauth token so we don't include it in the POST data
     self.module.params.pop("oauth_token")
     self.snapshot_type = module.params["snapshot_type"]
     self.snapshot_name = module.params["snapshot_name"]
     self.snapshot_tags = module.params["snapshot_tags"]
     self.snapshot_id = module.params["snapshot_id"]
     self.volume_id = module.params["volume_id"]
コード例 #22
0
def core(module):
    rest = DigitalOceanHelper(module)

    response = rest.get("account/keys")
    status_code = response.status_code
    json = response.json
    if status_code == 200:
        module.exit_json(changed=False, data=json['ssh_keys'])
    else:
        module.fail_json(
            msg='Error fetching SSH Key information [{0}: {1}]'.format(
                status_code, response.json['message']))
コード例 #23
0
def core(module):
    region_name = module.params.get("region_name", None)

    rest = DigitalOceanHelper(module)

    base_url = "volumes?"
    if region_name is not None:
        base_url += "region=%s&" % region_name

    volumes = rest.get_paginated_data(base_url=base_url,
                                      data_key_name="volumes")

    module.exit_json(changed=False, data=volumes)
 def __init__(self, module):
     self.rest = DigitalOceanHelper(module)
     self.module = module
     self.id = None
     self.name = self.module.params.get("name")
     self.region = self.module.params.get("region")
     self.updates = []
     # Pop these values so we don't include them in the POST data
     self.module.params.pop("oauth_token")
     self.wait = self.module.params.pop("wait", True)
     self.wait_timeout = self.module.params.pop("wait_timeout", 600)
     if self.module.params.get("project"):
         # only load for non-default project assignments
         self.projects = DigitalOceanProjects(module, self.rest)
def main():
    argument_spec = DigitalOceanHelper.digital_ocean_argument_spec()
    argument_spec.update(
        state=dict(choices=["present", "absent"], required=True),
        command=dict(choices=["create", "attach"], required=True),
        block_size=dict(type="int", required=False),
        volume_name=dict(type="str", required=True),
        description=dict(type="str"),
        region=dict(type="str", required=False),
        snapshot_id=dict(type="str", required=False),
        droplet_id=dict(type="int"),
        project_name=dict(type="str",
                          aliases=["project"],
                          required=False,
                          default=""),
    )

    module = AnsibleModule(argument_spec=argument_spec)

    try:
        handle_request(module)
    except DOBlockStorageException as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    except KeyError as e:
        module.fail_json(msg="Unable to load %s" % e,
                         exception=traceback.format_exc())
コード例 #26
0
def main():
    module = AnsibleModule(
        argument_spec=DigitalOceanHelper.digital_ocean_argument_spec(),
        supports_check_mode=True,
    )

    core(module)
コード例 #27
0
def main():

    argument_spec = DigitalOceanHelper.digital_ocean_argument_spec()
    argument_spec.update(
        state=dict(type="str", choices=["present"], default="present"),
        region=dict(type="str", aliases=["region_id"], required=True),
        aws_access_key_id=dict(
            type="str",
            aliases=["AWS_ACCESS_KEY_ID"],
            fallback=(env_fallback, ["AWS_ACCESS_KEY_ID"]),
            required=True,
            no_log=True,
        ),
        aws_secret_access_key=dict(
            type="str",
            aliases=["AWS_SECRET_ACCESS_KEY"],
            fallback=(env_fallback, ["AWS_SECRET_ACCESS_KEY"]),
            required=True,
            no_log=True,
        ),
    )
    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)

    if not HAS_BOTO3:
        module.fail_json(msg=missing_required_lib("boto3"))

    run(module)
コード例 #28
0
def main():
    argument_spec = DigitalOceanHelper.digital_ocean_argument_spec()
    argument_spec.update(
        state=dict(choices=["present"], default="present"),
        name=dict(type="str", aliases=["domain", "domain_name"],
                  required=True),
        record_id=dict(type="int"),
        type=dict(
            type="str",
            choices=["A", "AAAA", "CNAME", "MX", "TXT", "SRV", "NS", "CAA"],
        ),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    manager = DigitalOceanDomainRecordManager(module)

    # verify credentials and domain
    manager.check_credentials()

    state = module.params.get("state")
    record_id = module.params.get("record_id")

    if state == "present":
        if record_id:
            changed, result = manager.get_records_by_id()
        else:
            changed, result = manager.get_records()
        module.exit_json(changed=changed, data={"records": result})
コード例 #29
0
def core(module):
    image_type = module.params['image_type']

    rest = DigitalOceanHelper(module)

    base_url = 'images?'
    if image_type == 'distribution':
        base_url += "type=distribution&"
    elif image_type == 'application':
        base_url += "type=application&"
    elif image_type == 'private':
        base_url += "private=true&"

    images = rest.get_paginated_data(base_url=base_url, data_key_name='images')

    module.exit_json(changed=False, data=images)
コード例 #30
0
def main():
    argument_spec = DigitalOceanHelper.digital_ocean_argument_spec()
    argument_spec.update(
        snapshot_type=dict(
            type="str",
            required=False,
            choices=["all", "droplet", "volume", "by_id"],
            default="all",
        ),
        snapshot_id=dict(type="str", required=False),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ["snapshot_type", "by_id", ["snapshot_id"]],
        ],
    )
    if module._name in (
        "digital_ocean_snapshot_facts",
        "community.digitalocean.digital_ocean_snapshot_facts",
    ):
        module.deprecate(
            "The 'digital_ocean_snapshot_facts' module has been renamed to 'digital_ocean_snapshot_info'",
            version="2.0.0",
            collection_name="community.digitalocean",
        )  # was Ansible 2.13

    try:
        core(module)
    except Exception as e:
        module.fail_json(msg=to_native(e), exception=format_exc())