Esempio n. 1
0
    def test_template_builders(self):
        expected_json = """
        {
          "builders": [
            {
              "source": "/source/path",
              "target": "/target/path",
              "type": "file"
            },
            {
              "source": "/source/path",
              "target": "/target/path",
              "type": "file"
            }
          ]
        }
        """

        t = Template()
        t.add_builder([
            builder.File(
                target="/target/path",
                source="/source/path",
            ),
            builder.File(
                target="/target/path",
                source="/source/path",
            )
        ])

        to_json = t.to_json()
        assert to_json == json.dumps(json.loads(expected_json),
                                     sort_keys=True,
                                     indent=2,
                                     separators=(',', ': '))
Esempio n. 2
0
    def test_template_provisioners(self):
        expected_json = """
        {
          "provisioners": [
            {
              "source": "/src/path",
              "destination": "/dest/path",
              "direction": "upload",
              "type": "file"
            }
          ]
        }
        """

        t = Template()
        t.add_provisioner(
            provisioner.File(
                source="/src/path",
                destination="/dest/path",
                direction=provisioner.File.Upload,
            ))

        to_json = t.to_json()
        assert to_json == json.dumps(json.loads(expected_json),
                                     sort_keys=True,
                                     indent=2,
                                     separators=(',', ': '))
    def test_support_only(self):
        expected_json = """
        {
          "provisioners": [
            {
              "type": "shell",
              "inline": [ "ls" ],
              "except": [ "azure-arm" ]
            }
          ]
        }
        """

        p = provisioner.Shell(inline=["ls"])

        p.__setattr__('except', ["azure-arm"])

        t = Template()
        t.add_provisioner(p)

        to_json = t.to_json()
        assert to_json == json.dumps(json.loads(expected_json),
                                     sort_keys=True,
                                     indent=2,
                                     separators=(',', ': '))
Esempio n. 4
0
    def test_template_variables(self):
        t = Template()

        t.add_variable(UserVar("my_var", "my_value"))

        d = t.to_dict()
        assert d['variables'] == {'my_var': 'my_value'}
Esempio n. 5
0
    def test_sensitve_variables(self):
        expected_json = """
                {
                  "variables": {
                    "my_secret": "{{env `MY_SECRET`}}",
                    "not_a_secret": "plaintext",
                    "foo": "bar"
                  },
                  "sensitive-variables": [
                    "my_secret",
                    "foo"
                  ]
                }
                """

        t = Template()
        vars = [
            EnvVar("my_secret", "MY_SECRET"),
            UserVar("not_a_secret", "plaintext"),
            UserVar("foo", "bar"),
        ]
        t.add_variable(vars)
        t.add_sensitive_variable("my_secret")
        t.add_sensitive_variable("foo")

        to_json = t.to_json()
        assert to_json == json.dumps(json.loads(expected_json),
                                     sort_keys=True,
                                     indent=2,
                                     separators=(',', ': '))
Esempio n. 6
0
    def test_template(self):
        t = Template(description="test description",
                     min_packer_version="0.9.0")

        d = t.to_dict()
        assert d['description'] == "test description"
        assert d['min_packer_version'] == "0.9.0"

        t.add_description("new description")
        t.add_min_packer_version("1.0.0")
        d = t.to_dict()
        assert d['description'] == "new description"
        assert d['min_packer_version'] == "1.0.0"
Esempio n. 7
0
    def test_template_post_processors(self):
        expected_json = """
        {
          "post-processors": [
            {
              "script": "/my/post/script",
              "type": "shell-local"
            }
          ]
        }
        """

        t = Template()
        t.add_post_processor(
            post_processor.ShellLocal(script="/my/post/script", ))

        to_json = t.to_json()
        assert to_json == json.dumps(json.loads(expected_json),
                                     sort_keys=True,
                                     indent=2,
                                     separators=(',', ': '))
Esempio n. 8
0
    def test_variable_no_duplicate_entries(self):
        expected_json = """
                {
                  "variables": {
                     "my_var1": "a value",
                     "my_var2": ""
                  }
                }
                """

        t = Template()
        vars = [
            UserVar("my_var1", "a value"),
            UserVar("my_var2"),
        ]
        t.add_variable(vars)

        to_json = t.to_json()
        assert to_json == json.dumps(json.loads(expected_json),
                                     sort_keys=True,
                                     indent=2,
                                     separators=(',', ': '))
Esempio n. 9
0
    def test_support_named_builds(self):
        expected_json = """
                {
                  "builders": [
                    {
                      "type": "file",
                      "name": "linuxFileBuilder",
                      "source": "/tmp/source/path",
                      "target": "/tmp/target/path"
                    },
                    {
                      "type": "file",
                      "name": "windowsFileBuilder",
                      "source": "C:/Source/Path",
                      "target": "C:/Target/Path"
                    }
                  ]
                }
                """

        b = [
            builder.File(
                name="linuxFileBuilder",
                source="/tmp/source/path",
                target="/tmp/target/path",
            ),
            builder.File(
                name="windowsFileBuilder",
                source='C:/Source/Path',
                target='C:/Target/Path',
            )
        ]

        t = Template()
        t.add_builder(b)

        to_json = t.to_json()
        assert to_json == json.dumps(json.loads(expected_json), sort_keys=True, indent=2,
                                     separators=(',', ': '))
Esempio n. 10
0
def main():
	"""
	main method.
	"""

	args = get_args()
	
	ami_config_file = args.var_file

	ami_config = get_config(ami_config_file)

	target_ami_name = generate_ami_name(ami_config['ami_name_prefix'])

	print(target_ami_name)

	template = Template()

	template.add_builder(
		builder.AmazonEbs(
			region=ami_config['region'],
			ami_name=target_ami_name,
			instance_type=ami_config['instance_type'],
			source_ami=ami_config['source_ami'],
			ssh_username=ami_config['ssh_username'],
			ami_description=ami_config['ami_description'],
			ami_virtualization_type=ami_config['ami_virtualization_type'],
			force_deregister=ami_config['force_deregister'],
			shutdown_behavior=ami_config['shutdown_behavior'],
			vpc_id=ami_config['vpc_id'],
			subnet_id=ami_config['subnet_id'],
			ssh_private_key_file=ami_config['ssh_private_key_file'],
			ssh_keypair_name=ami_config['ssh_keypair_name'],
			security_group_id=ami_config['security_group_id'],
		)
	)

	template.add_provisioner(
		provisioner.Ansible(
			playbook_file=ami_config['playbook_name'],
			command=ami_config['cmd_ansible'],
			user=ami_config['ssh_username'],
		)
	)

	PackerExecutable(machine_readable=False)

	p = PackerExecutable(executable_path=ami_config['cmd_packer'])

	(ret, out, err) = p.build(
		template.to_json(),
	)

	print(out)
	print(err)
Esempio n. 11
0
    def test_support_pause_before(self):
        expected_json = """
        {
          "provisioners": [
            {
              "type": "shell",
              "inline": [ "ls" ],
              "pause_before": "10s"
            }
          ]
        }
        """

        p = provisioner.Shell(inline=["ls"], pause_before="10s")

        t = Template()
        t.add_provisioner(p)

        to_json = t.to_json()
        assert to_json == json.dumps(json.loads(expected_json),
                                     sort_keys=True,
                                     indent=2,
                                     separators=(',', ': '))
Esempio n. 12
0
    def test_property_attributes_renders(self):
        expected_json = """
                        {
                          "provisioners": [
                            {
                              "attributes": ["examples/linux.yml"],
                              "profile": "a_profile",
                              "type": "inspec"
                            }
                          ]
                        }
                        """

        t = Template()
        p = provisioner.Inspec(
                attributes=["examples/linux.yml"],
                profile="a_profile"
            )

        t.add_provisioner(p)

        to_json = t.to_json()
        assert to_json == json.dumps(json.loads(expected_json), sort_keys=True, indent=2,
                                     separators=(',', ': '))
Esempio n. 13
0
    def test_variable_duplicate_entries(self):
        t = Template()
        vars = [
            UserVar("my_var"),
            UserVar("my_var"),
        ]
        with pytest.raises(ValueError) as excinfo:
            t.add_variable(vars)
        assert 'duplicate key "my_var" detected' == str(excinfo.value)

        with pytest.raises(ValueError) as excinfo:
            t.add_variable(UserVar("my_var"))
        assert 'duplicate key "my_var" detected' == str(excinfo.value)
Esempio n. 14
0
class TestPacker(unittest.TestCase):

    aws_access_key = UserVar("aws_access_key", "")
    aws_secret_key = UserVar("aws_secret_key", "")
    user_variables = [aws_access_key, aws_secret_key]
    builders = [
        builder.AmazonEbs(access_key=Ref(aws_access_key),
                          secret_key=Ref(aws_secret_key),
                          region="us-east-1",
                          source_ami_filter=builder.AmazonSourceAmiFilter(
                              filters={
                                  "virtualization-type": "hvm",
                                  "name":
                                  "*ubuntu-xenial-16.04-amd64-server-*",
                                  "root-device-type": "ebs"
                              },
                              owners=["099720109477"],
                              most_recent=True),
                          instance_type="t2.micro",
                          ami_name="packer-example {{timestamp}}",
                          ssh_username="******")
    ]
    template = Template()
    template.add_variable(user_variables)
    template.add_builder(builders)

    def test_validate(self):
        output = packer.validate(TestPacker.template)
        assert output.return_code == 0
        assert "successfully" in output.output

    def test_build(self):
        output = packer.build(TestPacker.template)
        assert output.return_code == 0
        assert "successful" in output.output

    def test_inspect(self):
        output = packer.inspect(TestPacker.template)
        assert output.return_code == 0
Esempio n. 15
0
 def create_template_from_config(self, tag_configs):
     """
     Generate a packer template using configurations.
     :param tag_configs: dict containing the tag details
     :return: template of type packerlicious.Template
     """
     template = Template()
     template.add_builder(
         builder.AmazonEbs(
             access_key="{{user `aws_access_key`}}",
             secret_key="{{user `aws_secret_key`}}",
             region=builder_config.get("region", "ap-southeast-2"),
             instance_type=builder_config.get("type", "t2.micro"),
             ssh_username="******",
             ami_name=self.ami_name,
             source_ami="ami-02769748522663066",
             tags=tag_configs))
     template.add_provisioner(provisioner.Shell(script=script_path))
     return template
Esempio n. 16
0
cloud_token = UserVar("cloud_token", token)

user_variables = [cloud_token]

builders = [builder.Null(communicator="none")]

post_processors = [[
    post_processor.Artifice(files=["builds/ubuntu1804-desktop-base.box"]),
    post_processor.VagrantCloud(box_tag="catosplace/ubuntu1804-desktop-base",
                                access_token=Ref(cloud_token),
                                version="1.0.2"),
    #post_processor.Checksum(
    #    checksum_types = [ "md5", "sha1", "sha256" ]
    #),
]]

t = Template()
t.add_variable(user_variables)
t.add_builder(builders)
t.add_post_processor(post_processors)

print(t.to_json())

(ret, out,
 err) = PackerExecutable(machine_readable=False).validate(t.to_json())
print(out.decode('unicode_escape'))

(ret, out, err) = PackerExecutable(machine_readable=False).build(t.to_json())
print(out.decode('unicode_escape'))
# https://www.packer.io/intro/getting-started/build-image.html#the-template
from packerlicious import builder, Ref, Template, UserVar

aws_access_key = UserVar("aws_access_key", "")
aws_secret_key = UserVar("aws_secret_key", "")
user_variables = [aws_access_key, aws_secret_key]

builders = [
    builder.AmazonEbs(access_key=Ref(aws_access_key),
                      secret_key=Ref(aws_secret_key),
                      region="us-east-1",
                      source_ami_filter=builder.AmazonSourceAmiFilter(
                          filters={
                              "virtualization-type": "hvm",
                              "name": "*ubuntu-xenial-16.04-amd64-server-*",
                              "root-device-type": "ebs"
                          },
                          owners=["099720109477"],
                          most_recent=True),
                      instance_type="t2.micro",
                      ami_name="packer-example {{timestamp}}",
                      ssh_username="******")
]

t = Template()
t.add_variable(user_variables)
t.add_builder(builders)

t.to_json()
Esempio n. 18
0
            str(current_box_version["version"].split('.')[1]) + "." + \
            str(int(current_box_version["version"].split('.')[2]) + 1)

print("Building new catosplace/ubuntu1804-desktop-base box version " + next_box_version)
version = UserVar("version", next_box_version)

post_processors = [
    post_processor.Vagrant(
        output = "builds/ubuntu1804-desktop-base.box",
        include = [
            "info.json"
        ]
    )
]

t = Template()
t.add_variable(desktop_user_variables)
t.add_variable(version)
t.add_builder(builders)
t.add_provisioner(provisioners)
# Move to new script user artifice
#t.add_post_processor(post_processors)

# View Packer Template
print(t.to_json())

(ret, out, err) = PackerExecutable(machine_readable=False).validate(t.to_json())
print(out.decode('unicode_escape'))

(ret, out, err) = PackerExecutable(machine_readable=False).build(t.to_json())
print(out.decode('unicode_escape'))
Esempio n. 19
0
    def test_jagged_array_render(self):
        expected_json = """
        {
          "builders": [
            {
              "boot_wait": "10s",
              "floppy_files": [
                ""
              ],
              "guest_additions_path": "VBoxGuestAdditions_{{.Version}}.iso",
              "guest_os_type": "Ubuntu_64",
              "http_directory": "",
              "iso_checksum": "sha512",
              "iso_checksum_type": "sha512",
              "iso_url": "",
              "ssh_port": 22,
              "type": "virtualbox-iso",
              "vboxmanage": [
                [
                  "modifyvm", "{{.Name}}", "--memory", "1024"
                ],
                [ 
                  "modifyvm", "{{.Name}}", "--vram", "36"
                ],
                [
                  "modifyvm", "{{.Name}}", "--cpus", "1"
                ]
              ],
              "virtualbox_version_file": ".vbox_version",
              "vm_name": "my_name"
            }
          ]
        }
        """

        t = Template()
        t.add_builder(
            builder.VirtualboxIso(
                boot_wait="10s",
                guest_os_type="Ubuntu_64",
                http_directory="",
                iso_url="",
                iso_checksum_type="sha512",
                iso_checksum="sha512",
                ssh_port=22,
                guest_additions_path="VBoxGuestAdditions_{{.Version}}.iso",
                virtualbox_version_file=".vbox_version",
                vm_name="my_name",
                floppy_files=[""],
                vboxmanage=[
                    "modifyvm {{.Name}} --memory 1024".split(),
                    "modifyvm {{.Name}} --vram 36".split(),
                    "modifyvm {{.Name}} --cpus 1".split()
                ]
                # vboxmanage=[['modifyvm {{.Name}} --memory 1024', "modifyvm {{.Name}} --cpus 1"]]
            ))

        to_json = t.to_json()
        assert to_json == json.dumps(json.loads(expected_json),
                                     sort_keys=True,
                                     indent=2,
                                     separators=(',', ': '))