Pulumi 已经从 Hugo 迁移到 VitePress,结构和 Docs-iSharkFly-Com 一致 #1
+384
File diff suppressed because it is too large
Load Diff
Generated
+12
@@ -0,0 +1,12 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Markdown personal settings
|
||||
/markdown.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Ignored default folder with query files
|
||||
/queries/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
Generated
+1
-4
@@ -1,9 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2">
|
||||
<component name="ProjectRootManager">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
<component name="ThriftCompiler">
|
||||
<compilers />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ThriftCompiler">
|
||||
<compilers />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,134 @@
|
||||
import { defineConfig, type DefaultTheme } from 'vitepress';
|
||||
import sidebar from './sidebar.json' with { type: 'json' };
|
||||
|
||||
const SITE_URL = 'https://pulumi.isharkfly.com/';
|
||||
const FORUM_URL = 'https://www.isharkfly.com';
|
||||
const REPO_URL = 'https://src.sharkdat.com/iSharkFly-Docs/Pulumi';
|
||||
|
||||
// iSharkFly links shown as a dropdown at the end of the nav bar.
|
||||
function isharkflyNav(zh: boolean): DefaultTheme.NavItem {
|
||||
return {
|
||||
text: 'iSharkFly',
|
||||
items: [
|
||||
{ text: zh ? 'iSharkFly' : 'iSharkFly', link: FORUM_URL },
|
||||
{ text: zh ? '文档导航' : 'Docs Portal', link: 'https://docs.isharkfly.com/' },
|
||||
{ text: zh ? '本站源码' : 'Source Code', link: REPO_URL },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const zhThemeText: DefaultTheme.Config = {
|
||||
outline: { level: [2, 3], label: '本页目录' },
|
||||
docFooter: { prev: '上一页', next: '下一页' },
|
||||
darkModeSwitchLabel: '外观',
|
||||
lightModeSwitchTitle: '切换到浅色模式',
|
||||
darkModeSwitchTitle: '切换到深色模式',
|
||||
sidebarMenuLabel: '菜单',
|
||||
returnToTopLabel: '回到顶部',
|
||||
langMenuLabel: '切换语言',
|
||||
skipToContentLabel: '跳到正文',
|
||||
notFound: {
|
||||
title: '页面未找到',
|
||||
quote: '你要找的页面不存在,或者已经被移动。',
|
||||
linkLabel: '返回首页',
|
||||
linkText: '返回首页',
|
||||
},
|
||||
footer: {
|
||||
message: '文档内容翻译自 Pulumi 官方文档。',
|
||||
copyright: `版权所有 © 2021-${new Date().getFullYear()} iSharkFly.com`,
|
||||
},
|
||||
};
|
||||
|
||||
const zhSearchText = {
|
||||
button: { buttonText: '搜索', buttonAriaLabel: '搜索' },
|
||||
modal: {
|
||||
displayDetails: '显示详细列表',
|
||||
resetButtonTitle: '清除查询',
|
||||
backButtonTitle: '关闭搜索',
|
||||
noResultsText: '没有找到结果',
|
||||
footer: {
|
||||
selectText: '选择',
|
||||
selectKeyAriaLabel: '回车',
|
||||
navigateText: '切换',
|
||||
navigateUpKeyAriaLabel: '向上',
|
||||
navigateDownKeyAriaLabel: '向下',
|
||||
closeText: '关闭',
|
||||
closeKeyAriaLabel: 'Esc',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// https://vitepress.dev/reference/site-config
|
||||
export default defineConfig({
|
||||
srcDir: 'docs',
|
||||
lang: 'zh-CN',
|
||||
title: 'Pulumi 中文文档',
|
||||
description: 'Pulumi 基础设施即代码(IaC)中文文档和博客',
|
||||
cleanUrls: true,
|
||||
lastUpdated: false,
|
||||
ignoreDeadLinks: true,
|
||||
sitemap: {
|
||||
hostname: SITE_URL,
|
||||
},
|
||||
head: [
|
||||
['link', { rel: 'icon', href: '/favicon.ico' }],
|
||||
// Google Tag Manager
|
||||
['script', {}, `(function (w, d, s, l, i) {
|
||||
w[l] = w[l] || [];
|
||||
w[l].push({
|
||||
'gtm.start':
|
||||
new Date().getTime(), event: 'gtm.js'
|
||||
});
|
||||
var f = d.getElementsByTagName(s)[0],
|
||||
j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : '';
|
||||
j.async = true;
|
||||
j.src =
|
||||
'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
|
||||
f.parentNode.insertBefore(j, f);
|
||||
})(window, document, 'script', 'dataLayer', 'GTM-W3NL9V');`],
|
||||
// End Google Tag Manager
|
||||
// Matomo Tag Manager
|
||||
['script', {}, `var _mtm = window._mtm = window._mtm || [];
|
||||
_mtm.push({'mtm.startTime': (new Date().getTime()), 'event': 'mtm.Start'});
|
||||
(function() {
|
||||
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
|
||||
g.async=true; g.src='https://analytics.sharkdat.com/js/container_yMtZdGlf.js'; s.parentNode.insertBefore(g,s);
|
||||
})();`],
|
||||
// End Matomo Tag Manager
|
||||
// Google AdSense
|
||||
['script', {
|
||||
async: '',
|
||||
src: 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4797644559430915',
|
||||
crossorigin: 'anonymous',
|
||||
}],
|
||||
],
|
||||
markdown: {
|
||||
theme: { light: 'github-light', dark: 'github-dark' },
|
||||
},
|
||||
themeConfig: {
|
||||
...zhThemeText,
|
||||
// https://vitepress.dev/reference/default-theme-config
|
||||
logo: '/logos/brand/pulumi-mark-purple.svg',
|
||||
nav: [
|
||||
{ text: '主页', link: '/' },
|
||||
{ text: '文档', link: '/docs/', activeMatch: '^/docs/' },
|
||||
{ text: '博客', link: '/blog/', activeMatch: '^/blog/' },
|
||||
isharkflyNav(true),
|
||||
],
|
||||
search: {
|
||||
provider: 'local',
|
||||
options: {
|
||||
translations: zhSearchText,
|
||||
},
|
||||
},
|
||||
// Generated from the Hugo menus / weights when the site was migrated; edit by hand from now on.
|
||||
sidebar: sidebar as DefaultTheme.SidebarMulti,
|
||||
socialLinks: [
|
||||
{ icon: 'git', link: `${REPO_URL}.git` },
|
||||
],
|
||||
editLink: undefined,
|
||||
} as DefaultTheme.Config,
|
||||
vite: {
|
||||
build: { chunkSizeWarningLimit: 4096 },
|
||||
},
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,58 @@
|
||||
// Shared selection state for <Chooser> / <Choosable>, replacing Hugo's pulumi-chooser web components.
|
||||
// A selection made in one chooser (e.g. language = python) applies to every choosable of that type on
|
||||
// the site and is remembered in localStorage.
|
||||
import { reactive } from 'vue'
|
||||
|
||||
const STORAGE_KEY = 'pulumi-chooser'
|
||||
|
||||
export const DEFAULTS: Record<string, string> = {
|
||||
language: 'typescript',
|
||||
'k8s-language': 'typescript',
|
||||
os: 'macos',
|
||||
cloud: 'aws',
|
||||
}
|
||||
|
||||
export const LABELS: Record<string, string> = {
|
||||
javascript: 'JavaScript',
|
||||
typescript: 'TypeScript',
|
||||
python: 'Python',
|
||||
go: 'Go',
|
||||
csharp: 'C#',
|
||||
fsharp: 'F#',
|
||||
visualbasic: 'VB',
|
||||
yaml: 'YAML',
|
||||
macos: 'macOS',
|
||||
linux: 'Linux',
|
||||
windows: 'Windows',
|
||||
aws: 'AWS',
|
||||
azure: 'Azure',
|
||||
gcp: 'Google Cloud',
|
||||
kubernetes: 'Kubernetes',
|
||||
}
|
||||
|
||||
export const selection = reactive<Record<string, string>>({ ...DEFAULTS })
|
||||
|
||||
let loaded = false
|
||||
export function loadSelection() {
|
||||
if (loaded || typeof window === 'undefined') return
|
||||
loaded = true
|
||||
try {
|
||||
Object.assign(selection, JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}'))
|
||||
} catch {
|
||||
// ignore malformed storage
|
||||
}
|
||||
}
|
||||
|
||||
export function select(type: string, value: string, persist = true) {
|
||||
selection[type] = value
|
||||
if (!persist || typeof window === 'undefined') return
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}')
|
||||
saved[type] = value
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(saved))
|
||||
} catch {
|
||||
// storage unavailable
|
||||
}
|
||||
}
|
||||
|
||||
export const splitList = (s?: string) => (s || '').split(',').map((v) => v.trim()).filter(Boolean)
|
||||
@@ -0,0 +1,23 @@
|
||||
<!-- .vitepress/theme/components/AdSenseAside.vue -->
|
||||
<template>
|
||||
<div class="adsense-aside">
|
||||
<ins class="adsbygoogle"
|
||||
style="display:block"
|
||||
data-ad-client="ca-pub-4797644559430915"
|
||||
data-ad-slot="1781911644"
|
||||
data-ad-format="auto"
|
||||
data-full-width-responsive="true"></ins>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import {onMounted} from 'vue'
|
||||
|
||||
onMounted(() => {
|
||||
try {
|
||||
(window.adsbygoogle = window.adsbygoogle || []).push({})
|
||||
} catch (e) {
|
||||
console.error('AdSense error:', e)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,16 @@
|
||||
<!-- Content shown only while its value is selected in the <Chooser> of the same type. -->
|
||||
<template>
|
||||
<component :is="inline ? 'span' : 'div'" v-show="visible" class="pulumi-choosable">
|
||||
<slot />
|
||||
</component>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { loadSelection, selection, splitList } from '../chooser'
|
||||
|
||||
const props = defineProps<{ type: string; values: string; inline?: boolean }>()
|
||||
const visible = computed(() => splitList(props.values).includes(selection[props.type]))
|
||||
|
||||
onMounted(loadSelection)
|
||||
</script>
|
||||
@@ -0,0 +1,29 @@
|
||||
<!-- Tab bar that picks which <Choosable> blocks of the same type are shown. -->
|
||||
<template>
|
||||
<div class="pulumi-chooser" role="tablist">
|
||||
<button
|
||||
v-for="opt in list"
|
||||
:key="opt"
|
||||
type="button"
|
||||
role="tab"
|
||||
:aria-selected="current === opt"
|
||||
:class="{ active: current === opt }"
|
||||
@click="select(type, opt)"
|
||||
>{{ LABELS[opt] || opt }}</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { LABELS, loadSelection, select, selection, splitList } from '../chooser'
|
||||
|
||||
const props = defineProps<{ type: string; options: string }>()
|
||||
const list = computed(() => splitList(props.options))
|
||||
const current = computed(() => selection[props.type])
|
||||
|
||||
onMounted(() => {
|
||||
loadSelection()
|
||||
// The remembered choice may not be offered on this page (e.g. options="csharp,fsharp").
|
||||
if (!list.value.includes(selection[props.type]) && list.value.length) select(props.type, list.value[0], false)
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,23 @@
|
||||
// https://vitepress.dev/guide/custom-theme
|
||||
import {h} from 'vue'
|
||||
import type {Theme} from 'vitepress'
|
||||
import DefaultTheme from 'vitepress/theme'
|
||||
import './style.css'
|
||||
import AdSenseAside from './components/AdSenseAside.vue'
|
||||
import Chooser from './components/Chooser.vue'
|
||||
import Choosable from './components/Choosable.vue'
|
||||
|
||||
export default {
|
||||
extends: DefaultTheme,
|
||||
Layout: () => {
|
||||
return h(DefaultTheme.Layout, null, {
|
||||
// https://vitepress.dev/guide/extending-default-theme#layout-slots
|
||||
'aside-ads-before': () => h(AdSenseAside)
|
||||
})
|
||||
},
|
||||
enhanceApp({app}) {
|
||||
// Replacements for the Hugo chooser/choosable shortcodes used across the docs
|
||||
app.component('Chooser', Chooser)
|
||||
app.component('Choosable', Choosable)
|
||||
}
|
||||
} satisfies Theme
|
||||
File diff suppressed because it is too large
Load Diff
Vendored
+156
@@ -0,0 +1,156 @@
|
||||
pipeline {
|
||||
agent any
|
||||
|
||||
options {
|
||||
ansiColor('xterm')
|
||||
disableConcurrentBuilds()
|
||||
timeout(time: 30, unit: 'MINUTES')
|
||||
}
|
||||
|
||||
tools {
|
||||
nodejs 'NodeJS 22.14.0'
|
||||
}
|
||||
|
||||
environment {
|
||||
PRJ_NAME = 'pulumi-isharkfly-com'
|
||||
// 显式指定 wrangler 配置文件
|
||||
WRANGLER_CONFIG = 'wrangler.jsonc'
|
||||
// 发布到线上的分支
|
||||
RELEASE_BRANCH = 'main'
|
||||
// Worker Preview 的自定义预览域名
|
||||
PREVIEW_DOMAIN = 'docs.sharkdat.com'
|
||||
// Cloudflare API Token(Jenkins Secret text 凭据,需要 Workers Scripts:Edit 权限)
|
||||
CLOUDFLARE_API_TOKEN = credentials('sharkdat-cloudflare-api-token')
|
||||
// Cloudflare Account ID(Secret text 凭据)。设置后 wrangler 不再调用 /memberships 查询账号,
|
||||
// 避免 token 缺少 Account 读取权限时报 "You may have incorrect permissions on your API token"
|
||||
CLOUDFLARE_ACCOUNT_ID = credentials('sharkdat-cloudflare-account-id')
|
||||
// 不让 wrangler 发送使用统计、不弹交互提示
|
||||
WRANGLER_SEND_METRICS = 'false'
|
||||
CI = 'true'
|
||||
}
|
||||
|
||||
stages {
|
||||
stage('Configure') {
|
||||
steps {
|
||||
sh 'git config --global url."https://github.com/".insteadOf git://github.com/'
|
||||
sh '''
|
||||
set -eu
|
||||
corepack enable
|
||||
node --version
|
||||
pnpm --version
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Install') {
|
||||
steps {
|
||||
sh 'pnpm install --frozen-lockfile'
|
||||
}
|
||||
}
|
||||
|
||||
stage('Build') {
|
||||
steps {
|
||||
echo 'Build VitePress docs ...'
|
||||
sh 'pnpm run docs:build'
|
||||
}
|
||||
}
|
||||
|
||||
stage('Deploy - CF') {
|
||||
steps {
|
||||
script {
|
||||
withEnv([
|
||||
'LANG=C.UTF-8',
|
||||
'LC_ALL=C.UTF-8',
|
||||
'NO_COLOR=1',
|
||||
'TERM=dumb'
|
||||
]) {
|
||||
// 部署消息:显示在 Cloudflare 控制台 → Worker → Deployments
|
||||
def shortSha = env.GIT_COMMIT ? env.GIT_COMMIT.take(7) : 'unknown'
|
||||
def deployMsg = "Jenkins ${env.JOB_NAME} #${env.BUILD_NUMBER} (${shortSha})"
|
||||
|
||||
// Tag 构建:部署到 production 环境(wrangler.jsonc 中的 env.production)
|
||||
if (env.TAG_NAME?.trim()) {
|
||||
sh """
|
||||
pnpm exec wrangler deploy --config ${env.WRANGLER_CONFIG} --env production \
|
||||
--message '${deployMsg}' \
|
||||
--tag '${env.TAG_NAME}'
|
||||
"""
|
||||
return
|
||||
}
|
||||
|
||||
// main 分支:部署默认 Worker
|
||||
if (env.BRANCH_NAME == env.RELEASE_BRANCH) {
|
||||
sh """
|
||||
pnpm exec wrangler deploy --config ${env.WRANGLER_CONFIG} --env="" \
|
||||
--message '${deployMsg}' \
|
||||
--tag '${shortSha}'
|
||||
"""
|
||||
return
|
||||
}
|
||||
|
||||
// PR 或其他分支:创建/更新 Worker Preview,不影响线上流量
|
||||
// 访问地址:https://<previewName>.docs.sharkdat.com
|
||||
// https://<previewName>-pulumi-isharkfly-com.huyuchengus.workers.dev
|
||||
def branchArg = env.CHANGE_ID
|
||||
? "pr-${env.CHANGE_ID}"
|
||||
: env.BRANCH_NAME
|
||||
|
||||
// 转成合法的 DNS 标签:小写、只含 a-z0-9-,并限制长度
|
||||
// (<deployment-id>-<previewName> 也要放进一个 63 字符的子域名标签里)
|
||||
def previewName = branchArg
|
||||
.toLowerCase()
|
||||
.replaceAll(/[^a-z0-9-]+/, '-')
|
||||
.replaceAll(/^-+|-+$/, '')
|
||||
previewName = previewName.take(40).replaceAll(/-+$/, '')
|
||||
|
||||
// 打印当前 token 所属账号,便于排查 "Worker does not yet exist"(通常是账号不对)
|
||||
sh 'pnpm exec wrangler whoami'
|
||||
|
||||
// Preview 挂在已有 Worker 下;首次构建时先 deploy 一次创建 Worker
|
||||
def workerExists = sh(
|
||||
script: "pnpm exec wrangler deployments list --config ${env.WRANGLER_CONFIG} --env=\"\" > /dev/null 2>&1",
|
||||
returnStatus: true
|
||||
) == 0
|
||||
if (!workerExists) {
|
||||
echo "Worker ${env.PRJ_NAME} 尚不存在,先执行首次 deploy 创建 Worker ..."
|
||||
sh """
|
||||
pnpm exec wrangler deploy --config ${env.WRANGLER_CONFIG} --env="" \
|
||||
--message 'Initial deploy: ${deployMsg}'
|
||||
"""
|
||||
}
|
||||
|
||||
// 用新版 Previews(需要 wrangler >= 4.135.0),才会出现在自定义预览域名 docs.sharkdat.com 下。
|
||||
// Jenkins 检出的是 detached HEAD,无法自动识别分支,所以必须显式传 --name。
|
||||
sh """
|
||||
pnpm exec wrangler preview --config ${env.WRANGLER_CONFIG} --env="" \
|
||||
--name '${previewName}' \
|
||||
--message '${deployMsg}' \
|
||||
--tag '${shortSha}'
|
||||
"""
|
||||
|
||||
echo "Preview URL: https://${previewName}.${env.PREVIEW_DOMAIN}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
always {
|
||||
script {
|
||||
env.BUILD_STARTED_AT = new Date(currentBuild.startTimeInMillis)
|
||||
.format('yyyy-MM-dd HH:mm:ss z', TimeZone.getTimeZone('America/New_York'))
|
||||
|
||||
env.BUILD_DURATION_TEXT = currentBuild.durationString
|
||||
|
||||
emailext (
|
||||
mimeType: 'text/html; charset=UTF-8',
|
||||
subject: "Build ${currentBuild.currentResult}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
|
||||
body: '${DEFAULT_CONTENT}',
|
||||
from: '[email protected]',
|
||||
to: '[email protected], [email protected]'
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="WEB_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
@@ -0,0 +1,75 @@
|
||||
# Pulumi 中文文档
|
||||
|
||||
欢迎来到 Pulumi 中文文档项目([https://pulumi.isharkfly.com/](https://pulumi.isharkfly.com/))。本项目从 Pulumi 官方的英文文档和博客 Fork 而来,并在此基础上进行中文翻译。
|
||||
|
||||
源代码仓库:[https://src.sharkdat.com/iSharkFly-Docs/Pulumi](https://src.sharkdat.com/iSharkFly-Docs/Pulumi)
|
||||
|
||||
## 中文本地化说明
|
||||
|
||||
如果您有兴趣参与我们的小组和项目,请使用下面的联系方式和我们联系:
|
||||
|
||||
| 联系方式名称 | 联系方式 |
|
||||
|---|---|
|
||||
| 电子邮件 | [[email protected]](mailto:[email protected]) |
|
||||
| QQ 或微信 | 103899765 |
|
||||
| QQ 交流群 | 15186112 |
|
||||
| 社区论坛 | [https://www.isharkfly.com/](https://www.isharkfly.com/) |
|
||||
|
||||
## 如何运行文档
|
||||
|
||||
本文档使用 [VitePress](https://vitepress.dev/) 进行编译,使用 pnpm 管理依赖(版本见 `package.json` 中的 `packageManager`,通过 `corepack enable` 启用)。
|
||||
|
||||
```bash
|
||||
corepack enable
|
||||
pnpm install
|
||||
pnpm run docs:dev # 本地预览,默认地址 http://localhost:5173/
|
||||
pnpm run docs:build # 编译静态站点,输出到 .vitepress/dist
|
||||
pnpm run docs:preview # 预览编译结果
|
||||
```
|
||||
|
||||
## 目录结构
|
||||
|
||||
| 路径 | 说明 |
|
||||
|---|---|
|
||||
| `docs/` | VitePress 源目录(`srcDir`) |
|
||||
| `docs/docs/` | Pulumi 文档:入门、概念、指南、教程等 |
|
||||
| `docs/blog/` | Pulumi 博客文章,每篇文章一个目录,图片放在文章目录中 |
|
||||
| `docs/public/` | 静态资源(图片、Logo)以及 Cloudflare 重定向规则 `_redirects` |
|
||||
| `.vitepress/config.mts` | 站点配置 |
|
||||
| `.vitepress/sidebar.json` | 文档和博客的侧边栏 |
|
||||
| `.vitepress/theme/` | 主题扩展,包括语言切换组件 `Chooser` / `Choosable` |
|
||||
|
||||
## 编写说明
|
||||
|
||||
本站最初是 Hugo 站点,已迁移到 VitePress。迁移时 Hugo 的短代码已经转换成下面的写法:
|
||||
|
||||
* 按语言(或操作系统、云平台)切换的内容使用 `Chooser` 和 `Choosable` 组件。同一类型的选择在全站共享,并保存在浏览器中:
|
||||
|
||||
~~~md
|
||||
<Chooser type="language" options="typescript,python,go,csharp" />
|
||||
|
||||
<Choosable type="language" values="typescript">
|
||||
|
||||
```ts
|
||||
// TypeScript 代码
|
||||
```
|
||||
|
||||
</Choosable>
|
||||
~~~
|
||||
|
||||
* 提示框使用 VitePress 的 `::: info` / `::: warning` 容器。
|
||||
* 新增页面后,需要在 `.vitepress/sidebar.json` 中加入对应的链接。
|
||||
* CLI 命令参考和 API 参考(`/docs/reference/cli`、`/docs/reference/pkg`)由 Pulumi 官方从源代码生成,不在本仓库中,链接直接指向 [pulumi.com](https://www.pulumi.com/docs/reference/)。
|
||||
* 旧地址(Hugo 的 `aliases` 和 `redirect_to`)的跳转规则在 `docs/public/_redirects` 中维护。
|
||||
|
||||
## 部署
|
||||
|
||||
Jenkins(见 `Jenkinsfile`)使用 corepack + pnpm 编译站点,并通过 wrangler 部署到 Cloudflare Workers 静态资源(见 `wrangler.jsonc`):
|
||||
|
||||
* `main` 分支:部署到线上 Worker;
|
||||
* Tag:部署到 `production` 环境;
|
||||
* 其他分支和 PR:创建 Worker Preview,不影响线上。
|
||||
|
||||
## 许可证
|
||||
|
||||
文档内容来自 [Pulumi](https://github.com/pulumi/pulumi-hugo),版权归原作者所有。
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
title: "2018 Year at a Glance"
|
||||
description: "As we close out 2018, here are some of the exciting things at Pulumi. We've launched our open source community, with support for many major clouds."
|
||||
date: 2018-12-31
|
||||
authors: ["joe-duffy"]
|
||||
tags: ["pulumi-news"]
|
||||
---
|
||||
# 2018 Year at a Glance
|
||||
|
||||
<p class="blog-meta">2018-12-31 · joe-duffy</p>
|
||||
|
||||
As we close out 2018, and enter into
|
||||
a New Year, I was reflecting on our progress here at Pulumi this past year and wanted to share some thoughts.
|
||||
It’s been an incredible year and we are hugely thankful to our passionate community, customers, and
|
||||
partners.
|
||||
|
||||
Here are some of the exciting things that happened:
|
||||
|
||||
**Launching our open source
|
||||
community.** After being hard at work for a little over a year,
|
||||
[we launched our open source project](/blog/introducing-pulumi-a-cloud-development-platform/),
|
||||
with the aim of making it considerably easier and more enjoyable to create and operate
|
||||
cloud software. This was a major moment for us. We had previously only shown Pulumi to a few select friends,
|
||||
family, and private beta users, and the reception was beyond our wildest expectations. We got passionate +1’s
|
||||
from cloud engineers of all roles and responsibilities -- developers, infrastructure engineers, operators, and
|
||||
managers alike. The Pulumi community has since grown to thousands of users across hundreds of companies of all
|
||||
sizes spread across the globe. The community is now a warm, welcoming, and collaborative place with significant
|
||||
open source contributions and passionate community leaders emerging who are helping one another while also
|
||||
helping us to make Pulumi even better.
|
||||
|
||||
**Support for major public, private, and hybrid clouds.** We launched with support for the three major public
|
||||
clouds, [AWS](/docs/get-started/aws/), [Azure](/docs/get-started/azure/), and
|
||||
[Google Cloud](/docs/get-started/gcp/), and have since added capabilities across all
|
||||
of them, including adding [serverless](/docs/tutorials/aws/rest-api/),
|
||||
[containers](https://github.com/pulumi/examples/blob/master/aws-ts-containers/index.ts), and
|
||||
[infrastructure](https://github.com/pulumi/examples/blob/master/aws-js-webserver/index.js)
|
||||
productivity libraries -- it is here where we believe Pulumi’s unique approach of using general purpose languages truly
|
||||
shines. We immediately had a wave of inbound interest in applying the Pulumi approach to infrastructure as code in other
|
||||
areas, and quickly added other providers including OpenStack, VMWare vSphere, Alibaba Cloud, F5 BigIP, and more. In
|
||||
September, we unveiled [a native Kubernetes provider](/docs/get-started/kubernetes/) with support for the
|
||||
entire API surface area across all versions, plus an operations tool, [KubeSpy](https://github.com/pulumi/kubespy) --
|
||||
both of which continue to lead to significant community growth. Many customers are loving that they can achieve a
|
||||
consistent engineering workflow across multi-cloud environments -- often spanning public, private, and/or hybrid clouds.
|
||||
|
||||
**Launching our commercial SaaS product.** In October, [we launched our commercial SaaS
|
||||
product](/blog/building-a-future-of-cloud-engineering/), with reasonable
|
||||
[pricing](https://www.pulumi.com/pricing/) so that teams of all sizes are able to get their code to the cloud
|
||||
productively, securely, and collaboratively. If Pulumi is like Git -- a local CLI and SDK -- then the Pulumi SaaS is
|
||||
like GitHub -- a hosted service to ensure you can use Pulumi in a team setting. In addition to the Team Edition, which
|
||||
is meant for the “Fortune 500,000,” we also launched the Enterprise Edition, for the Fortune 500. We already have
|
||||
multiple Fortune 500 customers moving into production with Pulumi, and expect this to be a significant area of future
|
||||
growth. Since launching, we’ve added support for more identity providers -- including GitHub, GitLab, and SSO/SAML (for
|
||||
Okta, ADFs, and others) -- as well as team management capabilities, such as RBAC, our GitHub App, GitHub Actions
|
||||
partnership, and more.
|
||||
|
||||
**Closing our Series A funding.** Also in October, [we secured $15MM in additional
|
||||
funds](https://www.geekwire.com/2018/pulumi-raises-15m-series-funding-round-launches-multicloud-app-deployment-service/),
|
||||
which will enable us to scale to meet the incredible opportunity in front of us. The funds will ensure that our open
|
||||
source projects are constantly improving and achieving production quality; that our commercial product can meet the most
|
||||
rigorous business requirements, small or large; and that we can grow our organization in areas necessary to meet our
|
||||
customers’ needs. When we set out to make it 10x easier for teams to do cloud engineering, we saw many facets in need of
|
||||
attention, and these funds will help us take concrete steps towards realizing the vision.
|
||||
|
||||
What an incredible year! It can still hardly believe it’s been just six months since launching.
|
||||
|
||||
As we look to 2019, we plan to continue engaging with and growing our open source community, built on the same tenets of openness and collaboration -- the best part of
|
||||
my job. We have heard loud and clear that what customers need today are solutions, not just raw technologies, and we
|
||||
will continue to deliver commercial value in our Team and Enterprise Edition SaaS products that cloud engineering
|
||||
easier, more secure, and more collaborative.
|
||||
|
||||
We are just getting started and we can’t wait to continue on the journey of
|
||||
reimagining cloud engineering together. Thank you for your passionate support -- and here’s to a wonderful 2019!
|
||||
|
||||
— Joe
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
title: "2019 Year at a Glance"
|
||||
description: "As 2019 winds down, let's review Pulumi's most exciting recent milestones. This includes 1.0, our 2.0 roadmap, and dozens of other major features."
|
||||
date: 2019-12-31
|
||||
authors: ["joe-duffy"]
|
||||
tags: ["pulumi-news"]
|
||||
---
|
||||
# 2019 Year at a Glance
|
||||
|
||||
<p class="blog-meta">2019-12-31 · joe-duffy</p>
|
||||
|
||||
As we celebrate another incredible year in the books here at Pulumi, I wanted to share some reflections about our most exciting milestones over the past twelve months. The best part has been connecting with more customers worldwide, as we saw more than a 15x growth in our customer base, surely a sign of big things to come in 2020. We couldn't have done it without our amazing community; thank you deeply for your continued support and passion around Pulumi's bold mission to empower every engineer to program the cloud — you make it all worthwhile.
|
||||
|
||||
It's impossible to highlight everything, but here are some of our favorite milestones:
|
||||
|
||||
**[Pulumi 1.0](/blog/pulumi-1-0/).** After working with several major organizations to go to production with Pulumi, including multiple Fortune 500 and Global 2000 customers, we felt it was time to focus on a "1.0" release. To us, that meant significant improvements to quality, rounding out any open design issues, and sticking to compatibility. As such, we finished JavaScript, TypeScript, and Python support, made significant improvements to documentation and examples, and landed on a release we were proud to stand behind. Months later, we are up to version 1.8, and have stuck to our promise of "no breaking changes": we understand how fundamental an infrastructure as code tool is to your organization, and how frustrating breaking changes would be. A solid 1.0 serves as a critical foundation for us going forward.
|
||||
|
||||
**Global community.** Our community of end users grew significantly during 2019, with thousands of end users sharing best practices on [our Community Slack](https://slack.pulumi.com), and we expanded our physical presence globally. This included over two dozen events from big to small, including AWS re:Invent, Microsoft Build, Google Cloud Next, KubeCon EU and NA, and many Devopsdays, as well as several [community workshops](https://github.com/pulumi/infrastructure-as-code-workshop). We've also seen an uptick in community-led user groups and presentations, consulting and integration partnerships, and look forward to expanding our efforts here even more significantly next year. (If you ever need support/swag for your event, [please contact us](https://www.pulumi.com/contact/)!)
|
||||
|
||||
**[Pulumi 2.0 roadmap](/blog/pulumi-2-0-roadmap/).** After 1.0, we published a roadmap to our next major release, Pulumi 2.0. The two themes for this release are to continue [pushing the boundaries of productivity](/blog/pulumi-watch-mode-fast-inner-loop-development-for-cloud-infrastructure/), while also giving you "belts and suspenders" for teams and enterprises. We feel this is the magic of Pulumi: the ability to simultaneously run fast and build out infrastructure productively and using the latest and greatest features in AWS, Azure, GCP, and Kubernetes ... while still ensuring that security, compliance, and cost-related requirements and best practices are adhered to.
|
||||
|
||||
**[Simpler, per-user pricing](/blog/announcing-per-user-pricing-and-unlimited-stacks-for-teams/).** When we launched, our pricing was based on the number of stacks you have. Although our hearts were in the right place with this approach, we realized after working with customers that this could force architectural choices based on price, not what was in the best interest of teams and their projects. This didn't feel right — we don't want to penalize teams for doing the right thing! We rolled out per-user pricing in response and have had success with teams of all sizes — from teams of less than 5 engineers all the way up to teams of hundreds.
|
||||
|
||||
**Pulumi Crosswalk.** We introduced the Pulumi Crosswalk brand for our collection of cloud-specific higher level frameworks that simplify many common infrastructure patterns, while also including built-in best practices. Throughout the year, we've rounded out that support, starting with AWS, then Kubernetes, as well as some initial steps towards frameworks for Azure and GCP:
|
||||
|
||||
* **[Pulumi Crosswalk for AWS](/blog/introducing-pulumi-crosswalk-for-aws-the-easiest-way-to-aws/)** simplifies common AWS patterns, including [creating VPCs](/docs/guides/crosswalk/aws/vpc/), [ECS, EKS, and Fargate clusters](/blog/running-containers-in-aws-the-lowdown-ecs-fargate-and-eks/), [building and publishing Docker images to ECR registries](/blog/building-and-publishing-docker-images-to-a-private-amazon-ecr-repository/), and [more](/docs/guides/crosswalk/aws/).
|
||||
|
||||
* **[Pulumi Crosswalk for Kubernetes](/blog/crosswalk-kubernetes/)** encapsulates battle-tested approaches to running Kubernetes clusters and related infrastructure in production. This includes [playbooks for running Kubernetes in AWS, Azure, or GCP](/docs/guides/crosswalk/kubernetes/playbooks/), as well as [kx](/blog/introducing-kx/), a highly productive library that eliminates the "walls of YAML" boilerplate from your Kubernetes applications configurations.
|
||||
|
||||
* Although still works in progress, Pulumi Crosswalk for Azure will include [simple Azure Functions callbacks](/blog/serverless-as-simple-callbacks-with-pulumi-and-azure-functions/) and [globally distributed applications that auto-scale alongside Cosmos DB](/blog/how-to-build-globally-distributed-applications-with-azure-cosmos-db-and-pulumi/), and Pulumi Crosswalk for GCP will include [simplified Google Functions](/blog/simple-serverless-programming-with-google-cloud-functions-and-pulumi/).
|
||||
|
||||
**[Policy as Code ("CrossGuard")](/blog/announcing-crossguard-preview/).** We shipped a preview of our new policy as code support, code-named CrossGuard, which allows you to enforce policies at deployment time. CrossGuard brings the same "familiar language" approach we've used for infrastructure as code, and applies it to policy as code, enabling you to author your own rich rules to enforce security, compliance, cost, and team best practices. We open sourced previews of out-of-the-box rules by way of [AWSGuard](/docs/guides/crossguard/awsguard/) and [OPA integration](https://github.com/pulumi/pulumi-policy-opa). CrossGuard is [open source](https://github.com/pulumi/pulumi-policy) and Pulumi's [Team Pro and Enterprise tiers](https://www.pulumi.com/pricing/) support advanced organization-wide controls.
|
||||
|
||||
**[.NET](/blog/pulumi-dotnet-core/).** We have added initial preview support for writing your infrastructure as code in any .NET Core language, including C#, F#, and VB. This covers any existing Pulumi resource provider, including AWS, Azure, GCP, as well as [support for the entire Kubernetes object model](/blog/managing-kubernetes-infrastructure-with-dotnet-and-pulumi/). .NET, along with Go, will transition out of preview into being generally available as part of the 2.0 release.
|
||||
|
||||
**[More identity options](/docs/intro/console/accounts/).** Out of the gate, we supported GitHub as an identity provider when authenticating with the Pulumi service. Since then, we added [GitLab](/blog/welcoming-gitlab-users-to-pulumi/), [Atlassian](/blog/pulumi-now-supports-atlassian-identity/), [Email](/blog/announcing-support-for-email-based-identities/), and [SAML/SSO](/docs/guides/saml/), with user guides for [Azure ActiveDirectory](/docs/guides/saml/aad/), [Google GSuite](/docs/guides/saml/gsuite/), and [Okta](/docs/guides/saml/okta/). These all integrate with features like history/auditing, RBAC, and policy as code.
|
||||
|
||||
**[Enhanced, pluggable secrets](/blog/managing-secrets-with-pulumi/).** We heard that keeping secrets from leaking in plaintext to your start files is a challenge with current infrastructure as code tools. So, we deepend the way secrets integrate with Pulumi's engine, including transitive encryption so that, no matter where your secret goes in your program, it won't leak in plaintext. In addition, we added the ability to [use your own secrets provider for encryption](/docs/intro/concepts/config/#configuring-secrets-encryption), including AWS KMS, Azure KeyVault, Google Cloud KMS, and HashiCorp Vault. This ensures you get great ease-of-use — falling into the "pit of success" with secrets — while still leveraging your existing organization's approach.
|
||||
|
||||
**More state storage options.** Although the hosted Pulumi SaaS works great for most end users, offering the right mix of convenience and control, we understand it doesn't work for everyone. It is now possible to store state locally using the `pulumi login --local` command, or to [configure Pulumi to store state in AWS S3, Azure Blob Storage, or Google Cloud Storage](/docs/intro/concepts/state/#self-managed-backend). Additionally, [Pulumi Enterprise offers a self-hosted option](/docs/guides/self-hosted/), so that you can still benefit from the Pulumi SaaS's features around identity, policies, and controls, while hosting it in your own cloud account or behind your firewall.
|
||||
|
||||
**[More CI/CD integrations](/docs/guides/continuous-delivery/).** In partnership with customers, and in some cases the CI/CD vendors themselves, we have continued adding more CI/CD integrations, to enable automated delivery of your infrastructure. This includes [Jenkins](/docs/guides/continuous-delivery/jenkins/), [Azure DevOps Pipelines](/blog/cd-made-easy-with-pulumi-and-azure-pipelines/), [Octopus Deploy](/docs/guides/continuous-delivery/octopus-deploy/), [Codefresh](/docs/guides/continuous-delivery/codefresh/), and [revised support for GitHub Actions](/docs/guides/continuous-delivery/github-actions/).
|
||||
|
||||
**Coexistence and conversion tools.** We know that many teams have existing infrastructure in place. We want to make it a easy as possible to choose Pulumi and, as we've worked with major customers to transition away from existing infrastructure tools, we've built tools to help ease the adoption process. This includes the following approaches:
|
||||
|
||||
* **Coexist** with existing infrastructure, including [referencing existing Terraform remote state](/blog/using-terraform-remote-state-with-pulumi/), [deploying Kubernetes YAML as-is](https://github.com/pulumi/pulumi-kubernetes/blob/master/tests/sdk/nodejs/examples/yaml-guestbook/index.ts), [deploying Kubernetes Helm charts](/blog/using-helm-and-pulumi-to-define-cloud-native-infrastructure-as-code/), [deploying AWS CloudFormation stacks](https://www.pulumi.com/docs/reference/pkg/aws/cloudformation/stack/), or [deploying Azure Resource Manager (ARM) templates](https://github.com/pulumi/examples/tree/master/classic-azure-ts-arm-template) — in each case, enabling you to consume output properties from infrastructure deployed via other tools, for either temporary or permanent coexistence of Pulumi with these other tools.
|
||||
|
||||
* **Convert** your existing infrastructure so that it comes under the control of Pulumi. This includes [adopting existing cloud resources](/blog/adopting-existing-cloud-resources-into-pulumi/), no matter how they were provisioned (even if done manually by pointing and clicking in your cloud's UI), as well as the [tf2pulumi](/blog/from-terraform-to-infrastructure-as-software/) tool, which converts existing HCL programs to Pulumi, preserving your existing Terraform project and code structure.
|
||||
|
||||
**Support for large-scale projects.** As we've seen bigger and bigger Pulumi projects, we have put together [guidance](/blog/continuous-delivery-with-gitlab-and-pulumi-on-amazon-eks/) for multi-project approaches. This includes adding [the ability for stacks to reference one another](/blog/architect-aws-application-infra-with-pulumi-stack-references/), an essential building block when, for instance, one project depends on a piece of infrastructure provisioned by another project.
|
||||
|
||||
**Lots of providers!** We've added more than 20 new providers for managing resources across many cloud and service providers. This includes the existing core cloud providers for [AWS](/docs/intro/cloud-providers/aws/), [Azure](/docs/intro/cloud-providers/azure/), [GCP](/docs/intro/cloud-providers/gcp/), and [Kubernetes](/docs/intro/cloud-providers/kubernetes/), in addition to newly added providers [DigitalOcean](/docs/intro/cloud-providers/digitalocean/), [Linode](/docs/intro/cloud-providers/linode/), [OpenStack](/docs/intro/cloud-providers/openstack/), [Packet](/docs/intro/cloud-providers/equinix-metal/), and [vSphere](/docs/intro/cloud-providers/vsphere/). Modern cloud infrastructures include components managed by SaaS or other service providers alongside and connected to your core cloud infrastructure, and for those, we have added support for [Aiven](/docs/intro/cloud-providers/aiven/), [CloudAMQP](/docs/intro/cloud-providers/cloudamqp/), [Cloudflare](/docs/intro/cloud-providers/cloudflare/), [Consul](/docs/intro/cloud-providers/consul/), [Datadog](/docs/intro/cloud-providers/datadog/), [DNSimple](/docs/intro/cloud-providers/dnsimple/), [Docker](/docs/intro/cloud-providers/docker/), [Fastly](/docs/intro/cloud-providers/fastly/), [F5 BigIP](/docs/intro/cloud-providers/f5bigip/), [GitLab](/docs/intro/cloud-providers/gitlab/), [Kafka](/docs/intro/cloud-providers/kafka/), [MySQL](/docs/intro/cloud-providers/mysql/), [New Relic](/docs/intro/cloud-providers/newrelic/), [Okta](/docs/intro/cloud-providers/okta/), [PostgreSQL](/docs/intro/cloud-providers/postgresql/), [RabbitMQ](/docs/intro/cloud-providers/rabbitmq/), [SignalFX](/docs/intro/cloud-providers/signalfx/), [Spotinst](/docs/intro/cloud-providers/spotinst/), and [Vault](/docs/intro/cloud-providers/vault/).
|
||||
|
||||
It's impossible to overstate how big an impact you, the community, have had on Pulumi. In fact, every feature on this list was delivered in response to a real community, customer, or partner need.
|
||||
|
||||
2019 has been a major year for the Pulumi community by any measure. As we look forward, we anticipate even more accelerated growth and capabilities. We wish you all a wonderful New Year, and want to again thank you for the love and support — here's to an incredible 2020!
|
||||
|
||||
— Joe
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 264 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 106 KiB |
@@ -0,0 +1,290 @@
|
||||
---
|
||||
title: "7 Ways to Deal with Application Secrets in Azure"
|
||||
description: "In this post, we will look at 7 ways to deal with application secrects in Azure."
|
||||
date: 2019-07-26
|
||||
authors: ["mikhail-shilkov"]
|
||||
tags: ["Azure","Security"]
|
||||
---
|
||||
# 7 Ways to Deal with Application Secrets in Azure
|
||||
|
||||
<p class="blog-meta">2019-07-26 · mikhail-shilkov</p>
|
||||
|
||||
Every non-trivial application relies on configuration values that may depend on the current execution environment. Some of these values contain sensitive information that shouldn't be shared publicly. In general, the fewer parties that have access to those secret values, the safer the application will be—in fact, in an ideal world, no one would be granted direct access to those secrets.
|
||||
|
||||
Examples of secret configuration values include:
|
||||
|
||||
- A connection string to a message bus or a database
|
||||
- A SAS Token to an Azure Storage account
|
||||
- An access key for a third-party service
|
||||
|
||||
There's no one universal way to manage secrets, as a lot depends on the context in which they are used. In this article, I go through seven ways to use secret values in a .NET Core application running in Azure. I start with naively hard-coded strings and build up from there to more secure options.
|
||||
|
||||
While the concepts are universally applicable, my code samples focus on a .NET application running in **Azure App Service** and configured with Pulumi.
|
||||
|
||||
## 1. Hard-coded Secrets
|
||||
|
||||
Whenever you want to try a new API requiring a secret access token, it's natural to copy-paste that secret into your code and run it—simply to make sure that the setup works.
|
||||
|
||||
For example, you are testing integration with a payment service:
|
||||
|
||||
``` cs
|
||||
var apiKey = "payment-service-key";
|
||||
var paymentService = new PaymentService(apiKey);
|
||||
```
|
||||
|
||||
or you want to start sending messages to an **Azure Storage Queue**:
|
||||
|
||||
``` cs
|
||||
var connectionString = "DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key";
|
||||
var storageAccount = CloudStorageAccount.Parse(connectionString);
|
||||
var queueClient = storageAccount.CreateCloudQueueClient();
|
||||
```
|
||||
|
||||
Both snippets are fine for a Hello-World application with a lifespan of two hours. However, I would strongly discourage doing so in any code that can potentially be checked into a source control system, even for a 10-minute experiment. Don't copy-paste secrets into files which are part of a git repository. One accidental `git commit & git push`—and the secrets are compromised.
|
||||
|
||||
Avoid the "Secrets as Code" practice: there are bots scanning your GitHub repository for those.
|
||||
|
||||
## 2. Configuration Files
|
||||
|
||||
Traditionally, putting secrets in a configuration file is considered more secure. For classic .NET applications, this would be an `app.config` or a `web.config` file. The idea is that the values on a developer machine are different from the values in the production environment. Non-sensitive development settings are kept on disk and maybe in source control, while the real secrets are only injected by a deployment script or a CI/CD system, so they are not exposed publicly.
|
||||
|
||||
In the .NET Core world, a configuration is usually stored in an `appsettings.json` file:
|
||||
|
||||
``` json
|
||||
{
|
||||
"MyConfig": {
|
||||
"PaymentApiKey": "payment-service-key",
|
||||
"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
which is then mapped to a plain C# object in code:
|
||||
|
||||
``` cs
|
||||
public class MyConfig
|
||||
{
|
||||
public string PaymentApiKey { get; set; }
|
||||
public string StorageConnectionString { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
With some configuration not shown here, the properties are filled at startup time and can be used in the code as a plain object:
|
||||
|
||||
``` cs
|
||||
var apiKey = config.PaymentApiKey;
|
||||
var paymentService = new PaymentService(apiKey);
|
||||
// ...
|
||||
|
||||
var connectionString = config.StorageConnectionString;
|
||||
var storageAccount = CloudStorageAccount.Parse(connectionString);
|
||||
var queueClient = storageAccount.CreateCloudQueueClient();
|
||||
```
|
||||
|
||||
In my experience, such setup still poses substantial risks. `appsettings.production.json` may still be accidentally checked into the source control. Developers tend to use real cloud resources for their local and test environments, which do contain sensitive information that can be exploited when leaked.
|
||||
|
||||
On top of that, it doesn't feel right to mix configuration—how many threads to run, or how big the message batches should be—with secret connection strings and API keys in the same file. These are separate kinds of configuration, and they warrant different workflows.
|
||||
|
||||
## 3. Environment Variables and Application Settings
|
||||
|
||||
One alternative approach is to read the secret values from environment variables. .NET Core configuration system can parse environment variables instead of, or in addition to the settings files. Likewise, one could read such values with a one-liner in C#:
|
||||
|
||||
``` cs
|
||||
var apiKey = Environment.GetEnvironmentVariable("PAYMENT_API_KEY");
|
||||
// ...
|
||||
|
||||
var connectionString = Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING");
|
||||
// ...
|
||||
```
|
||||
|
||||
Your CI/CD system should inject those values as part of the deployment pipeline.
|
||||
|
||||
The App Service gives you the ability to set environment variables via **Application Settings**. Here is a snippet of a Pulumi program that passes both secret values to `appSettings`:
|
||||
|
||||
``` ts
|
||||
const cfg = new pulumi.Config();
|
||||
const paymentApiKey = cfg.requireSecret("paymentApiKey");
|
||||
|
||||
const storageAccount = new azure.storage.Account("storage", {
|
||||
resourceGroupName: resourceGroup.name,
|
||||
accountReplicationType: "LRS",
|
||||
accountTier: "Standard",
|
||||
});
|
||||
|
||||
const app = new azure.appservice.AppService("app", {
|
||||
resourceGroupName: resourceGroup.name,
|
||||
appServicePlanId: appServicePlan.id,
|
||||
appSettings: {
|
||||
"PAYMENT_API_KEY": paymentApiKey,
|
||||
"STORAGE_CONNECTION_STRING": storageAccount.primaryConnectionString,
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
The Storage connection string is produced by the Pulumi program directly, so it doesn't have to be placed anywhere outside the program itself.
|
||||
|
||||
The payment service key is provided by a third party, so its encrypted value is stored in Pulumi configuration. Read [Managing Secrets with Pulumi](/blog/managing-secrets-with-pulumi/) to learn about security options available for secrets in Pulumi config.
|
||||
|
||||
## 4. Azure Key Vault
|
||||
|
||||
In the previous example, both secrets end up in Application Settings. Every person with sufficient permissions may go to the App Service and see them in clear text. While this can be restricted, it's a good idea to grant full read access to the application developers and operators of the App Service to give them the full picture when troubleshooting issues.
|
||||
|
||||
In some cases, compliance to a certain standard may *require* the use of a certified key management service offering enhanced security for sensitive secrets.
|
||||
|
||||
Azure has a dedicated service for storing secrets, **Azure Key Vault**. You can create and populate a Key Vault with all the secrets from the same Pulumi program:
|
||||
|
||||
``` ts
|
||||
const vault = new azure.keyvault.KeyVault("vault", {
|
||||
resourceGroupName: resourceGroup.name,
|
||||
sku: {
|
||||
name: "standard",
|
||||
},
|
||||
tenantId: tenantId,
|
||||
accessPolicies: [{
|
||||
tenantId,
|
||||
// The current principal has to be granted permissions to Key Vault so that it can actually add and then remove
|
||||
// secrets to/from the Key Vault. Otherwise, 'pulumi up' and 'pulumi destroy' operations will fail.
|
||||
objectId: currentPrincipal,
|
||||
secretPermissions: ["delete", "get", "list", "set"],
|
||||
}],
|
||||
});
|
||||
|
||||
const secret = new azure.keyvault.Secret("paymentApiKey", {
|
||||
keyVaultId: vault.id,
|
||||
value: paymentApiKey,
|
||||
});
|
||||
```
|
||||
|
||||
Additionally, one or many **Service Principals** (SP) should be configured to access the Key Vault. One SP which has been granted secret management access deploys the infrastructure by running the Pulumi program. That's why the snippet above assigns an access policy to `currentPrincipal`.
|
||||
|
||||
Another SP is used by the application itself to read the secret values. The Client ID and Client Secret parameters are placed in the application configuration. Finally, .NET Core configuration gets hooked to the Key Vault at startup:
|
||||
|
||||
``` cs
|
||||
builder.AddAzureKeyVault(
|
||||
$"https://{config["azureKeyVault:vault"]}.vault.azure.net/",
|
||||
config["azureKeyVault:clientId"],
|
||||
config["azureKeyVault:clientSecret"]
|
||||
);
|
||||
```
|
||||
|
||||
This solution is not entirely satisfying though, since we've traded storing the secrets for storing SP credentials. Is that a big enough win? Luckily, it's easy to get rid of those credentials with Managed identities.
|
||||
|
||||
## 5. Accessing Key Vault with Managed Identities
|
||||
|
||||
With **Managed identities**, Azure takes care of creating a Service Principal, passing the credentials, rotating secrets, and so on. Enabling a managed identity on App Service is just an extra option:
|
||||
|
||||
``` ts
|
||||
const app = new azure.appservice.AppService("app", {
|
||||
resourceGroupName: resourceGroup.name,
|
||||
appServicePlanId: appServicePlan.id,
|
||||
// A system-assigned managed identity
|
||||
identity: {
|
||||
type: "SystemAssigned",
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
On top of that, the managed principal must be granted access to the Key Vault:
|
||||
|
||||
``` ts
|
||||
const principalId = app.identity.apply(id => id.principalId);
|
||||
|
||||
// Grant App Service access to KV secrets
|
||||
new azure.keyvault.AccessPolicy("app-policy", {
|
||||
keyVaultId: vault.id,
|
||||
tenantId: tenantId,
|
||||
objectId: principalId,
|
||||
secretPermissions: ["get"],
|
||||
});
|
||||
```
|
||||
|
||||
Now, the configuration block in the .NET Core app doesn't need to retrieve any secrets. `AzureServiceTokenProvider` helps with the authentication process:
|
||||
|
||||
``` cs
|
||||
var azureServiceTokenProvider = new AzureServiceTokenProvider();
|
||||
var keyVaultClient = new KeyVaultClient(
|
||||
new KeyVaultClient.AuthenticationCallback(
|
||||
azureServiceTokenProvider.KeyVaultTokenCallback));
|
||||
builder.AddAzureKeyVault(
|
||||
keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
|
||||
```
|
||||
|
||||
That's quite a bit of a boilerplate, but there is a way to get rid of it.
|
||||
|
||||
## 6. Accessing Key Vault from Application Settings
|
||||
|
||||
App Service has a neat feature of integrating its Application Settings with Key Vault. It allows us to combine #3 and #5's approaches and get the best of both:
|
||||
|
||||
``` ts
|
||||
// Produce a URI of the KV secret defined above
|
||||
const secretUri = pulumi.interpolate`${secret.vaultUri}secrets/${secret.name}/${secret.version}`;
|
||||
|
||||
const app = new azure.appservice.AppService("app", {
|
||||
resourceGroupName: resourceGroup.name,
|
||||
appServicePlanId: appServicePlan.id,
|
||||
// A system-assigned managed identity
|
||||
identity: {
|
||||
type: "SystemAssigned",
|
||||
},
|
||||
appSettings: {
|
||||
// The setting points directly to the KV setting
|
||||
"PAYMENT_API_KEY": pulumi.interpolate`@Microsoft.KeyVault(SecretUri=${secretUri})`,
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
With that, the API key is loaded into the App Service environment variable without its value being publicly exposed anywhere!
|
||||
|
||||
## 7. Role-based Access Control
|
||||
|
||||
What is the most secure way to deal with secrets? *Have no secrets*. The Storage Account connection string is a great example when it's possible to avoid storing and reading the sensitive value altogether.
|
||||
|
||||
**Role-based access control** (RBAC) of **Azure Active Directory** (AAD) is a great tool to manage permissions in a declarative way. Let's assume our application only needs to send messages to one Storage Queue. Instead of storing a full connection string with an access token, the connection string should point to the account, and the identity behind the App Service should be granted write permissions to the required Storage Queue:
|
||||
|
||||
``` ts
|
||||
const permission = new azure.role.Assignment("send", {
|
||||
principalId,
|
||||
scope: pulumi.interpolate`${storageAccount.id}/queueServices/default/queues/${queue.name}`,
|
||||
roleDefinitionName: "Storage Queue Data Message Sender",
|
||||
});
|
||||
```
|
||||
|
||||
We can put the queue URL into Application Settings because there's nothing secret in it:
|
||||
|
||||
``` ts
|
||||
const queueUri = pulumi.interpolate`${storageAccount.primaryQueueEndpoint}${queue.name}`;
|
||||
|
||||
const app = new azure.appservice.AppService("app", {
|
||||
resourceGroupName: resourceGroup.name,
|
||||
appServicePlanId: appServicePlan.id,
|
||||
identity: {
|
||||
type: "SystemAssigned"
|
||||
},
|
||||
appSettings: {
|
||||
"STORAGE_QUEUE_URL": queueUri,
|
||||
},
|
||||
```
|
||||
|
||||
It takes a bit of C# boilerplate to send a message with role-based authorization:
|
||||
|
||||
``` cs
|
||||
var provider = new AzureServiceTokenProvider();
|
||||
string accessToken = await provider.GetAccessTokenAsync("https://storage.azure.com/");
|
||||
var tokenCredential = new TokenCredential(accessToken);
|
||||
var storageCredentials = new StorageCredentials(tokenCredential);
|
||||
var url = Environment.GetEnvironmentVariable("StorageBlobUrl");
|
||||
var queue = new CloudQueue(new Uri(url), storageCredentials);
|
||||
queue.AddMessage(new CloudQueueMessage("Hello"));
|
||||
```
|
||||
|
||||
Let's hope another quality-of-life improvement is on the way.
|
||||
|
||||
## Role of Infrastructure as Code
|
||||
|
||||
While security practices may vary depending on application requirements, Pulumi plays an essential role in the appropriate setup of service configuration and environment:
|
||||
|
||||
- It links an output of one resource to another one's input, avoiding the need to store the values.
|
||||
- It provides a built-in mechanism to manage external secrets.
|
||||
- It is a great way to take advantage of Azure features like Managed identities and RBAC in a cohesive way.
|
||||
|
||||
Infrastructure as Code helps make your applications secure and reliable. Refer to [this full example](https://github.com/pulumi/examples/tree/master/classic-azure-ts-msi-keyvault-rbac) of using Key Vault, Managed identities, RBAC with App Service and Pulumi.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 164 KiB |
@@ -0,0 +1,260 @@
|
||||
---
|
||||
title: "Adopting Existing Cloud Resources into Pulumi"
|
||||
description: "Migrating from Terraform or another IaC tool? Learn how to adopt existing cloud infrastructure from Terraform, CloudFormation, ARM, YAML, and more into Pulumi."
|
||||
date: 2019-08-15
|
||||
authors: ["luke-hoban"]
|
||||
tags: ["migration"]
|
||||
---
|
||||
# Adopting Existing Cloud Resources into Pulumi
|
||||
|
||||
<p class="blog-meta">2019-08-15 · luke-hoban</p>
|
||||
|
||||
::: info 注意
|
||||
Migrate from Terraform to modern languages with tf2pulumi. Supports Terraform 0.12 and generates TypeScript and Python.
|
||||
|
||||
:::
|
||||
|
||||
<div class="header-hero-actions mt-8 mb-4 text-center">
|
||||
<a class="btn btn-lg mr-2" href="/docs/guides/adopting/from_terraform/">
|
||||
Learn More
|
||||
</a>
|
||||
</div>
|
||||
<br>
|
||||
|
||||
Most cloud infrastructure projects involve working with existing cloud resources — either building on top of existing resources or adopting existing resources under management with a new and more robust infrastructure provisioning solution.
|
||||
|
||||
Whether you are adopting resources that were deployed manually using your cloud provider's console or CLI — or migrating existing infrastructure from tools like Terraform or CloudFormation — Pulumi makes it easy to adopt and manage your existing resources.
|
||||
|
||||
When working with existing resources, there are typically two scenarios:
|
||||
|
||||
* You need to reference existing resources to use as inputs to new resources in Pulumi
|
||||
* You need to adopt existing resources under management so they can be updated/managed in Pulumi
|
||||
|
||||
We'll review referencing existing resources, and then dive deeper into how you can adopt existing resources with Pulumi.
|
||||
|
||||
## Referencing Existing Resources
|
||||
|
||||
For referencing existing resources, Pulumi offers several tools.
|
||||
|
||||
* The `.get` methods available on every resource let you [get all the details for a resource](https://www.pulumi.com/docs/reference/pkg/aws/ec2/vpc/#look-up) from the cloud provider based just on its `id`.
|
||||
* The `StackReference` resource lets you reference outputs of another stack for use as inputs to a stack, which is very useful for [organizing projects and stacks](/docs/guides/organizing-projects-stacks/).
|
||||
* [`terraform.state.RemoteStateReference()`](/blog/using-terraform-remote-state-with-pulumi/), [`aws.cloudformation.getStack()`](https://www.pulumi.com/docs/reference/pkg/aws/cloudformation/getstack/) and [`azure.core.TemplateDeployment.get()`](https://www.pulumi.com/docs/reference/pkg/azure/core/templatedeployment/#look-up) let you reference outputs from existing Terraform, CloudFormation and ARM deployments respectively.
|
||||
|
||||
Together, these make it easy to reference existing infrastructure regardless of how it was provisioned.
|
||||
|
||||
## Adopting Existing Resources
|
||||
|
||||
For adopting existing resources, Pulumi offers the [`import`](https://www.pulumi.com/docs/reference/pkg/azure/core/templatedeployment/#look-up) resource option to request that a resource defined in your Pulumi program adopt an existing resource in the cloud provider instead of creating a new one. In keeping with its focus on infrastructure as *code*, Pulumi lets you specify this `import` behavior inside the Pulumi code for your infrastructure deployment, instead of outside of it in some manual workflow. In its simplest form, it looks like this:
|
||||
|
||||
```ts
|
||||
const myVpc = new aws.ec2.Vpc("my-vpc", {
|
||||
cidrBlock: "10.11.0.0/16",
|
||||
}, { import: "vpc-02cd0cd2d807f340c"});
|
||||
```
|
||||
|
||||
When Pulumi first sees a resource (in this case `my-vpc`), if it has an `import` option set, it will adopt the existing resource specified by that `import` ID from the cloud provider under management instead of creating a new resource.
|
||||
|
||||
We can see this when we deploy our Pulumi program with `pulumi up`:
|
||||
|
||||
```
|
||||
$ pulumi up
|
||||
Previewing update (dev):
|
||||
|
||||
Type Name Plan
|
||||
pulumi:pulumi:Stack importtestaws-dev
|
||||
= └─ aws:ec2:Vpc my-vpc import
|
||||
|
||||
Resources:
|
||||
= 1 to import
|
||||
1 unchanged
|
||||
```
|
||||
|
||||
Because the `import` is provided in code, it can be configured in several different ways. You can look up import ids from Pulumi config instead of hard-coding them into programs, construct ids from predictable names based on program parameters, or even conditionally add the `import: <id>` property depending on whether one wants to deploy a stack in "adoption" or "creation" mode.
|
||||
|
||||
Import can be used for a wide variety of adoption scenarios, from importing a single resource to migrating an entire stack from an existing tool like Terraform. You can even automate an entire migration process across dozens of instances of infrastructure deployment. For small numbers of resources, you can just paste in individual resource IDs. For larger conversions, you can create a mapping of cloud resource ids (in JSON, CSV, or any other format) and load that into your Pulumi program with something like `import: idMapping[name]`. If you are importing or migrating dozens of stacks, you can even select between which of these mappings to use via a Pulumi config setting.
|
||||
|
||||
### Walkthrough of Adopting Existing Infrastructure to Pulumi
|
||||
|
||||
To see one of these scenarios in action end-to-end, let's walk through the process of deploying some "existing" infrastructure outside of Pulumi, and then adopting it under management of a Pulumi program. You can also check out the video below which walks through the same scenario.
|
||||
|
||||
<iframe width="560" height="315" src="https://www.youtube.com/embed/kX_3Wdft0Ms?rel=0" frameborder="0" allowfullscreen></iframe>
|
||||
|
||||
We'll use Terraform to provision our "existing" infrastructure. These resources could have been provisioned manually in the console, or using platform-native infrastructure-as-code solutions like CloudFormation, ARM or Kubernetes YAML.
|
||||
|
||||
We'll also use TypeScript, though of course, the process is similar regardless of the language you choose.
|
||||
|
||||
#### 1. Deploy "existing" infrastructure
|
||||
|
||||
For our "existing" infrastructure, we'll use a small Azure deployment of a Virtual Machine and corresponding Resource Group and Networking resources. We'll deploy [this example](https://www.terraform.io/docs/providers/azurerm/r/virtual_machine.html#example-usage-from-an-azure-platform-image-) using `terraform`. Save the code in that example to `main.tf` and run `terraform init` and then `terraform apply` to deploy it.
|
||||
|
||||
#### 2. Create a Pulumi program
|
||||
|
||||
Next, we'll create a Pulumi program to describe the same infrastructure that exists in Azure. We could write this by hand, but since we used Terraform to define the original infrastructure, we also have the option to use [`tf2pulumi`](https://github.com/pulumi/tf2pulumi) to automatically convert our `.tf` files to Pulumi.
|
||||
|
||||
```bash
|
||||
$ pulumi new azure-typescript --force
|
||||
$ tf2pulumi
|
||||
```
|
||||
|
||||
We now have a Pulumi program in `index.ts` that describes the same infrastructure:
|
||||
|
||||
```ts
|
||||
import * as pulumi from "@pulumi/pulumi";
|
||||
import * as azure from "@pulumi/azure";
|
||||
|
||||
const config = new pulumi.Config();
|
||||
const prefix = config.get("prefix") || "tfvmex";
|
||||
|
||||
const mainResourceGroup = new azure.core.ResourceGroup("main", {
|
||||
location: "West US 2",
|
||||
name: `${prefix}-resources`,
|
||||
});
|
||||
const mainVirtualNetwork = new azure.network.VirtualNetwork("main", {
|
||||
addressSpaces: ["10.0.0.0/16"],
|
||||
location: mainResourceGroup.location,
|
||||
name: `${prefix}-network`,
|
||||
resourceGroupName: mainResourceGroup.name,
|
||||
});
|
||||
|
||||
...
|
||||
|
||||
```
|
||||
|
||||
If we try to run a `pulumi up` now to deploy this though, we see that as we expect, we will try to deploy a new copy of the infrastructure:
|
||||
|
||||
```
|
||||
$ pulumi up
|
||||
Previewing update (dev2):
|
||||
|
||||
Type Name Plan
|
||||
+ pulumi:pulumi:Stack importazure-dev2 create
|
||||
+ ├─ azure:core:ResourceGroup main create
|
||||
+ ├─ azure:network:VirtualNetwork main create
|
||||
+ ├─ azure:network:Subnet internal create
|
||||
+ ├─ azure:network:NetworkInterface main create
|
||||
+ └─ azure:compute:VirtualMachine main create
|
||||
|
||||
Resources:
|
||||
+ 6 to create
|
||||
```
|
||||
|
||||
Instead of creating new resources though, we want to adopt the existing ones.
|
||||
|
||||
#### 3.Add `import` IDs
|
||||
|
||||
As we saw earlier, to import existing resources, we simply add `import: <id>` to the resource options of a resource defined in Pulumi. That resource will then be imported instead of created.
|
||||
|
||||
We can try this for one resource first. We can look in our `terraform.tfstate` file or in the Azure Portal and see that the id of the Resource Group is `/subscriptions/0282681f-7a9e-424b-80b2-96babd57a8a1/resourceGroups/tfvmex-resources`. So let's use that:
|
||||
|
||||
```ts
|
||||
const mainResourceGroup = new azure.core.ResourceGroup("main", {
|
||||
location: "West US 2",
|
||||
name: `${prefix}-resources`,
|
||||
}, { import: "/subscriptions/0282681f-7a9e-424b-80b2-96babd57a8a1/resourceGroups/tfvmex-resources" });
|
||||
```
|
||||
|
||||
#### 4. Adopt resources
|
||||
|
||||
Now our preview shows that it will import the `ResourceGroup` instead:
|
||||
|
||||
```
|
||||
$ pulumi up
|
||||
Previewing update (dev2):
|
||||
|
||||
Type Name Plan
|
||||
+ pulumi:pulumi:Stack importazure-dev2 create
|
||||
= └─ azure:core:ResourceGroup main import
|
||||
|
||||
Resources:
|
||||
+ 1 to create
|
||||
= 1 to import
|
||||
2 changes
|
||||
```
|
||||
|
||||
We can complete this process, adding `import: <id>` to all resources, and then import them all to Pulumi.
|
||||
|
||||
```
|
||||
Updating (dev2):
|
||||
|
||||
Type Name Status
|
||||
+ pulumi:pulumi:Stack importazure-dev2 created
|
||||
= ├─ azure:core:ResourceGroup main imported
|
||||
= ├─ azure:network:VirtualNetwork main imported
|
||||
= ├─ azure:network:Subnet internal imported
|
||||
= ├─ azure:network:NetworkInterface main imported
|
||||
= └─ azure:compute:VirtualMachine main imported
|
||||
|
||||
Resources:
|
||||
+ 1 created
|
||||
= 5 imported
|
||||
6 changes
|
||||
|
||||
Duration: 8s
|
||||
```
|
||||
|
||||
As noted earlier, if we were doing this at larger scale, instead of putting resource IDs inline in the code, we could load the IDs from a file or from Pulumi config. These IDs could be automatically extracted from our `.tfstate` file or from queries against our cloud provider.
|
||||
|
||||
#### 5. Managing the resources with Pulumi
|
||||
|
||||
Once all of the resources are adopted into Pulumi, we can manage them by making incremental changes in Pulumi, and can discontinue using the existing `.tf` files to manage this set of infrastructure. For example, if we want to add a new tag to our Virtual Machine, we can use the code below. We can also now remove the `import` property if we want, or else leave it intact so long as the `id` of the resource remains the same. (If in the future we need to make a change that replaces one of these imported resources, Pulumi will require that the `id` property is removed, as it will no longer be correct.)
|
||||
|
||||
```diff
|
||||
const mainVirtualMachine = new azure.compute.VirtualMachine("main", {
|
||||
location: mainResourceGroup.location,
|
||||
name: `${prefix}-vm`,
|
||||
networkInterfaceIds: [mainNetworkInterface.id],
|
||||
osProfile: {
|
||||
// Note: This comes directly from the original Terraform example, but
|
||||
// you would typically replace this with secret config in Pulumi, which
|
||||
// you can do after importing these resources into Pulumi.
|
||||
adminPassword: "Password1234!",
|
||||
adminUsername: "testadmin",
|
||||
computerName: "hostname",
|
||||
},
|
||||
osProfileLinuxConfig: {
|
||||
disablePasswordAuthentication: false,
|
||||
},
|
||||
resourceGroupName: mainResourceGroup.name,
|
||||
storageImageReference: {
|
||||
offer: "UbuntuServer",
|
||||
publisher: "Canonical",
|
||||
sku: "16.04-LTS",
|
||||
version: "latest",
|
||||
},
|
||||
storageOsDisk: {
|
||||
caching: "ReadWrite",
|
||||
createOption: "FromImage",
|
||||
managedDiskType: "Standard_LRS",
|
||||
name: "myosdisk1",
|
||||
},
|
||||
tags: {
|
||||
environment: "staging",
|
||||
+ managedBy: "Pulumi",
|
||||
},
|
||||
vmSize: "Standard_DS1_v2",
|
||||
});
|
||||
```
|
||||
|
||||
Deploying this, Pulumi shows we will update the existing resource to add the new tag:
|
||||
|
||||
```
|
||||
~ tags: {
|
||||
+ managedBy: "Pulumi"
|
||||
}
|
||||
```
|
||||
|
||||
Since the resources are now being managed by Pulumi, we can use the Pulumi Console to see them:
|
||||
|
||||

|
||||
|
||||
And then navigate to the Virtual Machine in the Azure Portal and see the newly added `managedBy: Pulumi` tag.
|
||||
|
||||

|
||||
|
||||
The result is that we have migrated our existing infrastructure into Pulumi and can now use all the rich features of Pulumi to manage it going forward!
|
||||
|
||||
## Conclusion
|
||||
|
||||
With Pulumi, you can easily work with existing cloud infrastructure, either referencing the existing infrastructure as inputs to new cloud infrastructure defined in Pulumi, or adopting existing infrastructure under management with Pulumi.
|
||||
|
||||
[Get started](/docs/get-started/) with Pulumi today!
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 85 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 85 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 31 KiB |
@@ -0,0 +1,132 @@
|
||||
---
|
||||
title: "Advanced TypeScript type FTW!"
|
||||
description: "TypeScript is great for cloud apps and infrastructure because of its rich type system. In this blog, learn how the type system works for infrastructure as code."
|
||||
date: 2018-09-19
|
||||
authors: ["cyrus-najmabadi"]
|
||||
tags: ["TypeScript"]
|
||||
---
|
||||
# Advanced TypeScript type FTW!
|
||||
|
||||
<p class="blog-meta">2018-09-19 · cyrus-najmabadi</p>
|
||||
|
||||
We at Pulumi love TypeScript for cloud apps and infrastructure, because of its rich type system and great ahead-of-time
|
||||
typechecking – making for a more productive inner loop and helping to find errors sooner. The typesystem magic behind
|
||||
how this works for infrastructure as code can be fascinating!
|
||||
|
||||
A core part of the Pulumi [programming model](/docs/reference/) is that we allow people to express complex
|
||||
[dependency data](/docs/intro/concepts/inputs-outputs/) that may _eventually_ be available.
|
||||
Traditional JavaScript programming might expose that as a Promise<T>, but we’ve taken that one step further by introducing
|
||||
a type we call:
|
||||
|
||||
type Input<T> = T | Promise<T> | Output<T>;
|
||||
|
||||
// Like a Promise<T>, but also keeps track of dependency information so we can figure
|
||||
// out what the upstream/downstream impact is whenever any values change in the system
|
||||
interface Output<T> { /* ... */ }
|
||||
|
||||
This complex type can often show up as inputs to all Pulumi objects like so:
|
||||
|
||||
interface VpcInput {
|
||||
ipAddresses: Input<Input<string>[]>;
|
||||
}
|
||||
|
||||
Breaking that down, it’s basically saying “I’ll take an array of strings. But those actual string values can individually be
|
||||
strings, promises-of-strings, or strings-carrying-dependency-information.” It even goes one step beyond that, because the
|
||||
entire array itself could be just an array-of-those-things, or a promise-of-array-of-those-things, or an
|
||||
array-of-those-things-with-dependency-information. Whew…!
|
||||
|
||||
This approach is great for people producing the data. As a producer I can do:
|
||||
|
||||
new Vpc({ ipAddresses: ["an-address"] }); // or even
|
||||
new Vpc({ ipAddresses: ["an-address", computeAddressAsynchronously() ]}); // or even
|
||||
new Vpc({ ipAddresses: ["an-address", computeAddressAsynchronously(), someDependency.address ]}); // or even
|
||||
new Vpc({ ipAddresses: computeAnArrayAnyOfTheAboveAsynchrousnously() }); // etc. etc.
|
||||
|
||||
It’s super flexible, and let’s people naturally produce the values in whatever way they want without having to work too hard to
|
||||
make it conform to some very narrow type.
|
||||
|
||||
However, while easy to produce, this can sometimes be difficult to consume. For example, if you wanted to take in that
|
||||
`Input<Input<string>[]>` and then check if there was a very specific value in it, you might have to go through and do a bunch of
|
||||
work. You’d have to first deal with potentially getting a `Input<string>[]` or a `Promise<Input<string>[]>` or even an `Output<Input<string>[]>`.
|
||||
Then, once you even got to the underlying array, you’d have to deal with each potential element in it being a `string`… or a `Promise<string>`… or a… well… you get the idea. It’s not fun 😃.
|
||||
|
||||
Up until now, we’d supplied some simple helpers to make this more managable. Our helpers would effectively ‘unwrap’ one
|
||||
layer of this sort of structure allowing you take the external value and deal with an internal value of a known shape.
|
||||
So it effectively worked like this:
|
||||
|
||||
function unwrap<T>(input: Input<T>): T { /* ... */ }
|
||||
|
||||
// so, you could then write:
|
||||
const ipAddresses: Input<string>[] = unwrap(vpc.ipAddresses);
|
||||
|
||||
This helped things somewhat. But it still meant that as you processed that array you had to then unwrap each and every
|
||||
element. As our data model has grown, and we’ve tackled more and more complex domains, we started seeing code start to
|
||||
form the programming [Pyramid of Doom](https://en.wikipedia.org/wiki/Pyramid_of_doom_(programming)), where you just kept
|
||||
on going deeper and deeper, unwrapping all the way. We started seeing this happen so often that we wanted to see if we
|
||||
there was anything we could do to make life much nicer for people using our APIs and using these helpers.
|
||||
|
||||
Our core goal was to change our ‘unwrap’ function from just peeling away one layer of this onion, to peeling away _all_
|
||||
layers. So, for example, if you started with an `Input<Input<string>[]>` you would just get back a plain old `string[]`
|
||||
that you could use completely naturally in all the ways you’d expect. We were initially uncertain if we could make
|
||||
this work, but thanks to the power of JavaScript and the expressivity of TypeScript, we think we found a great solution
|
||||
here.
|
||||
|
||||
We knew that providing the implementation such a function itself was not going to the true hard part. After all, we
|
||||
already had the code to peel back one layer. So peeling back all the layers was more a matter of just having the function
|
||||
call itself recursively when encountering things like arrays (or other objects that themselves contained `Input`s).
|
||||
|
||||
The real hard part came in when were trying figure out how would we even express this in a type-safe manner TypeScript.
|
||||
After all, what’s the type signature when you effectively want to say:
|
||||
|
||||
function unwrap(input: Input<...MaybeHasInputsOrPromisesOrOutputsArbitrarilyDeep...>): ThatThingWithAllTheDeepInputsPromisesAndOutputsErased;
|
||||
|
||||
This was a big head scratcher for a while. But after exploring some of the powerful new features that TypeScript has
|
||||
been bringing about in recent releases, we finally found a great way to manage it. In the end, it ends up looking
|
||||
something like this:
|
||||
|
||||
type primitive = string | number | boolean | undefined | null;
|
||||
|
||||
type Unwrap<T> =
|
||||
T extends Promise<infer U> ? UnwrapSimple<U> :
|
||||
T extends Output<infer U> ? UnwrapSimple<U> :
|
||||
UnwrapSimple<T>;
|
||||
|
||||
type UnwrapSimple<T> =
|
||||
T extends primitive ? T :
|
||||
T extends Array<infer U> ? UnwrappedArray<U> :
|
||||
T extends object ? UnwrappedObject<T> :
|
||||
never;
|
||||
|
||||
interface UnwrappedArray<T> extends Array<Unwrap<T>> {}
|
||||
|
||||
type UnwrappedObject<T> = {
|
||||
[P in keyof T]: Unwrap<T[P]>;
|
||||
};
|
||||
|
||||
function unwrap<T>(val: T): Unwrap<T>;
|
||||
|
||||
It’s a bit of a doozy containing a bunch of type definitions and the final function declaration that uses them. It
|
||||
makes use of many advanced TypeScript typing features. Including ‘Union Types’ (the ‘primitive’ type), ‘Mapped Types’
|
||||
(which ‘UnwrappedObject’ is an example of), ‘Conditional Types’ (the types with `?` and `:` in them) and ‘Inferred Types’
|
||||
(the use of `infer U` in several places). You can read more about these in the
|
||||
[Advanced Types](https://www.typescriptlang.org/docs/handbook/advanced-types.html) documentation.
|
||||
|
||||
Put together, the `Unwrap<T>` itself is effectively a recursively defined structural pattern matching type. You can see
|
||||
it reference itself once you walk into `UnwrappedArray<T>` and `UnwrappedObject<T>` types. As it recurses, it matches
|
||||
the type it has and then ‘peels away’ the wrappings that have been caused by `Promise<T>` and `Output<T>`. As it hits
|
||||
Arrays and Objects, it dives deeper, unwrapping along the way. This is all manageable in TypeScript because it does this
|
||||
sort of matching and unwrapping in a lazy fashion, allowing us to express what is effectively an infinitely large
|
||||
pattern-matching type, without it having any trouble understanding it or applying it!
|
||||
|
||||
It amazes us how well this works and how expressive TypeScript is here. As you can see here, TypeScript completely
|
||||
understands what’s going on and will give you all the great type-checking support and tooling that we know and love:
|
||||
|
||||

|
||||
|
||||
Since adding support for this, we’ve been able to start using this new function across our own codebase and we’ve seen
|
||||
things get dramatically simpler. The pyramid-of-doom goes away and code becomes much cleaner and easier to read and
|
||||
maintain. JavaScript helped us write this system easily, but thanks to TypeScript we can express these complex intents
|
||||
and have the safety and understanding to do this sort of thing with confidence.
|
||||
|
||||
A special thanks to [@DanielRosenwasser](https://github.com/danielrosenwasser) over from the TypeScript team for
|
||||
putting up with my constant pestering on how to work through this and deal with some especially thorny areas!
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
title: "Pulumi container images now available on Amazon ECR Public"
|
||||
description: "Pulumi container images now available on Amazon ECR Public"
|
||||
date: 2020-12-01
|
||||
authors: ["paul-stack"]
|
||||
tags: ["aws","containers"]
|
||||
---
|
||||
# Pulumi container images now available on Amazon ECR Public
|
||||
|
||||
<p class="blog-meta">2020-12-01 · paul-stack</p>
|
||||
|
||||
At re:Invent, the AWS team unveiled the new Amazon Elastic Container Registry Public (Amazon ECR Public), creating a new
|
||||
option for users in publishing and pulling public container images. Pulumi fully supports Amazon ECR Public in two ways:
|
||||
|
||||
1. Official Pulumi container images are available today on Amazon ECR Public.
|
||||
2. Pulumi is the easiest way to package and publish your container images, and we’ll support publishing your container
|
||||
images to Amazon ECR Public very soon.
|
||||
|
||||
If you want to learn more about Pulumi and building resources in AWS, join one of our [upcoming workshops](https://www.pulumi.com/resources/#upcoming).
|
||||
|
||||
Pulumi publishes official container images for running Pulumi along with the desired Pulumi programming language runtimes.
|
||||
These containers are used directly by developers as the foundation for process automation, such as GitHub Actions; in custom
|
||||
container environments with Pulumi’s Automation API; and in Kubernetes-based solutions, like the Pulumi Kubernetes Operator.
|
||||
These images are publicly available via [Docker Hub](https://hub.docker.com/r/pulumi) and will continue to be available there.
|
||||
|
||||
With the unveiling of Amazon ECR Public, we want to make sure Pulumi’s official container images are always available to
|
||||
ensure that our users can ultimately choose the right container image that suits their needs. Going forward, Pulumi’s
|
||||
official container images will be available on Amazon ECR Public.
|
||||
|
||||
We've published our Pulumi container images in this new repository, and we plan to publish to both the Docker Hub and Amazon
|
||||
ECR Public repositories for all new Pulumi releases. You can browse Pulumi images in the Amazon ECR gallery here:
|
||||
[https://gallery.ecr.aws/?searchTerm=pulumi](https://gallery.ecr.aws/?searchTerm=pulumi).
|
||||
|
||||
## Try it out!
|
||||
|
||||
Here’s how easy it is to grab the latest Pulumi container images from the Amazon ECR Public repository:
|
||||
|
||||
```bash
|
||||
$ docker pull public.ecr.aws/pulumi/pulumi:latest
|
||||
```
|
||||
|
||||
To grab the latest language runtime specific containers, run the following commands:
|
||||
|
||||
Python:
|
||||
|
||||
```bash
|
||||
$ docker pull public.ecr.aws/pulumi/pulumi-python:latest
|
||||
```
|
||||
|
||||
Go:
|
||||
|
||||
```bash
|
||||
$ docker pull public.ecr.aws/pulumi/pulumi-go:latest
|
||||
```
|
||||
|
||||
TypeScript / JavaScript:
|
||||
|
||||
```bash
|
||||
$ docker pull public.ecr.aws/pulumi/pulumi-nodejs:latest
|
||||
```
|
||||
|
||||
DotNet:
|
||||
|
||||
```bash
|
||||
$ docker pull public.ecr.aws/pulumi/pulumi-dotnet:latest
|
||||
```
|
||||
|
||||
Finally, you can grab the latest official image for the Pulumi Kubernetes Operator with this command:
|
||||
|
||||
```bash
|
||||
$ docker pull public.ecr.aws/pulumi/pulumi-kubernetes-operator:latest
|
||||
```
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user