Remove support for type=profile from lxd_container module

pull/18777/head
Hiroaki Nakamura 8 years ago committed by Matt Clay
parent be391b4d1f
commit 364ad3b8e5

@ -32,14 +32,6 @@ options:
description: description:
- Name of a container. - Name of a container.
required: true required: true
type:
choices:
- container
- profile
description:
- The resource type.
required: false
default: container
architecture: architecture:
description: description:
- The archiecture for the container (e.g. "x86_64" or "i686"). - The archiecture for the container (e.g. "x86_64" or "i686").
@ -82,24 +74,15 @@ options:
"alias": "ubuntu/xenial/amd64" }). "alias": "ubuntu/xenial/amd64" }).
See https://github.com/lxc/lxd/blob/master/doc/rest-api.md#post-1 See https://github.com/lxc/lxd/blob/master/doc/rest-api.md#post-1
required: false required: false
new_name:
description:
- A new name of a profile.
- If this parameter is specified a profile will be renamed to this name.
required: false
state: state:
choices: choices:
- present
- started - started
- stopped - stopped
- restarted - restarted
- absent - absent
- frozen - frozen
description: description:
- Define the state of a container or profile. - Define the state of a container.
- Valid choices for type=container are started, stopped, restarted,
absent, or frozen.
- Valid choices for type=profile are present or absent.
required: false required: false
default: started default: started
timeout: timeout:
@ -173,6 +156,7 @@ notes:
""" """
EXAMPLES = """ EXAMPLES = """
# An example for creating a Ubuntu container and install python
- hosts: localhost - hosts: localhost
connection: local connection: local
tasks: tasks:
@ -185,39 +169,33 @@ EXAMPLES = """
mode: pull mode: pull
server: https://images.linuxcontainers.org server: https://images.linuxcontainers.org
protocol: lxd protocol: lxd
alias: "ubuntu/xenial/amd64" alias: ubuntu/xenial/amd64
profiles: ["default"] profiles: ["default"]
- name: Install python in the created container "mycontainer" wait_for_ipv4_addresses: true
command: lxc exec mycontainer -- apt install -y python timeout: 600
- name: Copy /etc/hosts in the created container "mycontainer" to localhost with name "mycontainer-hosts"
command: lxc file pull mycontainer/etc/hosts mycontainer-hosts - name: check python is installed in container
delegate_to: mycontainer
raw: dpkg-query -W -f='${Status}' python
# Note your container must be in the inventory for the below example. register: python_install_check
# failed_when: python_install_check.rc not in [0, 1]
# [containers] changed_when: false
# mycontainer ansible_connection=lxd
# - name: install python in container
- hosts: delegate_to: mycontainer
- mycontainer raw: apt-get install -y python
tasks: when: python_install_check.rc == 1
- template: src=foo.j2 dest=/etc/bar
# An example for deleting a container
- hosts: localhost - hosts: localhost
connection: local connection: local
tasks: tasks:
- name: Create a stopped container - name: Restart a container
lxd_container: lxd_container:
name: mycontainer name: mycontainer
state: stopped state: restarted
source:
type: image
mode: pull
server: https://images.linuxcontainers.org
protocol: lxd
alias: "ubuntu/xenial/amd64"
profiles: ["default"]
# An example for restarting a container
- hosts: localhost - hosts: localhost
connection: local connection: local
tasks: tasks:
@ -225,35 +203,34 @@ EXAMPLES = """
lxd_container: lxd_container:
name: mycontainer name: mycontainer
state: restarted state: restarted
source:
type: image
mode: pull
server: https://images.linuxcontainers.org
protocol: lxd
alias: "ubuntu/xenial/amd64"
profiles: ["default"]
# An example for connecting to the LXD server using https # An example for restarting a container using https to connect to the LXD server
- hosts: localhost - hosts: localhost
connection: local connection: local
tasks: tasks:
- name: create macvlan profile - name: Restart a container
lxd_container: lxd_container:
url: https://127.0.0.1:8443 url: https://127.0.0.1:8443
# These cert_file and key_file values are equal to the default values. # These cert_file and key_file values are equal to the default values.
#cert_file: "{{ lookup('env', 'HOME') }}/.config/lxc/client.crt" #cert_file: "{{ lookup('env', 'HOME') }}/.config/lxc/client.crt"
#key_file: "{{ lookup('env', 'HOME') }}/.config/lxc/client.key" #key_file: "{{ lookup('env', 'HOME') }}/.config/lxc/client.key"
trust_password: mypassword trust_password: mypassword
type: profile name: mycontainer
name: macvlan state: restarted
state: present
config: {} # Note your container must be in the inventory for the below example.
description: 'my macvlan profile' #
devices: # [containers]
eth0: # mycontainer ansible_connection=lxd
nictype: macvlan #
parent: br0 - hosts:
type: nic - mycontainer
tasks:
- name: copy /etc/hosts in the created container to localhost with name "mycontainer-hosts"
fetch:
src: /etc/hosts
dest: /tmp/mycontainer-hosts
flat: true
""" """
RETURN=""" RETURN="""
@ -294,11 +271,6 @@ LXD_ANSIBLE_STATES = {
'frozen': '_frozen' 'frozen': '_frozen'
} }
# PROFILE_STATES is a list for states supported for type=profiles
PROFILES_STATES = [
'present', 'absent'
]
# ANSIBLE_LXD_STATES is a map of states of lxd containers to the Ansible # ANSIBLE_LXD_STATES is a map of states of lxd containers to the Ansible
# lxc_container module state parameter value. # lxc_container module state parameter value.
ANSIBLE_LXD_STATES = { ANSIBLE_LXD_STATES = {
@ -307,11 +279,10 @@ ANSIBLE_LXD_STATES = {
'Frozen': 'frozen', 'Frozen': 'frozen',
} }
# CONFIG_PARAMS is a map from a resource type to config attribute names. # CONFIG_PARAMS is a list of config attribute names.
CONFIG_PARAMS = { CONFIG_PARAMS = [
'container': ['architecture', 'config', 'devices', 'ephemeral', 'profiles', 'source'], 'architecture', 'config', 'devices', 'ephemeral', 'profiles', 'source'
'profile': ['config', 'description', 'devices'] ]
}
try: try:
callable(all) callable(all)
@ -324,7 +295,7 @@ except NameError:
return False return False
return True return True
class LxdContainerManagement(object): class LXDContainerManagement(object):
def __init__(self, module): def __init__(self, module):
"""Management of LXC containers via Ansible. """Management of LXC containers via Ansible.
@ -333,16 +304,10 @@ class LxdContainerManagement(object):
""" """
self.module = module self.module = module
self.name = self.module.params['name'] self.name = self.module.params['name']
self.type = self.module.params['type']
self._build_config() self._build_config()
self.state = self.module.params['state'] self.state = self.module.params['state']
if self.type == 'container':
self._check_argument_choices('state', self.state, LXD_ANSIBLE_STATES.keys())
elif self.type == 'profile':
self._check_argument_choices('state', self.state, PROFILES_STATES)
self.new_name = self.module.params.get('new_name', None)
self.timeout = self.module.params['timeout'] self.timeout = self.module.params['timeout']
self.wait_for_ipv4_addresses = self.module.params['wait_for_ipv4_addresses'] self.wait_for_ipv4_addresses = self.module.params['wait_for_ipv4_addresses']
self.force_stop = self.module.params['force_stop'] self.force_stop = self.module.params['force_stop']
@ -362,15 +327,9 @@ class LxdContainerManagement(object):
self.trust_password = self.module.params.get('trust_password', None) self.trust_password = self.module.params.get('trust_password', None)
self.actions = [] self.actions = []
def _check_argument_choices(self, name, value, choices):
if value not in choices:
choices_str=",".join([str(c) for c in choices])
msg="value of %s must be one of: %s, got: %s" % (name, choices_str, value)
self.module.fail_json(msg=msg)
def _build_config(self): def _build_config(self):
self.config = {} self.config = {}
for attr in CONFIG_PARAMS[self.type]: for attr in CONFIG_PARAMS:
param_val = self.module.params.get(attr, None) param_val = self.module.params.get(attr, None)
if param_val is not None: if param_val is not None:
self.config[attr] = param_val self.config[attr] = param_val
@ -555,77 +514,6 @@ class LxdContainerManagement(object):
self._operate_and_wait('PUT', '/1.0/containers/{0}'.format(self.name), body_json=body_json) self._operate_and_wait('PUT', '/1.0/containers/{0}'.format(self.name), body_json=body_json)
self.actions.append('apply_container_configs') self.actions.append('apply_container_configs')
def _get_profile_json(self):
return self.client.do(
'GET', '/1.0/profiles/{0}'.format(self.name),
ok_error_codes=[404]
)
@staticmethod
def _profile_json_to_module_state(resp_json):
if resp_json['type'] == 'error':
return 'absent'
return 'present'
def _update_profile(self):
if self.state == 'present':
if self.old_state == 'absent':
if self.new_name is None:
self._create_profile()
else:
self.module.fail_json(
msg='new_name must not be set when the profile does not exist and the specified state is present',
changed=False)
else:
if self.new_name is not None and self.new_name != self.name:
self._rename_profile()
if self._needs_to_apply_profile_configs():
self._apply_profile_configs()
elif self.state == 'absent':
if self.old_state == 'present':
if self.new_name is None:
self._delete_profile()
else:
self.module.fail_json(
msg='new_name must not be set when the profile exists and the specified state is absent',
changed=False)
def _create_profile(self):
config = self.config.copy()
config['name'] = self.name
self.client.do('POST', '/1.0/profiles', config)
self.actions.append('create')
def _rename_profile(self):
config = {'name': self.new_name}
self.client.do('POST', '/1.0/profiles/{}'.format(self.name), config)
self.actions.append('rename')
self.name = self.new_name
def _needs_to_change_profile_config(self, key):
if key not in self.config:
return False
old_configs = self.old_profile_json['metadata'].get(key, None)
return self.config[key] != old_configs
def _needs_to_apply_profile_configs(self):
return (
self._needs_to_change_profile_config('config') or
self._needs_to_change_profile_config('description') or
self._needs_to_change_profile_config('devices')
)
def _apply_profile_configs(self):
config = self.old_profile_json.copy()
for k, v in self.config.iteritems():
config[k] = v
self.client.do('PUT', '/1.0/profiles/{}'.format(self.name), config)
self.actions.append('apply_profile_configs')
def _delete_profile(self):
self.client.do('DELETE', '/1.0/profiles/{}'.format(self.name))
self.actions.append('delete')
def run(self): def run(self):
"""Run the main method.""" """Run the main method."""
@ -633,15 +521,10 @@ class LxdContainerManagement(object):
if self.trust_password is not None: if self.trust_password is not None:
self.client.authenticate(self.trust_password) self.client.authenticate(self.trust_password)
if self.type == 'container': self.old_container_json = self._get_container_json()
self.old_container_json = self._get_container_json() self.old_state = self._container_json_to_module_state(self.old_container_json)
self.old_state = self._container_json_to_module_state(self.old_container_json) action = getattr(self, LXD_ANSIBLE_STATES[self.state])
action = getattr(self, LXD_ANSIBLE_STATES[self.state]) action()
action()
elif self.type == 'profile':
self.old_profile_json = self._get_profile_json()
self.old_state = self._profile_json_to_module_state(self.old_profile_json)
self._update_profile()
state_changed = len(self.actions) > 0 state_changed = len(self.actions) > 0
result_json = { result_json = {
@ -665,7 +548,6 @@ class LxdContainerManagement(object):
fail_params['logs'] = e.kwargs['logs'] fail_params['logs'] = e.kwargs['logs']
self.module.fail_json(**fail_params) self.module.fail_json(**fail_params)
def main(): def main():
"""Ansible Main module.""" """Ansible Main module."""
@ -675,14 +557,6 @@ def main():
type='str', type='str',
required=True required=True
), ),
new_name=dict(
type='str',
),
type=dict(
type='str',
choices=CONFIG_PARAMS.keys(),
default='container'
),
architecture=dict( architecture=dict(
type='str', type='str',
), ),
@ -705,7 +579,7 @@ def main():
type='dict', type='dict',
), ),
state=dict( state=dict(
choices=list(set(LXD_ANSIBLE_STATES.keys()) | set(PROFILES_STATES)), choices=LXD_ANSIBLE_STATES.keys(),
default='started' default='started'
), ),
timeout=dict( timeout=dict(
@ -743,7 +617,7 @@ def main():
supports_check_mode=False, supports_check_mode=False,
) )
lxd_manage = LxdContainerManagement(module=module) lxd_manage = LXDContainerManagement(module=module)
lxd_manage.run() lxd_manage.run()
# import module bits # import module bits

Loading…
Cancel
Save