func()

in google_guest_agent/network/manager/network_manager_linux.go [284:347]


func (n *networkManager) writeNetworkManagerConfigs(ifaces []string) ([]string, error) {
	var result []string

	for i, iface := range ifaces {
		if !shouldManageInterface(i == 0) {
			logger.Debugf("ManagePrimaryNIC is disabled, skipping writeNetworkManagerConfigs for %s", iface)
			continue
		}
		if isInvalid(iface) {
			continue
		}
		logger.Debugf("writing nmconnection file for %s", iface)

		configFilePath := n.networkManagerConfigFilePath(iface)
		connID := fmt.Sprintf("google-guest-agent-%s", iface)

		// Create the ini file.
		config := nmConfig{
			GuestAgent: guestAgentSection{
				ManagedByGuestAgent: true,
			},
			Connection: nmConnectionSection{
				InterfaceName: iface,
				ID:            connID,
				ConnType:      "ethernet",
			},
			Ipv4: nmIPv4Section{
				Method: "auto",
			},
			Ipv6: nmIPv6Section{
				Method: "auto",
			},
		}

		// Save the config.
		if err := writeIniFile(configFilePath, &config); err != nil {
			return []string{}, fmt.Errorf("error saving connection config for %s: %v", iface, err)
		}

		// The permissions need to be 600 in order for nmcli to load and use the file correctly.
		if err := os.Chmod(configFilePath, nmConfigFileMode); err != nil {
			return []string{}, fmt.Errorf("error updating permissions for %s connection config: %v", iface, err)
		}

		// Clean up the files written by the old agent. Make sure they're managed
		// by the agent before deleting them.
		ifcfgFilePath := n.ifcfgFilePath(iface)
		contents, err := os.ReadFile(ifcfgFilePath)
		if err != nil && !os.IsNotExist(err) {
			return nil, fmt.Errorf("failed to read ifcfg file(%s): %v", ifcfgFilePath, err)
		}

		// Check for the google comment.
		if strings.Contains(string(contents), "# Added by Google Compute Engine OS Login.") {
			if err = os.Remove(ifcfgFilePath); err != nil {
				return nil, fmt.Errorf("failed to remove previously managed ifcfg file(%s): %v", ifcfgFilePath, err)
			}
		}

		result = append(result, iface)
	}

	return result, nil
}