需要脚本以通过Packer构建的Ubuntu服务器18.04的用户登录名运行

时间:2019-03-29 10:11:30

标签: python shell azure ubuntu-18.04

有点奇怪,所以请忍受我。

我正在使用Packer构建Azure VM映像。安装的一部分需要安装一些Python库。我可以通过Packer运行列表中的Shell脚本执行此操作,但是在密封映像并准备使用它们时,不会安装这些库。

我发现未安装这些库是因为它已安装到用户配置文件中,并且Packer流程的一部分是在“重新密封”图像以供使用时删除该用户配置文件。

我已经用多种方法搜索了Google,但是我没有找到任何可以让我在不存在的用户登录时作为脚本运行的东西,例如,当我们第一次使用该图像并登录时,已创建。

有人知道我第一次使用登录时如何运行此脚本吗?

#!/bin/bash

cd /


echo "Testing to make sure that script performed as expected, and basic scenarios work"
for cmd in python pip; do
    if ! command -v $cmd; then
        echo "$cmd was not installed or not found on PATH"
        exit 1
    fi
done


list1=(
    pandevice
    pan-python
    requests
    requests_toolbelt
    requests[security]
)

for i in "${list1[@]}"; do
    pip install $i
done


list2=(
    asn1crypto
    certifi
    cffi
    chardet
    cryptography
    enum34
    idna
    ipaddress
    pan-python
    pandevice
    pycparser
    pyOpenSSL
    requests
    requests-toolbelt
    six
    urllib3
)

for x in "${list2[@]}"; do
    if ! pip freeze | grep $x; then
        echo "$x was not installed or not found on PATH"
        exit 1
    fi
done

请注意,我已经考虑过使用sudo pip installWhat are the risks of running 'sudo pip'?

1 个答案:

答案 0 :(得分:0)

我很好奇您的打包器文件的样子。我已经使用root如下运行了一些脚本。

打包程序文件示例:

{
    "variables": {
        "image_class": "centos7-base",
        "build_number": ""
    },
    "builders": [
        {
            "type": "googlecompute",
            "source_image_family": "{{ user `google_base_image_family` }}",
            "account_file": "{{ user `gce_service_account` }}",
            "image_family": "{{ user `_image_family` }}-{{ user `image_class` }}",
            "image_name": "wp-{{ user `image_class` }}-b{{ user `build_number` }}-{{ timestamp }}",
            "project_id": "{{ user `gce_project_id` }}",
            "ssh_username": "{{ user `ssh_username` }}",
            "subnetwork": "{{ user `gce_subnetwork` }}",
            "network": "{{ user `gce_network` }}",
            "zone": "{{ user `gce_zone` }}",
            "omit_external_ip": "true",
            "use_internal_ip": "true",
            "disk_size": 20

        }
    ],
    "provisioners": [
        {
            "type": "shell",
            "only": ["googlecompute"],
            "script": "base-image.sh",
            "skip_clean": true,
            "execute_command": "sudo chmod +x {{ .Path }}; sudo {{ .Vars }} {{ .Path }}"
        }
    ],
    "post-processors": [
    ]
}

此文件用于Google Cloud。重要部分是provisioner: shell

"provisioners": [
        {
            "type": "shell",
            "only": ["googlecompute"],
            "script": "{{ user `provisioner_root` }}/shell/base-image.sh",
            "skip_clean": true,
            "execute_command": "sudo chmod +x {{ .Path }}; sudo {{ .Vars }} {{ .Path }}"

在base_image中进行的安装是持久的。总的来说,我认为在正在运行的服务器上进行安装不是一个好主意。这与不可变服务器的想法背道而驰。