1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-04-17 01:11:28 +00:00

Initial commit

This commit is contained in:
Ansible Core Team 2020-03-09 09:11:07 +00:00
commit aebc1b03fd
4861 changed files with 812621 additions and 0 deletions

View file

@ -0,0 +1,575 @@
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: oneandone_firewall_policy
short_description: Configure 1&1 firewall policy.
description:
- Create, remove, reconfigure, update firewall policies.
This module has a dependency on 1and1 >= 1.0
options:
state:
description:
- Define a firewall policy state to create, remove, or update.
required: false
default: 'present'
choices: [ "present", "absent", "update" ]
auth_token:
description:
- Authenticating API token provided by 1&1.
required: true
api_url:
description:
- Custom API URL. Overrides the
ONEANDONE_API_URL environment variable.
required: false
name:
description:
- Firewall policy name used with present state. Used as identifier (id or name) when used with absent state.
maxLength=128
required: true
firewall_policy:
description:
- The identifier (id or name) of the firewall policy used with update state.
required: true
rules:
description:
- A list of rules that will be set for the firewall policy.
Each rule must contain protocol parameter, in addition to three optional parameters
(port_from, port_to, and source)
add_server_ips:
description:
- A list of server identifiers (id or name) to be assigned to a firewall policy.
Used in combination with update state.
required: false
remove_server_ips:
description:
- A list of server IP ids to be unassigned from a firewall policy. Used in combination with update state.
required: false
add_rules:
description:
- A list of rules that will be added to an existing firewall policy.
It is syntax is the same as the one used for rules parameter. Used in combination with update state.
required: false
remove_rules:
description:
- A list of rule ids that will be removed from an existing firewall policy. Used in combination with update state.
required: false
description:
description:
- Firewall policy description. maxLength=256
required: false
wait:
description:
- wait for the instance to be in state 'running' before returning
required: false
default: "yes"
type: bool
wait_timeout:
description:
- how long before wait gives up, in seconds
default: 600
wait_interval:
description:
- Defines the number of seconds to wait when using the _wait_for methods
default: 5
requirements:
- "1and1"
- "python >= 2.6"
author:
- "Amel Ajdinovic (@aajdinov)"
- "Ethan Devenport (@edevenport)"
'''
EXAMPLES = '''
# Provisioning example. Create and destroy a firewall policy.
- oneandone_firewall_policy:
auth_token: oneandone_private_api_key
name: ansible-firewall-policy
description: Testing creation of firewall policies with ansible
rules:
-
protocol: TCP
port_from: 80
port_to: 80
source: 0.0.0.0
wait: true
wait_timeout: 500
- oneandone_firewall_policy:
auth_token: oneandone_private_api_key
state: absent
name: ansible-firewall-policy
# Update a firewall policy.
- oneandone_firewall_policy:
auth_token: oneandone_private_api_key
state: update
firewall_policy: ansible-firewall-policy
name: ansible-firewall-policy-updated
description: Testing creation of firewall policies with ansible - updated
# Add server to a firewall policy.
- oneandone_firewall_policy:
auth_token: oneandone_private_api_key
firewall_policy: ansible-firewall-policy-updated
add_server_ips:
- server_identifier (id or name)
- server_identifier #2 (id or name)
wait: true
wait_timeout: 500
state: update
# Remove server from a firewall policy.
- oneandone_firewall_policy:
auth_token: oneandone_private_api_key
firewall_policy: ansible-firewall-policy-updated
remove_server_ips:
- B2504878540DBC5F7634EB00A07C1EBD (server's IP id)
wait: true
wait_timeout: 500
state: update
# Add rules to a firewall policy.
- oneandone_firewall_policy:
auth_token: oneandone_private_api_key
firewall_policy: ansible-firewall-policy-updated
description: Adding rules to an existing firewall policy
add_rules:
-
protocol: TCP
port_from: 70
port_to: 70
source: 0.0.0.0
-
protocol: TCP
port_from: 60
port_to: 60
source: 0.0.0.0
wait: true
wait_timeout: 500
state: update
# Remove rules from a firewall policy.
- oneandone_firewall_policy:
auth_token: oneandone_private_api_key
firewall_policy: ansible-firewall-policy-updated
remove_rules:
- rule_id #1
- rule_id #2
- ...
wait: true
wait_timeout: 500
state: update
'''
RETURN = '''
firewall_policy:
description: Information about the firewall policy that was processed
type: dict
sample: '{"id": "92B74394A397ECC3359825C1656D67A6", "name": "Default Policy"}'
returned: always
'''
import os
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.general.plugins.module_utils.oneandone import (
get_firewall_policy,
get_server,
OneAndOneResources,
wait_for_resource_creation_completion
)
HAS_ONEANDONE_SDK = True
try:
import oneandone.client
except ImportError:
HAS_ONEANDONE_SDK = False
def _check_mode(module, result):
if module.check_mode:
module.exit_json(
changed=result
)
def _add_server_ips(module, oneandone_conn, firewall_id, server_ids):
"""
Assigns servers to a firewall policy.
"""
try:
attach_servers = []
for _server_id in server_ids:
server = get_server(oneandone_conn, _server_id, True)
attach_server = oneandone.client.AttachServer(
server_id=server['id'],
server_ip_id=next(iter(server['ips'] or []), None)['id']
)
attach_servers.append(attach_server)
if module.check_mode:
if attach_servers:
return True
return False
firewall_policy = oneandone_conn.attach_server_firewall_policy(
firewall_id=firewall_id,
server_ips=attach_servers)
return firewall_policy
except Exception as e:
module.fail_json(msg=str(e))
def _remove_firewall_server(module, oneandone_conn, firewall_id, server_ip_id):
"""
Unassigns a server/IP from a firewall policy.
"""
try:
if module.check_mode:
firewall_server = oneandone_conn.get_firewall_server(
firewall_id=firewall_id,
server_ip_id=server_ip_id)
if firewall_server:
return True
return False
firewall_policy = oneandone_conn.remove_firewall_server(
firewall_id=firewall_id,
server_ip_id=server_ip_id)
return firewall_policy
except Exception as e:
module.fail_json(msg=str(e))
def _add_firewall_rules(module, oneandone_conn, firewall_id, rules):
"""
Adds new rules to a firewall policy.
"""
try:
firewall_rules = []
for rule in rules:
firewall_rule = oneandone.client.FirewallPolicyRule(
protocol=rule['protocol'],
port_from=rule['port_from'],
port_to=rule['port_to'],
source=rule['source'])
firewall_rules.append(firewall_rule)
if module.check_mode:
firewall_policy_id = get_firewall_policy(oneandone_conn, firewall_id)
if (firewall_rules and firewall_policy_id):
return True
return False
firewall_policy = oneandone_conn.add_firewall_policy_rule(
firewall_id=firewall_id,
firewall_policy_rules=firewall_rules
)
return firewall_policy
except Exception as e:
module.fail_json(msg=str(e))
def _remove_firewall_rule(module, oneandone_conn, firewall_id, rule_id):
"""
Removes a rule from a firewall policy.
"""
try:
if module.check_mode:
rule = oneandone_conn.get_firewall_policy_rule(
firewall_id=firewall_id,
rule_id=rule_id)
if rule:
return True
return False
firewall_policy = oneandone_conn.remove_firewall_rule(
firewall_id=firewall_id,
rule_id=rule_id
)
return firewall_policy
except Exception as e:
module.fail_json(msg=str(e))
def update_firewall_policy(module, oneandone_conn):
"""
Updates a firewall policy based on input arguments.
Firewall rules and server ips can be added/removed to/from
firewall policy. Firewall policy name and description can be
updated as well.
module : AnsibleModule object
oneandone_conn: authenticated oneandone object
"""
try:
firewall_policy_id = module.params.get('firewall_policy')
name = module.params.get('name')
description = module.params.get('description')
add_server_ips = module.params.get('add_server_ips')
remove_server_ips = module.params.get('remove_server_ips')
add_rules = module.params.get('add_rules')
remove_rules = module.params.get('remove_rules')
changed = False
firewall_policy = get_firewall_policy(oneandone_conn, firewall_policy_id, True)
if firewall_policy is None:
_check_mode(module, False)
if name or description:
_check_mode(module, True)
firewall_policy = oneandone_conn.modify_firewall(
firewall_id=firewall_policy['id'],
name=name,
description=description)
changed = True
if add_server_ips:
if module.check_mode:
_check_mode(module, _add_server_ips(module,
oneandone_conn,
firewall_policy['id'],
add_server_ips))
firewall_policy = _add_server_ips(module, oneandone_conn, firewall_policy['id'], add_server_ips)
changed = True
if remove_server_ips:
chk_changed = False
for server_ip_id in remove_server_ips:
if module.check_mode:
chk_changed |= _remove_firewall_server(module,
oneandone_conn,
firewall_policy['id'],
server_ip_id)
_remove_firewall_server(module,
oneandone_conn,
firewall_policy['id'],
server_ip_id)
_check_mode(module, chk_changed)
firewall_policy = get_firewall_policy(oneandone_conn, firewall_policy['id'], True)
changed = True
if add_rules:
firewall_policy = _add_firewall_rules(module,
oneandone_conn,
firewall_policy['id'],
add_rules)
_check_mode(module, firewall_policy)
changed = True
if remove_rules:
chk_changed = False
for rule_id in remove_rules:
if module.check_mode:
chk_changed |= _remove_firewall_rule(module,
oneandone_conn,
firewall_policy['id'],
rule_id)
_remove_firewall_rule(module,
oneandone_conn,
firewall_policy['id'],
rule_id)
_check_mode(module, chk_changed)
firewall_policy = get_firewall_policy(oneandone_conn, firewall_policy['id'], True)
changed = True
return (changed, firewall_policy)
except Exception as e:
module.fail_json(msg=str(e))
def create_firewall_policy(module, oneandone_conn):
"""
Create a new firewall policy.
module : AnsibleModule object
oneandone_conn: authenticated oneandone object
"""
try:
name = module.params.get('name')
description = module.params.get('description')
rules = module.params.get('rules')
wait = module.params.get('wait')
wait_timeout = module.params.get('wait_timeout')
wait_interval = module.params.get('wait_interval')
firewall_rules = []
for rule in rules:
firewall_rule = oneandone.client.FirewallPolicyRule(
protocol=rule['protocol'],
port_from=rule['port_from'],
port_to=rule['port_to'],
source=rule['source'])
firewall_rules.append(firewall_rule)
firewall_policy_obj = oneandone.client.FirewallPolicy(
name=name,
description=description
)
_check_mode(module, True)
firewall_policy = oneandone_conn.create_firewall_policy(
firewall_policy=firewall_policy_obj,
firewall_policy_rules=firewall_rules
)
if wait:
wait_for_resource_creation_completion(
oneandone_conn,
OneAndOneResources.firewall_policy,
firewall_policy['id'],
wait_timeout,
wait_interval)
firewall_policy = get_firewall_policy(oneandone_conn, firewall_policy['id'], True) # refresh
changed = True if firewall_policy else False
_check_mode(module, False)
return (changed, firewall_policy)
except Exception as e:
module.fail_json(msg=str(e))
def remove_firewall_policy(module, oneandone_conn):
"""
Removes a firewall policy.
module : AnsibleModule object
oneandone_conn: authenticated oneandone object
"""
try:
fp_id = module.params.get('name')
firewall_policy_id = get_firewall_policy(oneandone_conn, fp_id)
if module.check_mode:
if firewall_policy_id is None:
_check_mode(module, False)
_check_mode(module, True)
firewall_policy = oneandone_conn.delete_firewall(firewall_policy_id)
changed = True if firewall_policy else False
return (changed, {
'id': firewall_policy['id'],
'name': firewall_policy['name']
})
except Exception as e:
module.fail_json(msg=str(e))
def main():
module = AnsibleModule(
argument_spec=dict(
auth_token=dict(
type='str',
default=os.environ.get('ONEANDONE_AUTH_TOKEN')),
api_url=dict(
type='str',
default=os.environ.get('ONEANDONE_API_URL')),
name=dict(type='str'),
firewall_policy=dict(type='str'),
description=dict(type='str'),
rules=dict(type='list', default=[]),
add_server_ips=dict(type='list', default=[]),
remove_server_ips=dict(type='list', default=[]),
add_rules=dict(type='list', default=[]),
remove_rules=dict(type='list', default=[]),
wait=dict(type='bool', default=True),
wait_timeout=dict(type='int', default=600),
wait_interval=dict(type='int', default=5),
state=dict(type='str', default='present', choices=['present', 'absent', 'update']),
),
supports_check_mode=True
)
if not HAS_ONEANDONE_SDK:
module.fail_json(msg='1and1 required for this module')
if not module.params.get('auth_token'):
module.fail_json(
msg='The "auth_token" parameter or ' +
'ONEANDONE_AUTH_TOKEN environment variable is required.')
if not module.params.get('api_url'):
oneandone_conn = oneandone.client.OneAndOneService(
api_token=module.params.get('auth_token'))
else:
oneandone_conn = oneandone.client.OneAndOneService(
api_token=module.params.get('auth_token'), api_url=module.params.get('api_url'))
state = module.params.get('state')
if state == 'absent':
if not module.params.get('name'):
module.fail_json(
msg="'name' parameter is required to delete a firewall policy.")
try:
(changed, firewall_policy) = remove_firewall_policy(module, oneandone_conn)
except Exception as e:
module.fail_json(msg=str(e))
elif state == 'update':
if not module.params.get('firewall_policy'):
module.fail_json(
msg="'firewall_policy' parameter is required to update a firewall policy.")
try:
(changed, firewall_policy) = update_firewall_policy(module, oneandone_conn)
except Exception as e:
module.fail_json(msg=str(e))
elif state == 'present':
for param in ('name', 'rules'):
if not module.params.get(param):
module.fail_json(
msg="%s parameter is required for new firewall policies." % param)
try:
(changed, firewall_policy) = create_firewall_policy(module, oneandone_conn)
except Exception as e:
module.fail_json(msg=str(e))
module.exit_json(changed=changed, firewall_policy=firewall_policy)
if __name__ == '__main__':
main()

View file

@ -0,0 +1,676 @@
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: oneandone_load_balancer
short_description: Configure 1&1 load balancer.
description:
- Create, remove, update load balancers.
This module has a dependency on 1and1 >= 1.0
options:
state:
description:
- Define a load balancer state to create, remove, or update.
required: false
default: 'present'
choices: [ "present", "absent", "update" ]
auth_token:
description:
- Authenticating API token provided by 1&1.
required: true
load_balancer:
description:
- The identifier (id or name) of the load balancer used with update state.
required: true
api_url:
description:
- Custom API URL. Overrides the
ONEANDONE_API_URL environment variable.
required: false
name:
description:
- Load balancer name used with present state. Used as identifier (id or name) when used with absent state.
maxLength=128
required: true
health_check_test:
description:
- Type of the health check. At the moment, HTTP is not allowed.
choices: [ "NONE", "TCP", "HTTP", "ICMP" ]
required: true
health_check_interval:
description:
- Health check period in seconds. minimum=5, maximum=300, multipleOf=1
required: true
health_check_path:
description:
- Url to call for checking. Required for HTTP health check. maxLength=1000
required: false
health_check_parse:
description:
- Regular expression to check. Required for HTTP health check. maxLength=64
required: false
persistence:
description:
- Persistence.
required: true
type: bool
persistence_time:
description:
- Persistence time in seconds. Required if persistence is enabled. minimum=30, maximum=1200, multipleOf=1
required: true
method:
description:
- Balancing procedure.
choices: [ "ROUND_ROBIN", "LEAST_CONNECTIONS" ]
required: true
datacenter:
description:
- ID or country code of the datacenter where the load balancer will be created.
default: US
choices: [ "US", "ES", "DE", "GB" ]
required: false
rules:
description:
- A list of rule objects that will be set for the load balancer. Each rule must contain protocol,
port_balancer, and port_server parameters, in addition to source parameter, which is optional.
required: true
description:
description:
- Description of the load balancer. maxLength=256
required: false
add_server_ips:
description:
- A list of server identifiers (id or name) to be assigned to a load balancer.
Used in combination with update state.
required: false
remove_server_ips:
description:
- A list of server IP ids to be unassigned from a load balancer. Used in combination with update state.
required: false
add_rules:
description:
- A list of rules that will be added to an existing load balancer.
It is syntax is the same as the one used for rules parameter. Used in combination with update state.
required: false
remove_rules:
description:
- A list of rule ids that will be removed from an existing load balancer. Used in combination with update state.
required: false
wait:
description:
- wait for the instance to be in state 'running' before returning
required: false
default: "yes"
type: bool
wait_timeout:
description:
- how long before wait gives up, in seconds
default: 600
wait_interval:
description:
- Defines the number of seconds to wait when using the _wait_for methods
default: 5
requirements:
- "1and1"
- "python >= 2.6"
author:
- Amel Ajdinovic (@aajdinov)
- Ethan Devenport (@edevenport)
'''
EXAMPLES = '''
# Provisioning example. Create and destroy a load balancer.
- oneandone_load_balancer:
auth_token: oneandone_private_api_key
name: ansible load balancer
description: Testing creation of load balancer with ansible
health_check_test: TCP
health_check_interval: 40
persistence: true
persistence_time: 1200
method: ROUND_ROBIN
datacenter: US
rules:
-
protocol: TCP
port_balancer: 80
port_server: 80
source: 0.0.0.0
wait: true
wait_timeout: 500
- oneandone_load_balancer:
auth_token: oneandone_private_api_key
name: ansible load balancer
wait: true
wait_timeout: 500
state: absent
# Update a load balancer.
- oneandone_load_balancer:
auth_token: oneandone_private_api_key
load_balancer: ansible load balancer
name: ansible load balancer updated
description: Testing the update of a load balancer with ansible
wait: true
wait_timeout: 500
state: update
# Add server to a load balancer.
- oneandone_load_balancer:
auth_token: oneandone_private_api_key
load_balancer: ansible load balancer updated
description: Adding server to a load balancer with ansible
add_server_ips:
- server identifier (id or name)
wait: true
wait_timeout: 500
state: update
# Remove server from a load balancer.
- oneandone_load_balancer:
auth_token: oneandone_private_api_key
load_balancer: ansible load balancer updated
description: Removing server from a load balancer with ansible
remove_server_ips:
- B2504878540DBC5F7634EB00A07C1EBD (server's ip id)
wait: true
wait_timeout: 500
state: update
# Add rules to a load balancer.
- oneandone_load_balancer:
auth_token: oneandone_private_api_key
load_balancer: ansible load balancer updated
description: Adding rules to a load balancer with ansible
add_rules:
-
protocol: TCP
port_balancer: 70
port_server: 70
source: 0.0.0.0
-
protocol: TCP
port_balancer: 60
port_server: 60
source: 0.0.0.0
wait: true
wait_timeout: 500
state: update
# Remove rules from a load balancer.
- oneandone_load_balancer:
auth_token: oneandone_private_api_key
load_balancer: ansible load balancer updated
description: Adding rules to a load balancer with ansible
remove_rules:
- rule_id #1
- rule_id #2
- ...
wait: true
wait_timeout: 500
state: update
'''
RETURN = '''
load_balancer:
description: Information about the load balancer that was processed
type: dict
sample: '{"id": "92B74394A397ECC3359825C1656D67A6", "name": "Default Balancer"}'
returned: always
'''
import os
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.general.plugins.module_utils.oneandone import (
get_load_balancer,
get_server,
get_datacenter,
OneAndOneResources,
wait_for_resource_creation_completion
)
HAS_ONEANDONE_SDK = True
try:
import oneandone.client
except ImportError:
HAS_ONEANDONE_SDK = False
DATACENTERS = ['US', 'ES', 'DE', 'GB']
HEALTH_CHECK_TESTS = ['NONE', 'TCP', 'HTTP', 'ICMP']
METHODS = ['ROUND_ROBIN', 'LEAST_CONNECTIONS']
def _check_mode(module, result):
if module.check_mode:
module.exit_json(
changed=result
)
def _add_server_ips(module, oneandone_conn, load_balancer_id, server_ids):
"""
Assigns servers to a load balancer.
"""
try:
attach_servers = []
for server_id in server_ids:
server = get_server(oneandone_conn, server_id, True)
attach_server = oneandone.client.AttachServer(
server_id=server['id'],
server_ip_id=next(iter(server['ips'] or []), None)['id']
)
attach_servers.append(attach_server)
if module.check_mode:
if attach_servers:
return True
return False
load_balancer = oneandone_conn.attach_load_balancer_server(
load_balancer_id=load_balancer_id,
server_ips=attach_servers)
return load_balancer
except Exception as ex:
module.fail_json(msg=str(ex))
def _remove_load_balancer_server(module, oneandone_conn, load_balancer_id, server_ip_id):
"""
Unassigns a server/IP from a load balancer.
"""
try:
if module.check_mode:
lb_server = oneandone_conn.get_load_balancer_server(
load_balancer_id=load_balancer_id,
server_ip_id=server_ip_id)
if lb_server:
return True
return False
load_balancer = oneandone_conn.remove_load_balancer_server(
load_balancer_id=load_balancer_id,
server_ip_id=server_ip_id)
return load_balancer
except Exception as ex:
module.fail_json(msg=str(ex))
def _add_load_balancer_rules(module, oneandone_conn, load_balancer_id, rules):
"""
Adds new rules to a load_balancer.
"""
try:
load_balancer_rules = []
for rule in rules:
load_balancer_rule = oneandone.client.LoadBalancerRule(
protocol=rule['protocol'],
port_balancer=rule['port_balancer'],
port_server=rule['port_server'],
source=rule['source'])
load_balancer_rules.append(load_balancer_rule)
if module.check_mode:
lb_id = get_load_balancer(oneandone_conn, load_balancer_id)
if (load_balancer_rules and lb_id):
return True
return False
load_balancer = oneandone_conn.add_load_balancer_rule(
load_balancer_id=load_balancer_id,
load_balancer_rules=load_balancer_rules
)
return load_balancer
except Exception as ex:
module.fail_json(msg=str(ex))
def _remove_load_balancer_rule(module, oneandone_conn, load_balancer_id, rule_id):
"""
Removes a rule from a load_balancer.
"""
try:
if module.check_mode:
rule = oneandone_conn.get_load_balancer_rule(
load_balancer_id=load_balancer_id,
rule_id=rule_id)
if rule:
return True
return False
load_balancer = oneandone_conn.remove_load_balancer_rule(
load_balancer_id=load_balancer_id,
rule_id=rule_id
)
return load_balancer
except Exception as ex:
module.fail_json(msg=str(ex))
def update_load_balancer(module, oneandone_conn):
"""
Updates a load_balancer based on input arguments.
Load balancer rules and server ips can be added/removed to/from
load balancer. Load balancer name, description, health_check_test,
health_check_interval, persistence, persistence_time, and method
can be updated as well.
module : AnsibleModule object
oneandone_conn: authenticated oneandone object
"""
load_balancer_id = module.params.get('load_balancer')
name = module.params.get('name')
description = module.params.get('description')
health_check_test = module.params.get('health_check_test')
health_check_interval = module.params.get('health_check_interval')
health_check_path = module.params.get('health_check_path')
health_check_parse = module.params.get('health_check_parse')
persistence = module.params.get('persistence')
persistence_time = module.params.get('persistence_time')
method = module.params.get('method')
add_server_ips = module.params.get('add_server_ips')
remove_server_ips = module.params.get('remove_server_ips')
add_rules = module.params.get('add_rules')
remove_rules = module.params.get('remove_rules')
changed = False
load_balancer = get_load_balancer(oneandone_conn, load_balancer_id, True)
if load_balancer is None:
_check_mode(module, False)
if (name or description or health_check_test or health_check_interval or health_check_path or
health_check_parse or persistence or persistence_time or method):
_check_mode(module, True)
load_balancer = oneandone_conn.modify_load_balancer(
load_balancer_id=load_balancer['id'],
name=name,
description=description,
health_check_test=health_check_test,
health_check_interval=health_check_interval,
health_check_path=health_check_path,
health_check_parse=health_check_parse,
persistence=persistence,
persistence_time=persistence_time,
method=method)
changed = True
if add_server_ips:
if module.check_mode:
_check_mode(module, _add_server_ips(module,
oneandone_conn,
load_balancer['id'],
add_server_ips))
load_balancer = _add_server_ips(module, oneandone_conn, load_balancer['id'], add_server_ips)
changed = True
if remove_server_ips:
chk_changed = False
for server_ip_id in remove_server_ips:
if module.check_mode:
chk_changed |= _remove_load_balancer_server(module,
oneandone_conn,
load_balancer['id'],
server_ip_id)
_remove_load_balancer_server(module,
oneandone_conn,
load_balancer['id'],
server_ip_id)
_check_mode(module, chk_changed)
load_balancer = get_load_balancer(oneandone_conn, load_balancer['id'], True)
changed = True
if add_rules:
load_balancer = _add_load_balancer_rules(module,
oneandone_conn,
load_balancer['id'],
add_rules)
_check_mode(module, load_balancer)
changed = True
if remove_rules:
chk_changed = False
for rule_id in remove_rules:
if module.check_mode:
chk_changed |= _remove_load_balancer_rule(module,
oneandone_conn,
load_balancer['id'],
rule_id)
_remove_load_balancer_rule(module,
oneandone_conn,
load_balancer['id'],
rule_id)
_check_mode(module, chk_changed)
load_balancer = get_load_balancer(oneandone_conn, load_balancer['id'], True)
changed = True
try:
return (changed, load_balancer)
except Exception as ex:
module.fail_json(msg=str(ex))
def create_load_balancer(module, oneandone_conn):
"""
Create a new load_balancer.
module : AnsibleModule object
oneandone_conn: authenticated oneandone object
"""
try:
name = module.params.get('name')
description = module.params.get('description')
health_check_test = module.params.get('health_check_test')
health_check_interval = module.params.get('health_check_interval')
health_check_path = module.params.get('health_check_path')
health_check_parse = module.params.get('health_check_parse')
persistence = module.params.get('persistence')
persistence_time = module.params.get('persistence_time')
method = module.params.get('method')
datacenter = module.params.get('datacenter')
rules = module.params.get('rules')
wait = module.params.get('wait')
wait_timeout = module.params.get('wait_timeout')
wait_interval = module.params.get('wait_interval')
load_balancer_rules = []
datacenter_id = None
if datacenter is not None:
datacenter_id = get_datacenter(oneandone_conn, datacenter)
if datacenter_id is None:
module.fail_json(
msg='datacenter %s not found.' % datacenter)
for rule in rules:
load_balancer_rule = oneandone.client.LoadBalancerRule(
protocol=rule['protocol'],
port_balancer=rule['port_balancer'],
port_server=rule['port_server'],
source=rule['source'])
load_balancer_rules.append(load_balancer_rule)
_check_mode(module, True)
load_balancer_obj = oneandone.client.LoadBalancer(
health_check_path=health_check_path,
health_check_parse=health_check_parse,
name=name,
description=description,
health_check_test=health_check_test,
health_check_interval=health_check_interval,
persistence=persistence,
persistence_time=persistence_time,
method=method,
datacenter_id=datacenter_id
)
load_balancer = oneandone_conn.create_load_balancer(
load_balancer=load_balancer_obj,
load_balancer_rules=load_balancer_rules
)
if wait:
wait_for_resource_creation_completion(oneandone_conn,
OneAndOneResources.load_balancer,
load_balancer['id'],
wait_timeout,
wait_interval)
load_balancer = get_load_balancer(oneandone_conn, load_balancer['id'], True) # refresh
changed = True if load_balancer else False
_check_mode(module, False)
return (changed, load_balancer)
except Exception as ex:
module.fail_json(msg=str(ex))
def remove_load_balancer(module, oneandone_conn):
"""
Removes a load_balancer.
module : AnsibleModule object
oneandone_conn: authenticated oneandone object
"""
try:
lb_id = module.params.get('name')
load_balancer_id = get_load_balancer(oneandone_conn, lb_id)
if module.check_mode:
if load_balancer_id is None:
_check_mode(module, False)
_check_mode(module, True)
load_balancer = oneandone_conn.delete_load_balancer(load_balancer_id)
changed = True if load_balancer else False
return (changed, {
'id': load_balancer['id'],
'name': load_balancer['name']
})
except Exception as ex:
module.fail_json(msg=str(ex))
def main():
module = AnsibleModule(
argument_spec=dict(
auth_token=dict(
type='str',
default=os.environ.get('ONEANDONE_AUTH_TOKEN')),
api_url=dict(
type='str',
default=os.environ.get('ONEANDONE_API_URL')),
load_balancer=dict(type='str'),
name=dict(type='str'),
description=dict(type='str'),
health_check_test=dict(
choices=HEALTH_CHECK_TESTS),
health_check_interval=dict(type='str'),
health_check_path=dict(type='str'),
health_check_parse=dict(type='str'),
persistence=dict(type='bool'),
persistence_time=dict(type='str'),
method=dict(
choices=METHODS),
datacenter=dict(
choices=DATACENTERS),
rules=dict(type='list', default=[]),
add_server_ips=dict(type='list', default=[]),
remove_server_ips=dict(type='list', default=[]),
add_rules=dict(type='list', default=[]),
remove_rules=dict(type='list', default=[]),
wait=dict(type='bool', default=True),
wait_timeout=dict(type='int', default=600),
wait_interval=dict(type='int', default=5),
state=dict(type='str', default='present', choices=['present', 'absent', 'update']),
),
supports_check_mode=True
)
if not HAS_ONEANDONE_SDK:
module.fail_json(msg='1and1 required for this module')
if not module.params.get('auth_token'):
module.fail_json(
msg='auth_token parameter is required.')
if not module.params.get('api_url'):
oneandone_conn = oneandone.client.OneAndOneService(
api_token=module.params.get('auth_token'))
else:
oneandone_conn = oneandone.client.OneAndOneService(
api_token=module.params.get('auth_token'), api_url=module.params.get('api_url'))
state = module.params.get('state')
if state == 'absent':
if not module.params.get('name'):
module.fail_json(
msg="'name' parameter is required for deleting a load balancer.")
try:
(changed, load_balancer) = remove_load_balancer(module, oneandone_conn)
except Exception as ex:
module.fail_json(msg=str(ex))
elif state == 'update':
if not module.params.get('load_balancer'):
module.fail_json(
msg="'load_balancer' parameter is required for updating a load balancer.")
try:
(changed, load_balancer) = update_load_balancer(module, oneandone_conn)
except Exception as ex:
module.fail_json(msg=str(ex))
elif state == 'present':
for param in ('name', 'health_check_test', 'health_check_interval', 'persistence',
'persistence_time', 'method', 'rules'):
if not module.params.get(param):
module.fail_json(
msg="%s parameter is required for new load balancers." % param)
try:
(changed, load_balancer) = create_load_balancer(module, oneandone_conn)
except Exception as ex:
module.fail_json(msg=str(ex))
module.exit_json(changed=changed, load_balancer=load_balancer)
if __name__ == '__main__':
main()

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,452 @@
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: oneandone_private_network
short_description: Configure 1&1 private networking.
description:
- Create, remove, reconfigure, update a private network.
This module has a dependency on 1and1 >= 1.0
options:
state:
description:
- Define a network's state to create, remove, or update.
required: false
default: 'present'
choices: [ "present", "absent", "update" ]
auth_token:
description:
- Authenticating API token provided by 1&1.
required: true
private_network:
description:
- The identifier (id or name) of the network used with update state.
required: true
api_url:
description:
- Custom API URL. Overrides the
ONEANDONE_API_URL environment variable.
required: false
name:
description:
- Private network name used with present state. Used as identifier (id or name) when used with absent state.
required: true
description:
description:
- Set a description for the network.
datacenter:
description:
- The identifier of the datacenter where the private network will be created
network_address:
description:
- Set a private network space, i.e. 192.168.1.0
subnet_mask:
description:
- Set the netmask for the private network, i.e. 255.255.255.0
add_members:
description:
- List of server identifiers (name or id) to be added to the private network.
remove_members:
description:
- List of server identifiers (name or id) to be removed from the private network.
wait:
description:
- wait for the instance to be in state 'running' before returning
required: false
default: "yes"
type: bool
wait_timeout:
description:
- how long before wait gives up, in seconds
default: 600
wait_interval:
description:
- Defines the number of seconds to wait when using the _wait_for methods
default: 5
requirements:
- "1and1"
- "python >= 2.6"
author:
- Amel Ajdinovic (@aajdinov)
- Ethan Devenport (@edevenport)
'''
EXAMPLES = '''
# Provisioning example. Create and destroy private networks.
- oneandone_private_network:
auth_token: oneandone_private_api_key
name: backup_network
description: Testing creation of a private network with ansible
network_address: 70.35.193.100
subnet_mask: 255.0.0.0
datacenter: US
- oneandone_private_network:
auth_token: oneandone_private_api_key
state: absent
name: backup_network
# Modify the private network.
- oneandone_private_network:
auth_token: oneandone_private_api_key
state: update
private_network: backup_network
network_address: 192.168.2.0
subnet_mask: 255.255.255.0
# Add members to the private network.
- oneandone_private_network:
auth_token: oneandone_private_api_key
state: update
private_network: backup_network
add_members:
- server identifier (id or name)
# Remove members from the private network.
- oneandone_private_network:
auth_token: oneandone_private_api_key
state: update
private_network: backup_network
remove_members:
- server identifier (id or name)
'''
RETURN = '''
private_network:
description: Information about the private network.
type: dict
sample: '{"name": "backup_network", "id": "55726DEDA20C99CF6F2AF8F18CAC9963"}'
returned: always
'''
import os
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.general.plugins.module_utils.oneandone import (
get_private_network,
get_server,
get_datacenter,
OneAndOneResources,
wait_for_resource_creation_completion,
wait_for_resource_deletion_completion
)
HAS_ONEANDONE_SDK = True
try:
import oneandone.client
except ImportError:
HAS_ONEANDONE_SDK = False
DATACENTERS = ['US', 'ES', 'DE', 'GB']
def _check_mode(module, result):
if module.check_mode:
module.exit_json(
changed=result
)
def _add_servers(module, oneandone_conn, name, members):
try:
private_network_id = get_private_network(oneandone_conn, name)
if module.check_mode:
if private_network_id and members:
return True
return False
network = oneandone_conn.attach_private_network_servers(
private_network_id=private_network_id,
server_ids=members)
return network
except Exception as e:
module.fail_json(msg=str(e))
def _remove_member(module, oneandone_conn, name, member_id):
try:
private_network_id = get_private_network(oneandone_conn, name)
if module.check_mode:
if private_network_id:
network_member = oneandone_conn.get_private_network_server(
private_network_id=private_network_id,
server_id=member_id)
if network_member:
return True
return False
network = oneandone_conn.remove_private_network_server(
private_network_id=name,
server_id=member_id)
return network
except Exception as ex:
module.fail_json(msg=str(ex))
def create_network(module, oneandone_conn):
"""
Create new private network
module : AnsibleModule object
oneandone_conn: authenticated oneandone object
Returns a dictionary containing a 'changed' attribute indicating whether
any network was added.
"""
name = module.params.get('name')
description = module.params.get('description')
network_address = module.params.get('network_address')
subnet_mask = module.params.get('subnet_mask')
datacenter = module.params.get('datacenter')
wait = module.params.get('wait')
wait_timeout = module.params.get('wait_timeout')
wait_interval = module.params.get('wait_interval')
if datacenter is not None:
datacenter_id = get_datacenter(oneandone_conn, datacenter)
if datacenter_id is None:
module.fail_json(
msg='datacenter %s not found.' % datacenter)
try:
_check_mode(module, True)
network = oneandone_conn.create_private_network(
private_network=oneandone.client.PrivateNetwork(
name=name,
description=description,
network_address=network_address,
subnet_mask=subnet_mask,
datacenter_id=datacenter_id
))
if wait:
wait_for_resource_creation_completion(
oneandone_conn,
OneAndOneResources.private_network,
network['id'],
wait_timeout,
wait_interval)
network = get_private_network(oneandone_conn,
network['id'],
True)
changed = True if network else False
_check_mode(module, False)
return (changed, network)
except Exception as e:
module.fail_json(msg=str(e))
def update_network(module, oneandone_conn):
"""
Modifies a private network.
module : AnsibleModule object
oneandone_conn: authenticated oneandone object
"""
try:
_private_network_id = module.params.get('private_network')
_name = module.params.get('name')
_description = module.params.get('description')
_network_address = module.params.get('network_address')
_subnet_mask = module.params.get('subnet_mask')
_add_members = module.params.get('add_members')
_remove_members = module.params.get('remove_members')
changed = False
private_network = get_private_network(oneandone_conn,
_private_network_id,
True)
if private_network is None:
_check_mode(module, False)
if _name or _description or _network_address or _subnet_mask:
_check_mode(module, True)
private_network = oneandone_conn.modify_private_network(
private_network_id=private_network['id'],
name=_name,
description=_description,
network_address=_network_address,
subnet_mask=_subnet_mask)
changed = True
if _add_members:
instances = []
for member in _add_members:
instance_id = get_server(oneandone_conn, member)
instance_obj = oneandone.client.AttachServer(server_id=instance_id)
instances.extend([instance_obj])
private_network = _add_servers(module, oneandone_conn, private_network['id'], instances)
_check_mode(module, private_network)
changed = True
if _remove_members:
chk_changed = False
for member in _remove_members:
instance = get_server(oneandone_conn, member, True)
if module.check_mode:
chk_changed |= _remove_member(module,
oneandone_conn,
private_network['id'],
instance['id'])
_check_mode(module, instance and chk_changed)
_remove_member(module,
oneandone_conn,
private_network['id'],
instance['id'])
private_network = get_private_network(oneandone_conn,
private_network['id'],
True)
changed = True
return (changed, private_network)
except Exception as ex:
module.fail_json(msg=str(ex))
def remove_network(module, oneandone_conn):
"""
Removes a private network.
module : AnsibleModule object
oneandone_conn: authenticated oneandone object.
"""
try:
pn_id = module.params.get('name')
wait_timeout = module.params.get('wait_timeout')
wait_interval = module.params.get('wait_interval')
private_network_id = get_private_network(oneandone_conn, pn_id)
if module.check_mode:
if private_network_id is None:
_check_mode(module, False)
_check_mode(module, True)
private_network = oneandone_conn.delete_private_network(private_network_id)
wait_for_resource_deletion_completion(oneandone_conn,
OneAndOneResources.private_network,
private_network['id'],
wait_timeout,
wait_interval)
changed = True if private_network else False
return (changed, {
'id': private_network['id'],
'name': private_network['name']
})
except Exception as e:
module.fail_json(msg=str(e))
def main():
module = AnsibleModule(
argument_spec=dict(
auth_token=dict(
type='str',
default=os.environ.get('ONEANDONE_AUTH_TOKEN')),
api_url=dict(
type='str',
default=os.environ.get('ONEANDONE_API_URL')),
private_network=dict(type='str'),
name=dict(type='str'),
description=dict(type='str'),
network_address=dict(type='str'),
subnet_mask=dict(type='str'),
add_members=dict(type='list', default=[]),
remove_members=dict(type='list', default=[]),
datacenter=dict(
choices=DATACENTERS),
wait=dict(type='bool', default=True),
wait_timeout=dict(type='int', default=600),
wait_interval=dict(type='int', default=5),
state=dict(type='str', default='present', choices=['present', 'absent', 'update']),
),
supports_check_mode=True
)
if not HAS_ONEANDONE_SDK:
module.fail_json(msg='1and1 required for this module')
if not module.params.get('auth_token'):
module.fail_json(
msg='auth_token parameter is required.')
if not module.params.get('api_url'):
oneandone_conn = oneandone.client.OneAndOneService(
api_token=module.params.get('auth_token'))
else:
oneandone_conn = oneandone.client.OneAndOneService(
api_token=module.params.get('auth_token'), api_url=module.params.get('api_url'))
state = module.params.get('state')
if state == 'absent':
if not module.params.get('name'):
module.fail_json(
msg="'name' parameter is required for deleting a network.")
try:
(changed, private_network) = remove_network(module, oneandone_conn)
except Exception as e:
module.fail_json(msg=str(e))
elif state == 'update':
if not module.params.get('private_network'):
module.fail_json(
msg="'private_network' parameter is required for updating a network.")
try:
(changed, private_network) = update_network(module, oneandone_conn)
except Exception as e:
module.fail_json(msg=str(e))
elif state == 'present':
if not module.params.get('name'):
module.fail_json(
msg="'name' parameter is required for new networks.")
try:
(changed, private_network) = create_network(module, oneandone_conn)
except Exception as e:
module.fail_json(msg=str(e))
module.exit_json(changed=changed, private_network=private_network)
if __name__ == '__main__':
main()

View file

@ -0,0 +1,342 @@
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: oneandone_public_ip
short_description: Configure 1&1 public IPs.
description:
- Create, update, and remove public IPs.
This module has a dependency on 1and1 >= 1.0
options:
state:
description:
- Define a public ip state to create, remove, or update.
required: false
default: 'present'
choices: [ "present", "absent", "update" ]
auth_token:
description:
- Authenticating API token provided by 1&1.
required: true
api_url:
description:
- Custom API URL. Overrides the
ONEANDONE_API_URL environment variable.
required: false
reverse_dns:
description:
- Reverse DNS name. maxLength=256
required: false
datacenter:
description:
- ID of the datacenter where the IP will be created (only for unassigned IPs).
required: false
type:
description:
- Type of IP. Currently, only IPV4 is available.
choices: ["IPV4", "IPV6"]
default: 'IPV4'
required: false
public_ip_id:
description:
- The ID of the public IP used with update and delete states.
required: true
wait:
description:
- wait for the instance to be in state 'running' before returning
required: false
default: "yes"
type: bool
wait_timeout:
description:
- how long before wait gives up, in seconds
default: 600
wait_interval:
description:
- Defines the number of seconds to wait when using the _wait_for methods
default: 5
requirements:
- "1and1"
- "python >= 2.6"
author:
- Amel Ajdinovic (@aajdinov)
- Ethan Devenport (@edevenport)
'''
EXAMPLES = '''
# Create a public IP.
- oneandone_public_ip:
auth_token: oneandone_private_api_key
reverse_dns: example.com
datacenter: US
type: IPV4
# Update a public IP.
- oneandone_public_ip:
auth_token: oneandone_private_api_key
public_ip_id: public ip id
reverse_dns: secondexample.com
state: update
# Delete a public IP
- oneandone_public_ip:
auth_token: oneandone_private_api_key
public_ip_id: public ip id
state: absent
'''
RETURN = '''
public_ip:
description: Information about the public ip that was processed
type: dict
sample: '{"id": "F77CC589EBC120905B4F4719217BFF6D", "ip": "10.5.132.106"}'
returned: always
'''
import os
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.general.plugins.module_utils.oneandone import (
get_datacenter,
get_public_ip,
OneAndOneResources,
wait_for_resource_creation_completion
)
HAS_ONEANDONE_SDK = True
try:
import oneandone.client
except ImportError:
HAS_ONEANDONE_SDK = False
DATACENTERS = ['US', 'ES', 'DE', 'GB']
TYPES = ['IPV4', 'IPV6']
def _check_mode(module, result):
if module.check_mode:
module.exit_json(
changed=result
)
def create_public_ip(module, oneandone_conn):
"""
Create new public IP
module : AnsibleModule object
oneandone_conn: authenticated oneandone object
Returns a dictionary containing a 'changed' attribute indicating whether
any public IP was added.
"""
reverse_dns = module.params.get('reverse_dns')
datacenter = module.params.get('datacenter')
ip_type = module.params.get('type')
wait = module.params.get('wait')
wait_timeout = module.params.get('wait_timeout')
wait_interval = module.params.get('wait_interval')
if datacenter is not None:
datacenter_id = get_datacenter(oneandone_conn, datacenter)
if datacenter_id is None:
_check_mode(module, False)
module.fail_json(
msg='datacenter %s not found.' % datacenter)
try:
_check_mode(module, True)
public_ip = oneandone_conn.create_public_ip(
reverse_dns=reverse_dns,
ip_type=ip_type,
datacenter_id=datacenter_id)
if wait:
wait_for_resource_creation_completion(oneandone_conn,
OneAndOneResources.public_ip,
public_ip['id'],
wait_timeout,
wait_interval)
public_ip = oneandone_conn.get_public_ip(public_ip['id'])
changed = True if public_ip else False
return (changed, public_ip)
except Exception as e:
module.fail_json(msg=str(e))
def update_public_ip(module, oneandone_conn):
"""
Update a public IP
module : AnsibleModule object
oneandone_conn: authenticated oneandone object
Returns a dictionary containing a 'changed' attribute indicating whether
any public IP was changed.
"""
reverse_dns = module.params.get('reverse_dns')
public_ip_id = module.params.get('public_ip_id')
wait = module.params.get('wait')
wait_timeout = module.params.get('wait_timeout')
wait_interval = module.params.get('wait_interval')
public_ip = get_public_ip(oneandone_conn, public_ip_id, True)
if public_ip is None:
_check_mode(module, False)
module.fail_json(
msg='public IP %s not found.' % public_ip_id)
try:
_check_mode(module, True)
public_ip = oneandone_conn.modify_public_ip(
ip_id=public_ip['id'],
reverse_dns=reverse_dns)
if wait:
wait_for_resource_creation_completion(oneandone_conn,
OneAndOneResources.public_ip,
public_ip['id'],
wait_timeout,
wait_interval)
public_ip = oneandone_conn.get_public_ip(public_ip['id'])
changed = True if public_ip else False
return (changed, public_ip)
except Exception as e:
module.fail_json(msg=str(e))
def delete_public_ip(module, oneandone_conn):
"""
Delete a public IP
module : AnsibleModule object
oneandone_conn: authenticated oneandone object
Returns a dictionary containing a 'changed' attribute indicating whether
any public IP was deleted.
"""
public_ip_id = module.params.get('public_ip_id')
public_ip = get_public_ip(oneandone_conn, public_ip_id, True)
if public_ip is None:
_check_mode(module, False)
module.fail_json(
msg='public IP %s not found.' % public_ip_id)
try:
_check_mode(module, True)
deleted_public_ip = oneandone_conn.delete_public_ip(
ip_id=public_ip['id'])
changed = True if deleted_public_ip else False
return (changed, {
'id': public_ip['id']
})
except Exception as e:
module.fail_json(msg=str(e))
def main():
module = AnsibleModule(
argument_spec=dict(
auth_token=dict(
type='str',
default=os.environ.get('ONEANDONE_AUTH_TOKEN')),
api_url=dict(
type='str',
default=os.environ.get('ONEANDONE_API_URL')),
public_ip_id=dict(type='str'),
reverse_dns=dict(type='str'),
datacenter=dict(
choices=DATACENTERS,
default='US'),
type=dict(
choices=TYPES,
default='IPV4'),
wait=dict(type='bool', default=True),
wait_timeout=dict(type='int', default=600),
wait_interval=dict(type='int', default=5),
state=dict(type='str', default='present', choices=['present', 'absent', 'update']),
),
supports_check_mode=True
)
if not HAS_ONEANDONE_SDK:
module.fail_json(msg='1and1 required for this module')
if not module.params.get('auth_token'):
module.fail_json(
msg='auth_token parameter is required.')
if not module.params.get('api_url'):
oneandone_conn = oneandone.client.OneAndOneService(
api_token=module.params.get('auth_token'))
else:
oneandone_conn = oneandone.client.OneAndOneService(
api_token=module.params.get('auth_token'), api_url=module.params.get('api_url'))
state = module.params.get('state')
if state == 'absent':
if not module.params.get('public_ip_id'):
module.fail_json(
msg="'public_ip_id' parameter is required to delete a public ip.")
try:
(changed, public_ip) = delete_public_ip(module, oneandone_conn)
except Exception as e:
module.fail_json(msg=str(e))
elif state == 'update':
if not module.params.get('public_ip_id'):
module.fail_json(
msg="'public_ip_id' parameter is required to update a public ip.")
try:
(changed, public_ip) = update_public_ip(module, oneandone_conn)
except Exception as e:
module.fail_json(msg=str(e))
elif state == 'present':
try:
(changed, public_ip) = create_public_ip(module, oneandone_conn)
except Exception as e:
module.fail_json(msg=str(e))
module.exit_json(changed=changed, public_ip=public_ip)
if __name__ == '__main__':
main()

View file

@ -0,0 +1,696 @@
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: oneandone_server
short_description: Create, destroy, start, stop, and reboot a 1&1 Host server.
description:
- Create, destroy, update, start, stop, and reboot a 1&1 Host server.
When the server is created it can optionally wait for it to be 'running' before returning.
options:
state:
description:
- Define a server's state to create, remove, start or stop it.
default: present
choices: [ "present", "absent", "running", "stopped" ]
auth_token:
description:
- Authenticating API token provided by 1&1. Overrides the
ONEANDONE_AUTH_TOKEN environment variable.
required: true
api_url:
description:
- Custom API URL. Overrides the
ONEANDONE_API_URL environment variable.
datacenter:
description:
- The datacenter location.
default: US
choices: [ "US", "ES", "DE", "GB" ]
hostname:
description:
- The hostname or ID of the server. Only used when state is 'present'.
description:
description:
- The description of the server.
appliance:
description:
- The operating system name or ID for the server.
It is required only for 'present' state.
fixed_instance_size:
description:
- The instance size name or ID of the server.
It is required only for 'present' state, and it is mutually exclusive with
vcore, cores_per_processor, ram, and hdds parameters.
required: true
choices: [ "S", "M", "L", "XL", "XXL", "3XL", "4XL", "5XL" ]
vcore:
description:
- The total number of processors.
It must be provided with cores_per_processor, ram, and hdds parameters.
cores_per_processor:
description:
- The number of cores per processor.
It must be provided with vcore, ram, and hdds parameters.
ram:
description:
- The amount of RAM memory.
It must be provided with with vcore, cores_per_processor, and hdds parameters.
hdds:
description:
- A list of hard disks with nested "size" and "is_main" properties.
It must be provided with vcore, cores_per_processor, and ram parameters.
private_network:
description:
- The private network name or ID.
firewall_policy:
description:
- The firewall policy name or ID.
load_balancer:
description:
- The load balancer name or ID.
monitoring_policy:
description:
- The monitoring policy name or ID.
server:
description:
- Server identifier (ID or hostname). It is required for all states except 'running' and 'present'.
count:
description:
- The number of servers to create.
default: 1
ssh_key:
description:
- User's public SSH key (contents, not path).
server_type:
description:
- The type of server to be built.
default: "cloud"
choices: [ "cloud", "baremetal", "k8s_node" ]
wait:
description:
- Wait for the server to be in state 'running' before returning.
Also used for delete operation (set to 'false' if you don't want to wait
for each individual server to be deleted before moving on with
other tasks.)
type: bool
default: 'yes'
wait_timeout:
description:
- how long before wait gives up, in seconds
default: 600
wait_interval:
description:
- Defines the number of seconds to wait when using the wait_for methods
default: 5
auto_increment:
description:
- When creating multiple servers at once, whether to differentiate
hostnames by appending a count after them or substituting the count
where there is a %02d or %03d in the hostname string.
type: bool
default: 'yes'
requirements:
- "1and1"
- "python >= 2.6"
author:
- "Amel Ajdinovic (@aajdinov)"
- "Ethan Devenport (@edevenport)"
'''
EXAMPLES = '''
# Provisioning example. Creates three servers and enumerate their names.
- oneandone_server:
auth_token: oneandone_private_api_key
hostname: node%02d
fixed_instance_size: XL
datacenter: US
appliance: C5A349786169F140BCBC335675014C08
auto_increment: true
count: 3
# Create three servers, passing in an ssh_key.
- oneandone_server:
auth_token: oneandone_private_api_key
hostname: node%02d
vcore: 2
cores_per_processor: 4
ram: 8.0
hdds:
- size: 50
is_main: false
datacenter: ES
appliance: C5A349786169F140BCBC335675014C08
count: 3
wait: yes
wait_timeout: 600
wait_interval: 10
ssh_key: SSH_PUBLIC_KEY
# Removing server
- oneandone_server:
auth_token: oneandone_private_api_key
state: absent
server: 'node01'
# Starting server.
- oneandone_server:
auth_token: oneandone_private_api_key
state: running
server: 'node01'
# Stopping server
- oneandone_server:
auth_token: oneandone_private_api_key
state: stopped
server: 'node01'
'''
RETURN = '''
servers:
description: Information about each server that was processed
type: list
sample: '[{"hostname": "my-server", "id": "server-id"}]'
returned: always
'''
import os
import time
from ansible.module_utils.six.moves import xrange
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.general.plugins.module_utils.oneandone import (
get_datacenter,
get_fixed_instance_size,
get_appliance,
get_private_network,
get_monitoring_policy,
get_firewall_policy,
get_load_balancer,
get_server,
OneAndOneResources,
wait_for_resource_creation_completion,
wait_for_resource_deletion_completion
)
HAS_ONEANDONE_SDK = True
try:
import oneandone.client
except ImportError:
HAS_ONEANDONE_SDK = False
DATACENTERS = ['US', 'ES', 'DE', 'GB']
ONEANDONE_SERVER_STATES = (
'DEPLOYING',
'POWERED_OFF',
'POWERED_ON',
'POWERING_ON',
'POWERING_OFF',
)
def _check_mode(module, result):
if module.check_mode:
module.exit_json(
changed=result
)
def _create_server(module, oneandone_conn, hostname, description,
fixed_instance_size_id, vcore, cores_per_processor, ram,
hdds, datacenter_id, appliance_id, ssh_key,
private_network_id, firewall_policy_id, load_balancer_id,
monitoring_policy_id, server_type, wait, wait_timeout,
wait_interval):
try:
existing_server = get_server(oneandone_conn, hostname)
if existing_server:
if module.check_mode:
return False
return None
if module.check_mode:
return True
server = oneandone_conn.create_server(
oneandone.client.Server(
name=hostname,
description=description,
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
appliance_id=appliance_id,
datacenter_id=datacenter_id,
rsa_key=ssh_key,
private_network_id=private_network_id,
firewall_policy_id=firewall_policy_id,
load_balancer_id=load_balancer_id,
monitoring_policy_id=monitoring_policy_id,
server_type=server_type,), hdds)
if wait:
wait_for_resource_creation_completion(
oneandone_conn,
OneAndOneResources.server,
server['id'],
wait_timeout,
wait_interval)
server = oneandone_conn.get_server(server['id']) # refresh
return server
except Exception as ex:
module.fail_json(msg=str(ex))
def _insert_network_data(server):
for addr_data in server['ips']:
if addr_data['type'] == 'IPV6':
server['public_ipv6'] = addr_data['ip']
elif addr_data['type'] == 'IPV4':
server['public_ipv4'] = addr_data['ip']
return server
def create_server(module, oneandone_conn):
"""
Create new server
module : AnsibleModule object
oneandone_conn: authenticated oneandone object
Returns a dictionary containing a 'changed' attribute indicating whether
any server was added, and a 'servers' attribute with the list of the
created servers' hostname, id and ip addresses.
"""
hostname = module.params.get('hostname')
description = module.params.get('description')
auto_increment = module.params.get('auto_increment')
count = module.params.get('count')
fixed_instance_size = module.params.get('fixed_instance_size')
vcore = module.params.get('vcore')
cores_per_processor = module.params.get('cores_per_processor')
ram = module.params.get('ram')
hdds = module.params.get('hdds')
datacenter = module.params.get('datacenter')
appliance = module.params.get('appliance')
ssh_key = module.params.get('ssh_key')
private_network = module.params.get('private_network')
monitoring_policy = module.params.get('monitoring_policy')
firewall_policy = module.params.get('firewall_policy')
load_balancer = module.params.get('load_balancer')
server_type = module.params.get('server_type')
wait = module.params.get('wait')
wait_timeout = module.params.get('wait_timeout')
wait_interval = module.params.get('wait_interval')
datacenter_id = get_datacenter(oneandone_conn, datacenter)
if datacenter_id is None:
_check_mode(module, False)
module.fail_json(
msg='datacenter %s not found.' % datacenter)
fixed_instance_size_id = None
if fixed_instance_size:
fixed_instance_size_id = get_fixed_instance_size(
oneandone_conn,
fixed_instance_size)
if fixed_instance_size_id is None:
_check_mode(module, False)
module.fail_json(
msg='fixed_instance_size %s not found.' % fixed_instance_size)
appliance_id = get_appliance(oneandone_conn, appliance)
if appliance_id is None:
_check_mode(module, False)
module.fail_json(
msg='appliance %s not found.' % appliance)
private_network_id = None
if private_network:
private_network_id = get_private_network(
oneandone_conn,
private_network)
if private_network_id is None:
_check_mode(module, False)
module.fail_json(
msg='private network %s not found.' % private_network)
monitoring_policy_id = None
if monitoring_policy:
monitoring_policy_id = get_monitoring_policy(
oneandone_conn,
monitoring_policy)
if monitoring_policy_id is None:
_check_mode(module, False)
module.fail_json(
msg='monitoring policy %s not found.' % monitoring_policy)
firewall_policy_id = None
if firewall_policy:
firewall_policy_id = get_firewall_policy(
oneandone_conn,
firewall_policy)
if firewall_policy_id is None:
_check_mode(module, False)
module.fail_json(
msg='firewall policy %s not found.' % firewall_policy)
load_balancer_id = None
if load_balancer:
load_balancer_id = get_load_balancer(
oneandone_conn,
load_balancer)
if load_balancer_id is None:
_check_mode(module, False)
module.fail_json(
msg='load balancer %s not found.' % load_balancer)
if auto_increment:
hostnames = _auto_increment_hostname(count, hostname)
descriptions = _auto_increment_description(count, description)
else:
hostnames = [hostname] * count
descriptions = [description] * count
hdd_objs = []
if hdds:
for hdd in hdds:
hdd_objs.append(oneandone.client.Hdd(
size=hdd['size'],
is_main=hdd['is_main']
))
servers = []
for index, name in enumerate(hostnames):
server = _create_server(
module=module,
oneandone_conn=oneandone_conn,
hostname=name,
description=descriptions[index],
fixed_instance_size_id=fixed_instance_size_id,
vcore=vcore,
cores_per_processor=cores_per_processor,
ram=ram,
hdds=hdd_objs,
datacenter_id=datacenter_id,
appliance_id=appliance_id,
ssh_key=ssh_key,
private_network_id=private_network_id,
monitoring_policy_id=monitoring_policy_id,
firewall_policy_id=firewall_policy_id,
load_balancer_id=load_balancer_id,
server_type=server_type,
wait=wait,
wait_timeout=wait_timeout,
wait_interval=wait_interval)
if server:
servers.append(server)
changed = False
if servers:
for server in servers:
if server:
_check_mode(module, True)
_check_mode(module, False)
servers = [_insert_network_data(_server) for _server in servers]
changed = True
_check_mode(module, False)
return (changed, servers)
def remove_server(module, oneandone_conn):
"""
Removes a server.
module : AnsibleModule object
oneandone_conn: authenticated oneandone object.
Returns a dictionary containing a 'changed' attribute indicating whether
the server was removed, and a 'removed_server' attribute with
the removed server's hostname and id.
"""
server_id = module.params.get('server')
wait = module.params.get('wait')
wait_timeout = module.params.get('wait_timeout')
wait_interval = module.params.get('wait_interval')
changed = False
removed_server = None
server = get_server(oneandone_conn, server_id, True)
if server:
_check_mode(module, True)
try:
oneandone_conn.delete_server(server_id=server['id'])
if wait:
wait_for_resource_deletion_completion(oneandone_conn,
OneAndOneResources.server,
server['id'],
wait_timeout,
wait_interval)
changed = True
except Exception as ex:
module.fail_json(
msg="failed to terminate the server: %s" % str(ex))
removed_server = {
'id': server['id'],
'hostname': server['name']
}
_check_mode(module, False)
return (changed, removed_server)
def startstop_server(module, oneandone_conn):
"""
Starts or Stops a server.
module : AnsibleModule object
oneandone_conn: authenticated oneandone object.
Returns a dictionary with a 'changed' attribute indicating whether
anything has changed for the server as a result of this function
being run, and a 'server' attribute with basic information for
the server.
"""
state = module.params.get('state')
server_id = module.params.get('server')
wait = module.params.get('wait')
wait_timeout = module.params.get('wait_timeout')
wait_interval = module.params.get('wait_interval')
changed = False
# Resolve server
server = get_server(oneandone_conn, server_id, True)
if server:
# Attempt to change the server state, only if it's not already there
# or on its way.
try:
if state == 'stopped' and server['status']['state'] == 'POWERED_ON':
_check_mode(module, True)
oneandone_conn.modify_server_status(
server_id=server['id'],
action='POWER_OFF',
method='SOFTWARE')
elif state == 'running' and server['status']['state'] == 'POWERED_OFF':
_check_mode(module, True)
oneandone_conn.modify_server_status(
server_id=server['id'],
action='POWER_ON',
method='SOFTWARE')
except Exception as ex:
module.fail_json(
msg="failed to set server %s to state %s: %s" % (
server_id, state, str(ex)))
_check_mode(module, False)
# Make sure the server has reached the desired state
if wait:
operation_completed = False
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(wait_interval)
server = oneandone_conn.get_server(server['id']) # refresh
server_state = server['status']['state']
if state == 'stopped' and server_state == 'POWERED_OFF':
operation_completed = True
break
if state == 'running' and server_state == 'POWERED_ON':
operation_completed = True
break
if not operation_completed:
module.fail_json(
msg="Timeout waiting for server %s to get to state %s" % (
server_id, state))
changed = True
server = _insert_network_data(server)
_check_mode(module, False)
return (changed, server)
def _auto_increment_hostname(count, hostname):
"""
Allow a custom incremental count in the hostname when defined with the
string formatting (%) operator. Otherwise, increment using name-01,
name-02, name-03, and so forth.
"""
if '%' not in hostname:
hostname = "%s-%%01d" % hostname
return [
hostname % i
for i in xrange(1, count + 1)
]
def _auto_increment_description(count, description):
"""
Allow the incremental count in the description when defined with the
string formatting (%) operator. Otherwise, repeat the same description.
"""
if '%' in description:
return [
description % i
for i in xrange(1, count + 1)
]
else:
return [description] * count
def main():
module = AnsibleModule(
argument_spec=dict(
auth_token=dict(
type='str',
default=os.environ.get('ONEANDONE_AUTH_TOKEN'),
no_log=True),
api_url=dict(
type='str',
default=os.environ.get('ONEANDONE_API_URL')),
hostname=dict(type='str'),
description=dict(type='str'),
appliance=dict(type='str'),
fixed_instance_size=dict(type='str'),
vcore=dict(type='int'),
cores_per_processor=dict(type='int'),
ram=dict(type='float'),
hdds=dict(type='list'),
count=dict(type='int', default=1),
ssh_key=dict(type='raw'),
auto_increment=dict(type='bool', default=True),
server=dict(type='str'),
datacenter=dict(
choices=DATACENTERS,
default='US'),
private_network=dict(type='str'),
firewall_policy=dict(type='str'),
load_balancer=dict(type='str'),
monitoring_policy=dict(type='str'),
server_type=dict(type='str', default='cloud', choices=['cloud', 'baremetal', 'k8s_node']),
wait=dict(type='bool', default=True),
wait_timeout=dict(type='int', default=600),
wait_interval=dict(type='int', default=5),
state=dict(type='str', default='present', choices=['present', 'absent', 'running', 'stopped']),
),
supports_check_mode=True,
mutually_exclusive=(['fixed_instance_size', 'vcore'], ['fixed_instance_size', 'cores_per_processor'],
['fixed_instance_size', 'ram'], ['fixed_instance_size', 'hdds'],),
required_together=(['vcore', 'cores_per_processor', 'ram', 'hdds'],)
)
if not HAS_ONEANDONE_SDK:
module.fail_json(msg='1and1 required for this module')
if not module.params.get('auth_token'):
module.fail_json(
msg='The "auth_token" parameter or ' +
'ONEANDONE_AUTH_TOKEN environment variable is required.')
if not module.params.get('api_url'):
oneandone_conn = oneandone.client.OneAndOneService(
api_token=module.params.get('auth_token'))
else:
oneandone_conn = oneandone.client.OneAndOneService(
api_token=module.params.get('auth_token'), api_url=module.params.get('api_url'))
state = module.params.get('state')
if state == 'absent':
if not module.params.get('server'):
module.fail_json(
msg="'server' parameter is required for deleting a server.")
try:
(changed, servers) = remove_server(module, oneandone_conn)
except Exception as ex:
module.fail_json(msg=str(ex))
elif state in ('running', 'stopped'):
if not module.params.get('server'):
module.fail_json(
msg="'server' parameter is required for starting/stopping a server.")
try:
(changed, servers) = startstop_server(module, oneandone_conn)
except Exception as ex:
module.fail_json(msg=str(ex))
elif state == 'present':
for param in ('hostname',
'appliance',
'datacenter'):
if not module.params.get(param):
module.fail_json(
msg="%s parameter is required for new server." % param)
try:
(changed, servers) = create_server(module, oneandone_conn)
except Exception as ex:
module.fail_json(msg=str(ex))
module.exit_json(changed=changed, servers=servers)
if __name__ == '__main__':
main()